summaryrefslogtreecommitdiff
path: root/tests/unit/src/android/net/apf/ApfTest.java
blob: 5c6a906d79382e5e54ca9b280be351efeb8cb510 (plain)
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
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.net.apf;

import static android.net.apf.ApfV4Generator.APF_VERSION_4;
import static android.net.apf.ApfV4Generator.DROP_LABEL;
import static android.net.apf.ApfV4Generator.PASS_LABEL;
import static android.net.apf.ApfV4Generator.Register.R0;
import static android.net.apf.ApfV4Generator.Register.R1;
import static android.net.apf.ApfJniUtils.compareBpfApf;
import static android.net.apf.ApfJniUtils.compileToBpf;
import static android.net.apf.ApfJniUtils.dropsAllPackets;
import static android.net.apf.ApfTestUtils.DROP;
import static android.net.apf.ApfTestUtils.MIN_PKT_SIZE;
import static android.net.apf.ApfTestUtils.PASS;
import static android.net.apf.ApfTestUtils.assertProgramEquals;
import static android.os.PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED;
import static android.os.PowerManager.ACTION_DEVICE_LIGHT_IDLE_MODE_CHANGED;
import static android.system.OsConstants.ARPHRD_ETHER;
import static android.system.OsConstants.ETH_P_ARP;
import static android.system.OsConstants.ETH_P_IP;
import static android.system.OsConstants.ETH_P_IPV6;
import static android.system.OsConstants.IPPROTO_ICMPV6;
import static android.system.OsConstants.IPPROTO_IPV6;
import static android.system.OsConstants.IPPROTO_TCP;
import static android.system.OsConstants.IPPROTO_UDP;

import static com.android.net.module.util.HexDump.hexStringToByteArray;
import static com.android.net.module.util.HexDump.toHexString;
import static com.android.net.module.util.NetworkStackConstants.ICMPV6_ECHO_REQUEST_TYPE;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.InetAddresses;
import android.net.IpPrefix;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.MacAddress;
import android.net.NattKeepalivePacketDataParcelable;
import android.net.TcpKeepalivePacketDataParcelable;
import android.net.apf.ApfCounterTracker.Counter;
import android.net.apf.ApfFilter.ApfConfiguration;
import android.net.apf.ApfTestUtils.MockIpClientCallback;
import android.net.apf.ApfTestUtils.TestApfFilter;
import android.net.apf.ApfTestUtils.TestLegacyApfFilter;
import android.net.apf.ApfV4Generator.IllegalInstructionException;
import android.net.metrics.IpConnectivityLog;
import android.os.Build;
import android.os.PowerManager;
import android.stats.connectivity.NetworkQuirkEvent;
import android.system.ErrnoException;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.ArrayMap;
import android.util.Log;
import android.util.Pair;

import androidx.test.InstrumentationRegistry;
import androidx.test.filters.SmallTest;

import com.android.internal.util.HexDump;
import com.android.net.module.util.DnsPacket;
import com.android.net.module.util.Inet4AddressUtils;
import com.android.net.module.util.NetworkStackConstants;
import com.android.net.module.util.PacketBuilder;
import com.android.networkstack.metrics.ApfSessionInfoMetrics;
import com.android.networkstack.metrics.IpClientRaInfoMetrics;
import com.android.networkstack.metrics.NetworkQuirkMetrics;
import com.android.server.networkstack.tests.R;
import com.android.testutils.DevSdkIgnoreRule;
import com.android.testutils.DevSdkIgnoreRunner;

import libcore.io.Streams;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Tests for APF program generator and interpreter.
 *
 * The test cases will be executed by both APFv4 and APFv6 interpreter.
 */
@RunWith(DevSdkIgnoreRunner.class)
@SmallTest
public class ApfTest {
    private static final int MIN_APF_VERSION = 2;

    @Rule
    public DevSdkIgnoreRule mDevSdkIgnoreRule = new DevSdkIgnoreRule();
    // Indicates which apf interpreter to run.
    @Parameterized.Parameter()
    public int mApfVersion;

    @Parameterized.Parameters
    public static Iterable<? extends Object> data() {
        return Arrays.asList(4, 6);
    }

    @Mock private Context mContext;
    @Mock
    private ApfFilter.Dependencies mDependencies;
    @Mock private PowerManager mPowerManager;
    @Mock private IpConnectivityLog mIpConnectivityLog;
    @Mock private NetworkQuirkMetrics mNetworkQuirkMetrics;
    @Mock private ApfSessionInfoMetrics mApfSessionInfoMetrics;
    @Mock private IpClientRaInfoMetrics mIpClientRaInfoMetrics;
    @Mock private ApfFilter.Clock mClock;
    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        doReturn(mPowerManager).when(mContext).getSystemService(PowerManager.class);
        doReturn(mApfSessionInfoMetrics).when(mDependencies).getApfSessionInfoMetrics();
        doReturn(mIpClientRaInfoMetrics).when(mDependencies).getIpClientRaInfoMetrics();
    }

    private static final String TAG = "ApfTest";
    // Expected return codes from APF interpreter.
    private static final ApfCapabilities MOCK_APF_CAPABILITIES =
            new ApfCapabilities(2, 4096, ARPHRD_ETHER);

    private static final boolean DROP_MULTICAST = true;
    private static final boolean ALLOW_MULTICAST = false;

    private static final boolean DROP_802_3_FRAMES = true;
    private static final boolean ALLOW_802_3_FRAMES = false;

    private static final int MIN_RDNSS_LIFETIME_SEC = 0;
    private static final int MIN_METRICS_SESSION_DURATIONS_MS = 300_000;

    // Constants for opcode encoding
    private static final byte LI_OP   = (byte)(13 << 3);
    private static final byte LDDW_OP = (byte)(22 << 3);
    private static final byte STDW_OP = (byte)(23 << 3);
    private static final byte SIZE0   = (byte)(0 << 1);
    private static final byte SIZE8   = (byte)(1 << 1);
    private static final byte SIZE16  = (byte)(2 << 1);
    private static final byte SIZE32  = (byte)(3 << 1);
    private static final byte R1_REG = 1;

    private static ApfConfiguration getDefaultConfig() {
        ApfFilter.ApfConfiguration config = new ApfConfiguration();
        config.apfCapabilities = MOCK_APF_CAPABILITIES;
        config.multicastFilter = ALLOW_MULTICAST;
        config.ieee802_3Filter = ALLOW_802_3_FRAMES;
        config.ethTypeBlackList = new int[0];
        config.minRdnssLifetimeSec = MIN_RDNSS_LIFETIME_SEC;
        config.minRdnssLifetimeSec = 67;
        config.minMetricsSessionDurationMs = MIN_METRICS_SESSION_DURATIONS_MS;
        return config;
    }

    private void assertPass(ApfV4Generator gen) throws ApfV4Generator.IllegalInstructionException {
        ApfTestUtils.assertPass(mApfVersion, gen);
    }

    private void assertDrop(ApfV4Generator gen) throws ApfV4Generator.IllegalInstructionException {
        ApfTestUtils.assertDrop(mApfVersion, gen);
    }

    private void assertPass(byte[] program, byte[] packet) {
        ApfTestUtils.assertPass(mApfVersion, program, packet);
    }

    private void assertDrop(byte[] program, byte[] packet) {
        ApfTestUtils.assertDrop(mApfVersion, program, packet);
    }

    private void assertPass(byte[] program, byte[] packet, int filterAge) {
        ApfTestUtils.assertPass(mApfVersion, program, packet, filterAge);
    }

    private void assertDrop(byte[] program, byte[] packet, int filterAge) {
        ApfTestUtils.assertDrop(mApfVersion, program, packet, filterAge);
    }

    private void assertPass(ApfV4Generator gen, byte[] packet, int filterAge)
            throws ApfV4Generator.IllegalInstructionException {
        ApfTestUtils.assertPass(mApfVersion, gen, packet, filterAge);
    }

    private void assertDrop(ApfV4Generator gen, byte[] packet, int filterAge)
            throws ApfV4Generator.IllegalInstructionException {
        ApfTestUtils.assertDrop(mApfVersion, gen, packet, filterAge);
    }

    private void assertDataMemoryContents(int expected, byte[] program, byte[] packet,
            byte[] data, byte[] expectedData) throws Exception {
        ApfTestUtils.assertDataMemoryContents(mApfVersion, expected, program, packet, data,
                expectedData);
    }

    private void assertVerdict(String msg, int expected, byte[] program,
            byte[] packet, int filterAge) {
        ApfTestUtils.assertVerdict(mApfVersion, msg, expected, program, packet, filterAge);
    }

    private void assertVerdict(int expected, byte[] program, byte[] packet) {
        ApfTestUtils.assertVerdict(mApfVersion, expected, program, packet);
    }

    /**
     * Test each instruction by generating a program containing the instruction,
     * generating bytecode for that program and running it through the
     * interpreter to verify it functions correctly.
     */
    @Test
    public void testApfInstructions() throws IllegalInstructionException {
        // Empty program should pass because having the program counter reach the
        // location immediately after the program indicates the packet should be
        // passed to the AP.
        ApfV4Generator gen = new ApfV4Generator(MIN_APF_VERSION);
        assertPass(gen);

        // Test jumping to pass label.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addJump(PASS_LABEL);
        byte[] program = gen.generate();
        assertEquals(1, program.length);
        assertEquals((14 << 3) | (0 << 1) | 0, program[0]);
        assertPass(program, new byte[MIN_PKT_SIZE], 0);

        // Test jumping to drop label.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addJump(DROP_LABEL);
        program = gen.generate();
        assertEquals(2, program.length);
        assertEquals((14 << 3) | (1 << 1) | 0, program[0]);
        assertEquals(1, program[1]);
        assertDrop(program, new byte[15], 15);

        // Test jumping if equal to 0.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addJumpIfR0Equals(0, DROP_LABEL);
        assertDrop(gen);

        // Test jumping if not equal to 0.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addJumpIfR0NotEquals(0, DROP_LABEL);
        assertPass(gen);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1);
        gen.addJumpIfR0NotEquals(0, DROP_LABEL);
        assertDrop(gen);

        // Test jumping if registers equal.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addJumpIfR0EqualsR1(DROP_LABEL);
        assertDrop(gen);

        // Test jumping if registers not equal.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addJumpIfR0NotEqualsR1(DROP_LABEL);
        assertPass(gen);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1);
        gen.addJumpIfR0NotEqualsR1(DROP_LABEL);
        assertDrop(gen);

        // Test load immediate.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1234567890);
        gen.addJumpIfR0Equals(1234567890, DROP_LABEL);
        assertDrop(gen);

        // Test add.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addAdd(1234567890);
        gen.addJumpIfR0Equals(1234567890, DROP_LABEL);
        assertDrop(gen);

        // Test add with a small signed negative value.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addAdd(-1);
        gen.addJumpIfR0Equals(-1, DROP_LABEL);
        assertDrop(gen);

        // Test subtract.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addAdd(-1234567890);
        gen.addJumpIfR0Equals(-1234567890, DROP_LABEL);
        assertDrop(gen);

        // Test or.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addOr(1234567890);
        gen.addJumpIfR0Equals(1234567890, DROP_LABEL);
        assertDrop(gen);

        // Test and.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1234567890);
        gen.addAnd(123456789);
        gen.addJumpIfR0Equals(1234567890 & 123456789, DROP_LABEL);
        assertDrop(gen);

        // Test left shift.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1234567890);
        gen.addLeftShift(1);
        gen.addJumpIfR0Equals(1234567890 << 1, DROP_LABEL);
        assertDrop(gen);

        // Test right shift.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1234567890);
        gen.addRightShift(1);
        gen.addJumpIfR0Equals(1234567890 >> 1, DROP_LABEL);
        assertDrop(gen);

        // Test multiply.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 123456789);
        gen.addMul(2);
        gen.addJumpIfR0Equals(123456789 * 2, DROP_LABEL);
        assertDrop(gen);

        // Test divide.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1234567890);
        gen.addDiv(2);
        gen.addJumpIfR0Equals(1234567890 / 2, DROP_LABEL);
        assertDrop(gen);

        // Test divide by zero.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addDiv(0);
        gen.addJump(DROP_LABEL);
        assertPass(gen);

        // Test add.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R1, 1234567890);
        gen.addAddR1();
        gen.addJumpIfR0Equals(1234567890, DROP_LABEL);
        assertDrop(gen);

        // Test subtract.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R1, -1234567890);
        gen.addAddR1();
        gen.addJumpIfR0Equals(-1234567890, DROP_LABEL);
        assertDrop(gen);

        // Test or.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R1, 1234567890);
        gen.addOrR1();
        gen.addJumpIfR0Equals(1234567890, DROP_LABEL);
        assertDrop(gen);

        // Test and.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1234567890);
        gen.addLoadImmediate(R1, 123456789);
        gen.addAndR1();
        gen.addJumpIfR0Equals(1234567890 & 123456789, DROP_LABEL);
        assertDrop(gen);

        // Test left shift.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1234567890);
        gen.addLoadImmediate(R1, 1);
        gen.addLeftShiftR1();
        gen.addJumpIfR0Equals(1234567890 << 1, DROP_LABEL);
        assertDrop(gen);

        // Test right shift.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1234567890);
        gen.addLoadImmediate(R1, -1);
        gen.addLeftShiftR1();
        gen.addJumpIfR0Equals(1234567890 >> 1, DROP_LABEL);
        assertDrop(gen);

        // Test multiply.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 123456789);
        gen.addLoadImmediate(R1, 2);
        gen.addMulR1();
        gen.addJumpIfR0Equals(123456789 * 2, DROP_LABEL);
        assertDrop(gen);

        // Test divide.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1234567890);
        gen.addLoadImmediate(R1, 2);
        gen.addDivR1();
        gen.addJumpIfR0Equals(1234567890 / 2, DROP_LABEL);
        assertDrop(gen);

        // Test divide by zero.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addDivR1();
        gen.addJump(DROP_LABEL);
        assertPass(gen);

        // Test byte load.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoad8(R0, 1);
        gen.addJumpIfR0Equals(45, DROP_LABEL);
        assertDrop(gen, new byte[]{123,45,0,0,0,0,0,0,0,0,0,0,0,0,0}, 0);

        // Test out of bounds load.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoad8(R0, 16);
        gen.addJumpIfR0Equals(0, DROP_LABEL);
        assertPass(gen, new byte[]{123,45,0,0,0,0,0,0,0,0,0,0,0,0,0}, 0);

        // Test half-word load.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoad16(R0, 1);
        gen.addJumpIfR0Equals((45 << 8) | 67, DROP_LABEL);
        assertDrop(gen, new byte[]{123,45,67,0,0,0,0,0,0,0,0,0,0,0,0}, 0);

        // Test word load.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoad32(R0, 1);
        gen.addJumpIfR0Equals((45 << 24) | (67 << 16) | (89 << 8) | 12, DROP_LABEL);
        assertDrop(gen, new byte[]{123,45,67,89,12,0,0,0,0,0,0,0,0,0,0}, 0);

        // Test byte indexed load.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R1, 1);
        gen.addLoad8Indexed(R0, 0);
        gen.addJumpIfR0Equals(45, DROP_LABEL);
        assertDrop(gen, new byte[]{123,45,0,0,0,0,0,0,0,0,0,0,0,0,0}, 0);

        // Test out of bounds indexed load.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R1, 8);
        gen.addLoad8Indexed(R0, 8);
        gen.addJumpIfR0Equals(0, DROP_LABEL);
        assertPass(gen, new byte[]{123,45,0,0,0,0,0,0,0,0,0,0,0,0,0}, 0);

        // Test half-word indexed load.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R1, 1);
        gen.addLoad16Indexed(R0, 0);
        gen.addJumpIfR0Equals((45 << 8) | 67, DROP_LABEL);
        assertDrop(gen, new byte[]{123,45,67,0,0,0,0,0,0,0,0,0,0,0,0}, 0);

        // Test word indexed load.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R1, 1);
        gen.addLoad32Indexed(R0, 0);
        gen.addJumpIfR0Equals((45 << 24) | (67 << 16) | (89 << 8) | 12, DROP_LABEL);
        assertDrop(gen, new byte[]{123,45,67,89,12,0,0,0,0,0,0,0,0,0,0}, 0);

        // Test jumping if greater than.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addJumpIfR0GreaterThan(0, DROP_LABEL);
        assertPass(gen);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1);
        gen.addJumpIfR0GreaterThan(0, DROP_LABEL);
        assertDrop(gen);

        // Test jumping if less than.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addJumpIfR0LessThan(0, DROP_LABEL);
        assertPass(gen);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addJumpIfR0LessThan(1, DROP_LABEL);
        assertDrop(gen);

        // Test jumping if any bits set.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addJumpIfR0AnyBitsSet(3, DROP_LABEL);
        assertPass(gen);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1);
        gen.addJumpIfR0AnyBitsSet(3, DROP_LABEL);
        assertDrop(gen);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 3);
        gen.addJumpIfR0AnyBitsSet(3, DROP_LABEL);
        assertDrop(gen);

        // Test jumping if register greater than.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addJumpIfR0GreaterThanR1(DROP_LABEL);
        assertPass(gen);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 2);
        gen.addLoadImmediate(R1, 1);
        gen.addJumpIfR0GreaterThanR1(DROP_LABEL);
        assertDrop(gen);

        // Test jumping if register less than.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addJumpIfR0LessThanR1(DROP_LABEL);
        assertPass(gen);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R1, 1);
        gen.addJumpIfR0LessThanR1(DROP_LABEL);
        assertDrop(gen);

        // Test jumping if any bits set in register.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R1, 3);
        gen.addJumpIfR0AnyBitsSetR1(DROP_LABEL);
        assertPass(gen);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R1, 3);
        gen.addLoadImmediate(R0, 1);
        gen.addJumpIfR0AnyBitsSetR1(DROP_LABEL);
        assertDrop(gen);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R1, 3);
        gen.addLoadImmediate(R0, 3);
        gen.addJumpIfR0AnyBitsSetR1(DROP_LABEL);
        assertDrop(gen);

        // Test load from memory.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadFromMemory(R0, 0);
        gen.addJumpIfR0Equals(0, DROP_LABEL);
        assertDrop(gen);

        // Test store to memory.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R1, 1234567890);
        gen.addStoreToMemory(R1, 12);
        gen.addLoadFromMemory(R0, 12);
        gen.addJumpIfR0Equals(1234567890, DROP_LABEL);
        assertDrop(gen);

        // Test filter age pre-filled memory.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadFromMemory(R0, gen.FILTER_AGE_MEMORY_SLOT);
        gen.addJumpIfR0Equals(123, DROP_LABEL);
        assertDrop(gen, new byte[MIN_PKT_SIZE], 123);

        // Test packet size pre-filled memory.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadFromMemory(R0, gen.PACKET_SIZE_MEMORY_SLOT);
        gen.addJumpIfR0Equals(MIN_PKT_SIZE, DROP_LABEL);
        assertDrop(gen);

        // Test IPv4 header size pre-filled memory.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadFromMemory(R0, gen.IPV4_HEADER_SIZE_MEMORY_SLOT);
        gen.addJumpIfR0Equals(20, DROP_LABEL);
        assertDrop(gen, new byte[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0x45}, 0);

        // Test not.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1234567890);
        gen.addNot(R0);
        gen.addJumpIfR0Equals(~1234567890, DROP_LABEL);
        assertDrop(gen);

        // Test negate.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1234567890);
        gen.addNeg(R0);
        gen.addJumpIfR0Equals(-1234567890, DROP_LABEL);
        assertDrop(gen);

        // Test move.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R1, 1234567890);
        gen.addMove(R0);
        gen.addJumpIfR0Equals(1234567890, DROP_LABEL);
        assertDrop(gen);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1234567890);
        gen.addMove(R1);
        gen.addJumpIfR0Equals(1234567890, DROP_LABEL);
        assertDrop(gen);

        // Test swap.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R1, 1234567890);
        gen.addSwap();
        gen.addJumpIfR0Equals(1234567890, DROP_LABEL);
        assertDrop(gen);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1234567890);
        gen.addSwap();
        gen.addJumpIfR0Equals(0, DROP_LABEL);
        assertDrop(gen);

        // Test jump if bytes not equal.
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1);
        gen.addJumpIfBytesAtR0NotEqual(new byte[]{123}, DROP_LABEL);
        program = gen.generate();
        assertEquals(6, program.length);
        assertEquals((13 << 3) | (1 << 1) | 0, program[0]);
        assertEquals(1, program[1]);
        assertEquals(((20 << 3) | (1 << 1) | 0) - 256, program[2]);
        assertEquals(1, program[3]);
        assertEquals(1, program[4]);
        assertEquals(123, program[5]);
        assertDrop(program, new byte[MIN_PKT_SIZE], 0);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1);
        gen.addJumpIfBytesAtR0NotEqual(new byte[]{123}, DROP_LABEL);
        byte[] packet123 = {0,123,0,0,0,0,0,0,0,0,0,0,0,0,0};
        assertPass(gen, packet123, 0);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addJumpIfBytesAtR0NotEqual(new byte[]{123}, DROP_LABEL);
        assertDrop(gen, packet123, 0);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1);
        gen.addJumpIfBytesAtR0NotEqual(new byte[]{1, 2, 30, 4, 5}, DROP_LABEL);
        byte[] packet12345 = {0,1,2,3,4,5,0,0,0,0,0,0,0,0,0};
        assertDrop(gen, packet12345, 0);
        gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R0, 1);
        gen.addJumpIfBytesAtR0NotEqual(new byte[]{1, 2, 3, 4, 5}, DROP_LABEL);
        assertPass(gen, packet12345, 0);
    }

    @Test(expected = ApfV4Generator.IllegalInstructionException.class)
    public void testApfGeneratorWantsV2OrGreater() throws Exception {
        // The minimum supported APF version is 2.
        new ApfV4Generator(1);
    }

    @Test
    public void testApfDataOpcodesWantApfV3() throws IllegalInstructionException, Exception {
        ApfV4Generator gen = new ApfV4Generator(MIN_APF_VERSION);
        try {
            gen.addStoreData(R0, 0);
            fail();
        } catch (IllegalInstructionException expected) {
            /* pass */
        }
        try {
            gen.addLoadData(R0, 0);
            fail();
        } catch (IllegalInstructionException expected) {
            /* pass */
        }
    }

    /**
     * Test that the generator emits immediates using the shortest possible encoding.
     */
    @Test
    public void testImmediateEncoding() throws IllegalInstructionException {
        ApfV4Generator gen;

        // 0-byte immediate: li R0, 0
        gen = new ApfV4Generator(4);
        gen.addLoadImmediate(R0, 0);
        assertProgramEquals(new byte[]{LI_OP | SIZE0}, gen.generate());

        // 1-byte immediate: li R0, 42
        gen = new ApfV4Generator(4);
        gen.addLoadImmediate(R0, 42);
        assertProgramEquals(new byte[]{LI_OP | SIZE8, 42}, gen.generate());

        // 2-byte immediate: li R1, 0x1234
        gen = new ApfV4Generator(4);
        gen.addLoadImmediate(R1, 0x1234);
        assertProgramEquals(new byte[]{LI_OP | SIZE16 | R1_REG, 0x12, 0x34}, gen.generate());

        // 4-byte immediate: li R0, 0x12345678
        gen = new ApfV4Generator(3);
        gen.addLoadImmediate(R0, 0x12345678);
        assertProgramEquals(
                new byte[]{LI_OP | SIZE32, 0x12, 0x34, 0x56, 0x78},
                gen.generate());
    }

    /**
     * Test that the generator emits negative immediates using the shortest possible encoding.
     */
    @Test
    public void testNegativeImmediateEncoding() throws IllegalInstructionException {
        ApfV4Generator gen;

        // 1-byte negative immediate: li R0, -42
        gen = new ApfV4Generator(3);
        gen.addLoadImmediate(R0, -42);
        assertProgramEquals(new byte[]{LI_OP | SIZE8, -42}, gen.generate());

        // 2-byte negative immediate: li R1, -0x1122
        gen = new ApfV4Generator(3);
        gen.addLoadImmediate(R1, -0x1122);
        assertProgramEquals(new byte[]{LI_OP | SIZE16 | R1_REG, (byte)0xEE, (byte)0xDE},
                gen.generate());

        // 4-byte negative immediate: li R0, -0x11223344
        gen = new ApfV4Generator(3);
        gen.addLoadImmediate(R0, -0x11223344);
        assertProgramEquals(
                new byte[]{LI_OP | SIZE32, (byte)0xEE, (byte)0xDD, (byte)0xCC, (byte)0xBC},
                gen.generate());
    }

    /**
     * Test that the generator correctly emits positive and negative immediates for LDDW/STDW.
     */
    @Test
    public void testLoadStoreDataEncoding() throws IllegalInstructionException {
        ApfV4Generator gen;

        // Load data with no offset: lddw R0, [0 + r1]
        gen = new ApfV4Generator(APF_VERSION_4);
        gen.addLoadData(R0, 0);
        assertProgramEquals(new byte[]{LDDW_OP | SIZE0}, gen.generate());

        // Store data with 8bit negative offset: lddw r0, [-42 + r1]
        gen = new ApfV4Generator(APF_VERSION_4);
        gen.addStoreData(R0, -42);
        assertProgramEquals(new byte[]{STDW_OP | SIZE8, -42}, gen.generate());

        // Store data to R1 with 16bit negative offset: stdw r1, [-0x1122 + r0]
        gen = new ApfV4Generator(APF_VERSION_4);
        gen.addStoreData(R1, -0x1122);
        assertProgramEquals(new byte[]{STDW_OP | SIZE16 | R1_REG, (byte)0xEE, (byte)0xDE},
                gen.generate());

        // Load data to R1 with 32bit negative offset: lddw r1, [0xDEADBEEF + r0]
        gen = new ApfV4Generator(APF_VERSION_4);
        gen.addLoadData(R1, 0xDEADBEEF);
        assertProgramEquals(
                new byte[]{LDDW_OP | SIZE32 | R1_REG,
                        (byte)0xDE, (byte)0xAD, (byte)0xBE, (byte)0xEF},
                gen.generate());
    }

    /**
     * Test that the interpreter correctly executes STDW with a negative 8bit offset
     */
    @Test
    public void testApfDataWrite() throws IllegalInstructionException, Exception {
        byte[] packet = new byte[MIN_PKT_SIZE];
        byte[] data = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
        byte[] expected_data = data.clone();

        // No memory access instructions: should leave the data segment untouched.
        ApfV4Generator gen = new ApfV4Generator(APF_VERSION_4);
        assertDataMemoryContents(PASS, gen.generate(), packet, data, expected_data);

        // Expect value 0x87654321 to be stored starting from address -11 from the end of the
        // data buffer, in big-endian order.
        gen = new ApfV4Generator(APF_VERSION_4);
        gen.addLoadImmediate(R0, 0x87654321);
        gen.addLoadImmediate(R1, -5);
        gen.addStoreData(R0, -6);  // -5 + -6 = -11 (offset +5 with data_len=16)
        expected_data[5] = (byte)0x87;
        expected_data[6] = (byte)0x65;
        expected_data[7] = (byte)0x43;
        expected_data[8] = (byte)0x21;
        assertDataMemoryContents(PASS, gen.generate(), packet, data, expected_data);
    }

    /**
     * Test that the interpreter correctly executes LDDW with a negative 16bit offset
     */
    @Test
    public void testApfDataRead() throws IllegalInstructionException, Exception {
        // Program that DROPs if address 10 (-6) contains 0x87654321.
        ApfV4Generator gen = new ApfV4Generator(APF_VERSION_4);
        gen.addLoadImmediate(R1, 1000);
        gen.addLoadData(R0, -1006);  // 1000 + -1006 = -6 (offset +10 with data_len=16)
        gen.addJumpIfR0Equals(0x87654321, DROP_LABEL);
        byte[] program = gen.generate();
        byte[] packet = new byte[MIN_PKT_SIZE];

        // Content is incorrect (last byte does not match) -> PASS
        byte[] data = new byte[16];
        data[10] = (byte)0x87;
        data[11] = (byte)0x65;
        data[12] = (byte)0x43;
        data[13] = (byte)0x00;  // != 0x21
        byte[] expected_data = data.clone();
        assertDataMemoryContents(PASS, program, packet, data, expected_data);

        // Fix the last byte -> conditional jump taken -> DROP
        data[13] = (byte)0x21;
        expected_data = data;
        assertDataMemoryContents(DROP, program, packet, data, expected_data);
    }

    /**
     * Test that the interpreter correctly executes LDDW followed by a STDW.
     * To cover a few more edge cases, LDDW has a 0bit offset, while STDW has a positive 8bit
     * offset.
     */
    @Test
    public void testApfDataReadModifyWrite() throws IllegalInstructionException, Exception {
        ApfV4Generator gen = new ApfV4Generator(APF_VERSION_4);
        gen.addLoadImmediate(R1, -22);
        gen.addLoadData(R0, 0);  // Load from address 32 -22 + 0 = 10
        gen.addAdd(0x78453412);  // 87654321 + 78453412 = FFAA7733
        gen.addStoreData(R0, 4);  // Write back to address 32 -22 + 4 = 14

        byte[] packet = new byte[MIN_PKT_SIZE];
        byte[] data = new byte[32];
        data[10] = (byte)0x87;
        data[11] = (byte)0x65;
        data[12] = (byte)0x43;
        data[13] = (byte)0x21;
        byte[] expected_data = data.clone();
        expected_data[14] = (byte)0xFF;
        expected_data[15] = (byte)0xAA;
        expected_data[16] = (byte)0x77;
        expected_data[17] = (byte)0x33;
        assertDataMemoryContents(PASS, gen.generate(), packet, data, expected_data);
    }

    @Test
    public void testApfDataBoundChecking() throws IllegalInstructionException, Exception {
        byte[] packet = new byte[MIN_PKT_SIZE];
        byte[] data = new byte[32];
        byte[] expected_data = data;

        // Program that DROPs unconditionally. This is our the baseline.
        ApfV4Generator gen = new ApfV4Generator(APF_VERSION_4);
        gen.addLoadImmediate(R0, 3);
        gen.addLoadData(R1, 7);
        gen.addJump(DROP_LABEL);
        assertDataMemoryContents(DROP, gen.generate(), packet, data, expected_data);

        // Same program as before, but this time we're trying to load past the end of the data.
        gen = new ApfV4Generator(APF_VERSION_4);
        gen.addLoadImmediate(R0, 20);
        gen.addLoadData(R1, 15);  // 20 + 15 > 32
        gen.addJump(DROP_LABEL);  // Not reached.
        assertDataMemoryContents(PASS, gen.generate(), packet, data, expected_data);

        // Subtracting an immediate should work...
        gen = new ApfV4Generator(APF_VERSION_4);
        gen.addLoadImmediate(R0, 20);
        gen.addLoadData(R1, -4);
        gen.addJump(DROP_LABEL);
        assertDataMemoryContents(DROP, gen.generate(), packet, data, expected_data);

        // ...and underflowing simply wraps around to the end of the buffer...
        gen = new ApfV4Generator(APF_VERSION_4);
        gen.addLoadImmediate(R0, 20);
        gen.addLoadData(R1, -30);
        gen.addJump(DROP_LABEL);
        assertDataMemoryContents(DROP, gen.generate(), packet, data, expected_data);

        // ...but doesn't allow accesses before the start of the buffer
        gen = new ApfV4Generator(APF_VERSION_4);
        gen.addLoadImmediate(R0, 20);
        gen.addLoadData(R1, -1000);
        gen.addJump(DROP_LABEL);  // Not reached.
        assertDataMemoryContents(PASS, gen.generate(), packet, data, expected_data);
    }

    /**
     * Generate some BPF programs, translate them to APF, then run APF and BPF programs
     * over packet traces and verify both programs filter out the same packets.
     */
    @Test
    public void testApfAgainstBpf() throws Exception {
        String[] tcpdump_filters = new String[]{ "udp", "tcp", "icmp", "icmp6", "udp port 53",
                "arp", "dst 239.255.255.250", "arp or tcp or udp port 53", "net 192.168.1.0/24",
                "arp or icmp6 or portrange 53-54", "portrange 53-54 or portrange 100-50000",
                "tcp[tcpflags] & (tcp-ack|tcp-fin) != 0 and (ip[2:2] > 57 or icmp)" };
        String pcap_filename = stageFile(R.raw.apf);
        for (String tcpdump_filter : tcpdump_filters) {
            byte[] apf_program = Bpf2Apf.convert(compileToBpf(tcpdump_filter));
            assertTrue("Failed to match for filter: " + tcpdump_filter,
                    compareBpfApf(mApfVersion, tcpdump_filter, pcap_filename, apf_program));
        }
    }

    /**
     * Generate APF program, run pcap file though APF filter, then check all the packets in the file
     * should be dropped.
     */
    @Test
    public void testApfFilterPcapFile() throws Exception {
        final byte[] MOCK_PCAP_IPV4_ADDR = {(byte) 172, 16, 7, (byte) 151};
        String pcapFilename = stageFile(R.raw.apfPcap);
        MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        LinkAddress link = new LinkAddress(InetAddress.getByAddress(MOCK_PCAP_IPV4_ADDR), 16);
        LinkProperties lp = new LinkProperties();
        lp.addLinkAddress(link);

        ApfConfiguration config = getDefaultConfig();
        ApfCapabilities MOCK_APF_PCAP_CAPABILITIES = new ApfCapabilities(4, 1700, ARPHRD_ETHER);
        config.apfCapabilities = MOCK_APF_PCAP_CAPABILITIES;
        config.multicastFilter = DROP_MULTICAST;
        config.ieee802_3Filter = DROP_802_3_FRAMES;
        TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);
        apfFilter.setLinkProperties(lp);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();
        byte[] data = new byte[Counter.totalSize()];
        final boolean result;

        result = dropsAllPackets(mApfVersion, program, data, pcapFilename);
        Log.i(TAG, "testApfFilterPcapFile(): Data counters: " + HexDump.toHexString(data, false));

        assertTrue("Failed to drop all packets by filter. \nAPF counters:" +
            HexDump.toHexString(data, false), result);
        apfFilter.shutdown();
    }

    private static final int ETH_HEADER_LEN               = 14;
    private static final int ETH_DEST_ADDR_OFFSET         = 0;
    private static final int ETH_ETHERTYPE_OFFSET         = 12;
    private static final byte[] ETH_BROADCAST_MAC_ADDRESS =
            {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff };
    private static final byte[] ETH_MULTICAST_MDNS_v4_MAC_ADDRESS =
            {(byte) 0x01, (byte) 0x00, (byte) 0x5e, (byte) 0x00, (byte) 0x00, (byte) 0xfb};
    private static final byte[] ETH_MULTICAST_MDNS_V6_MAC_ADDRESS =
            {(byte) 0x33, (byte) 0x33, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xfb};

    private static final int IP_HEADER_OFFSET = ETH_HEADER_LEN;

    private static final int IPV4_HEADER_LEN          = 20;
    private static final int IPV4_TOTAL_LENGTH_OFFSET = IP_HEADER_OFFSET + 2;
    private static final int IPV4_PROTOCOL_OFFSET     = IP_HEADER_OFFSET + 9;
    private static final int IPV4_SRC_ADDR_OFFSET     = IP_HEADER_OFFSET + 12;
    private static final int IPV4_DEST_ADDR_OFFSET    = IP_HEADER_OFFSET + 16;

    private static final int IPV4_TCP_HEADER_LEN           = 20;
    private static final int IPV4_TCP_HEADER_OFFSET        = IP_HEADER_OFFSET + IPV4_HEADER_LEN;
    private static final int IPV4_TCP_SRC_PORT_OFFSET      = IPV4_TCP_HEADER_OFFSET + 0;
    private static final int IPV4_TCP_DEST_PORT_OFFSET     = IPV4_TCP_HEADER_OFFSET + 2;
    private static final int IPV4_TCP_SEQ_NUM_OFFSET       = IPV4_TCP_HEADER_OFFSET + 4;
    private static final int IPV4_TCP_ACK_NUM_OFFSET       = IPV4_TCP_HEADER_OFFSET + 8;
    private static final int IPV4_TCP_HEADER_LENGTH_OFFSET = IPV4_TCP_HEADER_OFFSET + 12;
    private static final int IPV4_TCP_HEADER_FLAG_OFFSET   = IPV4_TCP_HEADER_OFFSET + 13;

    private static final int IPV4_UDP_HEADER_OFFSET    = IP_HEADER_OFFSET + IPV4_HEADER_LEN;
    private static final int IPV4_UDP_SRC_PORT_OFFSET  = IPV4_UDP_HEADER_OFFSET + 0;
    private static final int IPV4_UDP_DEST_PORT_OFFSET = IPV4_UDP_HEADER_OFFSET + 2;
    private static final int IPV4_UDP_LENGTH_OFFSET    = IPV4_UDP_HEADER_OFFSET + 4;
    private static final int IPV4_UDP_PAYLOAD_OFFSET   = IPV4_UDP_HEADER_OFFSET + 8;
    private static final byte[] IPV4_BROADCAST_ADDRESS =
            {(byte) 255, (byte) 255, (byte) 255, (byte) 255};

    private static final int IPV6_HEADER_LEN             = 40;
    private static final int IPV6_PAYLOAD_LENGTH_OFFSET  = IP_HEADER_OFFSET + 4;
    private static final int IPV6_NEXT_HEADER_OFFSET     = IP_HEADER_OFFSET + 6;
    private static final int IPV6_SRC_ADDR_OFFSET        = IP_HEADER_OFFSET + 8;
    private static final int IPV6_DEST_ADDR_OFFSET       = IP_HEADER_OFFSET + 24;
    private static final int IPV6_PAYLOAD_OFFSET = IP_HEADER_OFFSET + IPV6_HEADER_LEN;
    private static final int IPV6_TCP_SRC_PORT_OFFSET    = IPV6_PAYLOAD_OFFSET + 0;
    private static final int IPV6_TCP_DEST_PORT_OFFSET   = IPV6_PAYLOAD_OFFSET + 2;
    private static final int IPV6_TCP_SEQ_NUM_OFFSET     = IPV6_PAYLOAD_OFFSET + 4;
    private static final int IPV6_TCP_ACK_NUM_OFFSET     = IPV6_PAYLOAD_OFFSET + 8;
    // The IPv6 all nodes address ff02::1
    private static final byte[] IPV6_ALL_NODES_ADDRESS   =
            { (byte) 0xff, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
    private static final byte[] IPV6_ALL_ROUTERS_ADDRESS =
            { (byte) 0xff, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2 };
    private static final byte[] IPV6_SOLICITED_NODE_MULTICAST_ADDRESS = {
            (byte) 0xff, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            (byte) 0xff, (byte) 0xab, (byte) 0xcd, (byte) 0xef,
    };

    private static final int ICMP6_TYPE_OFFSET           = IP_HEADER_OFFSET + IPV6_HEADER_LEN;
    private static final int ICMP6_ROUTER_SOLICITATION   = 133;
    private static final int ICMP6_ROUTER_ADVERTISEMENT  = 134;
    private static final int ICMP6_NEIGHBOR_SOLICITATION = 135;
    private static final int ICMP6_NEIGHBOR_ANNOUNCEMENT = 136;

    private static final int ICMP6_RA_HEADER_LEN = 16;
    private static final int ICMP6_RA_CHECKSUM_OFFSET =
            IP_HEADER_OFFSET + IPV6_HEADER_LEN + 2;
    private static final int ICMP6_RA_ROUTER_LIFETIME_OFFSET =
            IP_HEADER_OFFSET + IPV6_HEADER_LEN + 6;
    private static final int ICMP6_RA_REACHABLE_TIME_OFFSET =
            IP_HEADER_OFFSET + IPV6_HEADER_LEN + 8;
    private static final int ICMP6_RA_RETRANSMISSION_TIMER_OFFSET =
            IP_HEADER_OFFSET + IPV6_HEADER_LEN + 12;
    private static final int ICMP6_RA_OPTION_OFFSET =
            IP_HEADER_OFFSET + IPV6_HEADER_LEN + ICMP6_RA_HEADER_LEN;

    private static final int ICMP6_PREFIX_OPTION_TYPE                      = 3;
    private static final int ICMP6_PREFIX_OPTION_LEN                       = 32;
    private static final int ICMP6_PREFIX_OPTION_VALID_LIFETIME_OFFSET     = 4;
    private static final int ICMP6_PREFIX_OPTION_PREFERRED_LIFETIME_OFFSET = 8;

    // From RFC6106: Recursive DNS Server option
    private static final int ICMP6_RDNSS_OPTION_TYPE = 25;
    // From RFC6106: DNS Search List option
    private static final int ICMP6_DNSSL_OPTION_TYPE = 31;

    // From RFC4191: Route Information option
    private static final int ICMP6_ROUTE_INFO_OPTION_TYPE = 24;
    // Above three options all have the same format:
    private static final int ICMP6_4_BYTE_OPTION_LEN      = 8;
    private static final int ICMP6_4_BYTE_LIFETIME_OFFSET = 4;
    private static final int ICMP6_4_BYTE_LIFETIME_LEN    = 4;

    private static final int UDP_HEADER_LEN              = 8;
    private static final int UDP_DESTINATION_PORT_OFFSET = ETH_HEADER_LEN + 22;

    private static final int DHCP_CLIENT_PORT       = 68;
    private static final int DHCP_CLIENT_MAC_OFFSET = ETH_HEADER_LEN + UDP_HEADER_LEN + 48;

    private static final int ARP_HEADER_OFFSET          = ETH_HEADER_LEN;
    private static final byte[] ARP_IPV4_REQUEST_HEADER = {
            0, 1, // Hardware type: Ethernet (1)
            8, 0, // Protocol type: IP (0x0800)
            6,    // Hardware size: 6
            4,    // Protocol size: 4
            0, 1  // Opcode: request (1)
    };
    private static final byte[] ARP_IPV4_REPLY_HEADER = {
            0, 1, // Hardware type: Ethernet (1)
            8, 0, // Protocol type: IP (0x0800)
            6,    // Hardware size: 6
            4,    // Protocol size: 4
            0, 2  // Opcode: reply (2)
    };
    private static final int ARP_SOURCE_IP_ADDRESS_OFFSET = ARP_HEADER_OFFSET + 14;
    private static final int ARP_TARGET_IP_ADDRESS_OFFSET = ARP_HEADER_OFFSET + 24;

    private static final byte[] MOCK_IPV4_ADDR           = {10, 0, 0, 1};
    private static final byte[] MOCK_BROADCAST_IPV4_ADDR = {10, 0, 31, (byte) 255}; // prefix = 19
    private static final byte[] MOCK_MULTICAST_IPV4_ADDR = {(byte) 224, 0, 0, 1};
    private static final byte[] ANOTHER_IPV4_ADDR        = {10, 0, 0, 2};
    private static final byte[] IPV4_SOURCE_ADDR         = {10, 0, 0, 3};
    private static final byte[] ANOTHER_IPV4_SOURCE_ADDR = {(byte) 192, 0, 2, 1};
    private static final byte[] BUG_PROBE_SOURCE_ADDR1   = {0, 0, 1, 2};
    private static final byte[] BUG_PROBE_SOURCE_ADDR2   = {3, 4, 0, 0};
    private static final byte[] IPV4_ANY_HOST_ADDR       = {0, 0, 0, 0};
    private static final byte[] IPV4_MDNS_MULTICAST_ADDR = {(byte) 224, 0, 0, (byte) 251};
    private static final byte[] IPV6_MDNS_MULTICAST_ADDR =
            {(byte) 0xff, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xfb};
    private static final int IPV6_UDP_DEST_PORT_OFFSET = IPV6_PAYLOAD_OFFSET + 2;
    private static final int MDNS_UDP_PORT = 5353;

    private static void setIpv4VersionFields(ByteBuffer packet) {
        packet.putShort(ETH_ETHERTYPE_OFFSET, (short) ETH_P_IP);
        packet.put(IP_HEADER_OFFSET, (byte) 0x45);
    }

    private static void setIpv6VersionFields(ByteBuffer packet) {
        packet.putShort(ETH_ETHERTYPE_OFFSET, (short) ETH_P_IPV6);
        packet.put(IP_HEADER_OFFSET, (byte) 0x60);
    }

    private static ByteBuffer makeIpv4Packet(int proto) {
        ByteBuffer packet = ByteBuffer.wrap(new byte[100]);
        setIpv4VersionFields(packet);
        packet.put(IPV4_PROTOCOL_OFFSET, (byte) proto);
        return packet;
    }

    private static ByteBuffer makeIpv6Packet(int nextHeader) {
        ByteBuffer packet = ByteBuffer.wrap(new byte[100]);
        setIpv6VersionFields(packet);
        packet.put(IPV6_NEXT_HEADER_OFFSET, (byte) nextHeader);
        return packet;
    }

    @Test
    public void testApfFilterIPv4() throws Exception {
        MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        LinkAddress link = new LinkAddress(InetAddress.getByAddress(MOCK_IPV4_ADDR), 19);
        LinkProperties lp = new LinkProperties();
        lp.addLinkAddress(link);

        ApfConfiguration config = getDefaultConfig();
        config.multicastFilter = DROP_MULTICAST;
        TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);
        apfFilter.setLinkProperties(lp);

        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        // Verify empty packet of 100 zero bytes is passed
        ByteBuffer packet = ByteBuffer.wrap(new byte[100]);
        assertPass(program, packet.array());

        // Verify unicast IPv4 packet is passed
        put(packet, ETH_DEST_ADDR_OFFSET, TestApfFilter.MOCK_MAC_ADDR);
        packet.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_IP);
        put(packet, IPV4_DEST_ADDR_OFFSET, MOCK_IPV4_ADDR);
        assertPass(program, packet.array());

        // Verify L2 unicast to IPv4 broadcast addresses is dropped (b/30231088)
        put(packet, IPV4_DEST_ADDR_OFFSET, IPV4_BROADCAST_ADDRESS);
        assertDrop(program, packet.array());
        put(packet, IPV4_DEST_ADDR_OFFSET, MOCK_BROADCAST_IPV4_ADDR);
        assertDrop(program, packet.array());

        // Verify multicast/broadcast IPv4, not DHCP to us, is dropped
        put(packet, ETH_DEST_ADDR_OFFSET, ETH_BROADCAST_MAC_ADDRESS);
        assertDrop(program, packet.array());
        packet.put(IP_HEADER_OFFSET, (byte) 0x45);
        assertDrop(program, packet.array());
        packet.put(IPV4_PROTOCOL_OFFSET, (byte)IPPROTO_UDP);
        assertDrop(program, packet.array());
        packet.putShort(UDP_DESTINATION_PORT_OFFSET, (short)DHCP_CLIENT_PORT);
        assertDrop(program, packet.array());
        put(packet, IPV4_DEST_ADDR_OFFSET, MOCK_MULTICAST_IPV4_ADDR);
        assertDrop(program, packet.array());
        put(packet, IPV4_DEST_ADDR_OFFSET, MOCK_BROADCAST_IPV4_ADDR);
        assertDrop(program, packet.array());
        put(packet, IPV4_DEST_ADDR_OFFSET, IPV4_BROADCAST_ADDRESS);
        assertDrop(program, packet.array());

        // Verify broadcast IPv4 DHCP to us is passed
        put(packet, DHCP_CLIENT_MAC_OFFSET, TestApfFilter.MOCK_MAC_ADDR);
        assertPass(program, packet.array());

        // Verify unicast IPv4 DHCP to us is passed
        put(packet, ETH_DEST_ADDR_OFFSET, TestApfFilter.MOCK_MAC_ADDR);
        assertPass(program, packet.array());

        apfFilter.shutdown();
    }

    @Test
    public void testApfFilterIPv6() throws Exception {
        MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        ApfConfiguration config = getDefaultConfig();
        TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        // Verify empty IPv6 packet is passed
        ByteBuffer packet = makeIpv6Packet(IPPROTO_UDP);
        assertPass(program, packet.array());

        // Verify empty ICMPv6 packet is passed
        packet.put(IPV6_NEXT_HEADER_OFFSET, (byte)IPPROTO_ICMPV6);
        assertPass(program, packet.array());

        // Verify empty ICMPv6 NA packet is passed
        packet.put(ICMP6_TYPE_OFFSET, (byte)ICMP6_NEIGHBOR_ANNOUNCEMENT);
        assertPass(program, packet.array());

        // Verify ICMPv6 NA to ff02::1 is dropped
        put(packet, IPV6_DEST_ADDR_OFFSET, IPV6_ALL_NODES_ADDRESS);
        assertDrop(program, packet.array());

        // Verify ICMPv6 NA to ff02::2 is dropped
        put(packet, IPV6_DEST_ADDR_OFFSET, IPV6_ALL_ROUTERS_ADDRESS);
        assertDrop(program, packet.array());

        // Verify ICMPv6 NA to Solicited-Node Multicast is passed
        put(packet, IPV6_DEST_ADDR_OFFSET, IPV6_SOLICITED_NODE_MULTICAST_ADDRESS);
        assertPass(program, packet.array());

        // Verify ICMPv6 RS to any is dropped
        packet.put(ICMP6_TYPE_OFFSET, (byte)ICMP6_ROUTER_SOLICITATION);
        assertDrop(program, packet.array());
        put(packet, IPV6_DEST_ADDR_OFFSET, IPV6_ALL_ROUTERS_ADDRESS);
        assertDrop(program, packet.array());

        apfFilter.shutdown();
    }

    private static void fillQuestionSection(ByteBuffer buf, String... qnames) throws IOException {
        buf.put(new DnsPacket.DnsHeader(0 /* id */, 0 /* flags */, qnames.length, 0 /* ancount */)
                .getBytes());
        for (String qname : qnames) {
            buf.put(DnsPacket.DnsRecord.makeQuestion(qname, 0 /* nsType */, 0 /* nsClass */)
                    .getBytes());
        }
    }

    private static byte[] makeMdnsV4Packet(String... qnames) throws IOException {
        final ByteBuffer buf = ByteBuffer.wrap(new byte[256]);
        final PacketBuilder builder = new PacketBuilder(buf);
        builder.writeL2Header(MacAddress.fromString("11:22:33:44:55:66"),
                MacAddress.fromBytes(ETH_MULTICAST_MDNS_v4_MAC_ADDRESS),
                (short) ETH_P_IP);
        builder.writeIpv4Header((byte) 0 /* tos */, (short) 0 /* id */,
                (short) 0 /* flagsAndFragmentOffset */, (byte) 0 /* ttl */, (byte) IPPROTO_UDP,
                (Inet4Address) Inet4Address.getByAddress(IPV4_SOURCE_ADDR),
                (Inet4Address) Inet4Address.getByAddress(IPV4_MDNS_MULTICAST_ADDR));
        builder.writeUdpHeader((short) MDNS_UDP_PORT, (short) MDNS_UDP_PORT);
        fillQuestionSection(buf, qnames);
        return builder.finalizePacket().array();
    }

    private static byte[] makeMdnsV6Packet(String... qnames) throws IOException {
        ByteBuffer buf = ByteBuffer.wrap(new byte[256]);
        final PacketBuilder builder = new PacketBuilder(buf);
        builder.writeL2Header(MacAddress.fromString("11:22:33:44:55:66"),
                MacAddress.fromBytes(ETH_MULTICAST_MDNS_V6_MAC_ADDRESS),
                (short) ETH_P_IPV6);
        builder.writeIpv6Header(0x680515ca /* vtf */, (byte) IPPROTO_UDP, (short) 0 /* hopLimit */,
                (Inet6Address) InetAddress.getByAddress(IPV6_ANOTHER_ADDR),
                (Inet6Address) Inet6Address.getByAddress(IPV6_MDNS_MULTICAST_ADDR));
        builder.writeUdpHeader((short) MDNS_UDP_PORT, (short) MDNS_UDP_PORT);
        fillQuestionSection(buf, qnames);
        return builder.finalizePacket().array();
    }

    private static void putLabel(ByteBuffer buf, String label) {
        final byte[] bytes = label.getBytes(StandardCharsets.UTF_8);
        buf.put((byte) bytes.length);
        buf.put(bytes);
    }

    private static void putPointer(ByteBuffer buf, int offset) {
        short pointer = (short) (offset | 0xc000);
        buf.putShort(pointer);
    }


    // Simplistic DNS compression code that intentionally does not depend on production code.
    private static List<Pair<Integer, String>> getDnsLabels(int startOffset, String... names) {
        // Maps all possible name suffixes to packet offsets.
        final HashMap<String, Integer> mPointerOffsets = new HashMap<>();
        final List<Pair<Integer, String>> out = new ArrayList<>();
        int offset = startOffset;
        for (int i = 0; i < names.length; i++) {
            String name = names[i];
            while (true) {
                if (name.length() == 0) {
                    out.add(label(""));
                    offset += 1 + 4;  // 1-byte label, DNS query
                    break;
                }

                final int pointerOffset = mPointerOffsets.getOrDefault(name, -1);
                if (pointerOffset != -1) {
                    out.add(pointer(pointerOffset));
                    offset += 2 + 4; // 2-byte pointer, DNS query
                    break;
                }

                mPointerOffsets.put(name, offset);

                final int indexOfDot = name.indexOf(".");
                final String label;
                if (indexOfDot == -1) {
                    label = name;
                    name = "";
                } else {
                    label = name.substring(0, indexOfDot);
                    name = name.substring(indexOfDot + 1);
                }
                out.add(label(label));
                offset += 1 + label.length();
            }
        }
        return out;
    }

    static Pair<Integer, String> label(String label) {
        return Pair.create(label.length(), label);
    }

    static Pair<Integer, String> pointer(int offset) {
        return Pair.create(0xc000 | offset, null);
    }

    @Test
    public void testGetDnsLabels() throws Exception {
        int startOffset = 12;
        List<Pair<Integer, String>> actual = getDnsLabels(startOffset, "myservice.tcp.local");
        assertEquals(4, actual.size());
        assertEquals(label("myservice"), actual.get(0));
        assertEquals(label("tcp"), actual.get(1));
        assertEquals(label("local"), actual.get(2));
        assertEquals(label(""), actual.get(3));

        startOffset = 30;
        actual = getDnsLabels(startOffset,
                "myservice.tcp.local", "foo.tcp.local", "myhostname.local", "bar.udp.local",
                "foo.myhostname.local");
        final int tcpLocalOffset = startOffset + 1 + "myservice".length();
        final int localOffset = startOffset + 1 + "myservice".length() + 1 + "tcp".length();
        final int myhostnameLocalOffset = 30
                + 1 + "myservice".length() + 1 + "tcp".length() + 1 + "local".length() + 1 + 4
                + 1 + "foo".length() + 2 + 4;

        assertEquals(13, actual.size());
        assertEquals(label("myservice"), actual.get(0));
        assertEquals(label("tcp"), actual.get(1));
        assertEquals(label("local"), actual.get(2));
        assertEquals(label(""), actual.get(3));
        assertEquals(label("foo"), actual.get(4));
        assertEquals(pointer(tcpLocalOffset), actual.get(5));
        assertEquals(label("myhostname"), actual.get(6));
        assertEquals(pointer(localOffset), actual.get(7));
        assertEquals(label("bar"), actual.get(8));
        assertEquals(label("udp"), actual.get(9));
        assertEquals(pointer(localOffset), actual.get(10));
        assertEquals(label("foo"), actual.get(11));
        assertEquals(pointer(myhostnameLocalOffset), actual.get(12));

    }

    private static byte[] makeMdnsCompressedV6Packet(String... names) throws IOException {
        ByteBuffer questions = ByteBuffer.allocate(1500);
        questions.put(new DnsPacket.DnsHeader(123, 0, names.length, 0).getBytes());
        final List<Pair<Integer, String>> labels = getDnsLabels(questions.position(), names);
        for (Pair<Integer, String> label : labels) {
            final String name = label.second;
            if (name == null) {
                putPointer(questions, label.first);
            } else {
                putLabel(questions, name);
            }
            if (TextUtils.isEmpty(name)) {
                questions.put(new byte[4]);
            }
        }
        questions.flip();

        ByteBuffer buf = PacketBuilder.allocate(/*hasEther=*/ true, IPPROTO_IPV6, IPPROTO_UDP,
                questions.limit());
        final PacketBuilder builder = new PacketBuilder(buf);
        builder.writeL2Header(MacAddress.fromString("11:22:33:44:55:66"),
                MacAddress.fromBytes(ETH_MULTICAST_MDNS_V6_MAC_ADDRESS),
                (short) ETH_P_IPV6);
        builder.writeIpv6Header(0x680515ca /* vtf */, (byte) IPPROTO_UDP, (short) 0 /* hopLimit */,
                (Inet6Address) InetAddress.getByAddress(IPV6_ANOTHER_ADDR),
                (Inet6Address) Inet6Address.getByAddress(IPV6_MDNS_MULTICAST_ADDR));
        builder.writeUdpHeader((short) MDNS_UDP_PORT, (short) MDNS_UDP_PORT);

        buf.put(questions);

        return builder.finalizePacket().array();
    }

    private static byte[] makeMdnsCompressedV6Packet() throws IOException {
        return makeMdnsCompressedV6Packet("myservice.tcp.local", "googlecast.tcp.local",
                "matter.tcp.local", "myhostname.local");
    }

    private static byte[] makeMdnsCompressedV6PacketWithManyNames() throws IOException {
        return makeMdnsCompressedV6Packet("myservice.tcp.local", "googlecast.tcp.local",
                "matter.tcp.local", "myhostname.local", "myhostname2.local", "myhostname3.local",
                "myhostname4.local", "myhostname5.local", "myhostname6.local", "myhostname7.local");

    }

    /** Adds to the program a no-op instruction that is one byte long. */
    private void addOneByteNoop(ApfV4Generator gen) {
        gen.addLeftShift(0);
    }

    @Test
    public void testAddOneByteNoopAddsOneByte() throws Exception {
        ApfV4Generator gen = new ApfV4Generator(MIN_APF_VERSION);
        addOneByteNoop(gen);
        assertEquals(1, gen.generate().length);

        final int count = 42;
        gen = new ApfV4Generator(MIN_APF_VERSION);
        for (int i = 0; i < count; i++) {
            addOneByteNoop(gen);
        }
        assertEquals(count, gen.generate().length);
    }

    @Test
    public void testQnameEncoding() {
        String[] qname = new String[]{"abcd", "ef", "日本"};
        byte[] encodedQname = ApfFilter.encodeQname(qname);
        Assert.assertArrayEquals(
                new byte[]{0x04, 0x61, 0x62, 0x63, 0x64, 0x02, 0x65, 0x66, 0x06, (byte) 0xe6,
                        (byte) 0x97, (byte) 0xa5, (byte) 0xe6, (byte) 0x9c, (byte) 0xac, 0x00},
                encodedQname);
    }

    @Test
    public void testApfFilterMdns() throws Exception {
        final byte[] unicastIpv4Addr = {(byte) 192, 0, 2, 63};

        MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        LinkAddress link = new LinkAddress(InetAddress.getByAddress(unicastIpv4Addr), 24);
        LinkProperties lp = new LinkProperties();
        lp.addLinkAddress(link);

        ApfConfiguration config = getDefaultConfig();
        TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);
        apfFilter.setLinkProperties(lp);

        // Construct IPv4 mDNS packet
        byte[] mdnsv4packet = makeMdnsV4Packet("test.local");
        byte[] mdnsv6packet = makeMdnsV6Packet("test.local");
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();
        // mDNSv4 packet is passed if no mDns filter is turned on
        assertPass(program, mdnsv4packet);
        // mDNSv6 packet is passed if no mDNS filter is turned on
        assertPass(program, mdnsv6packet);

        // mDNSv4 packet with qname in the allowlist is passed
        apfFilter.addToMdnsAllowList(new String[]{"test", "local"});
        apfFilter.addToMdnsAllowList(new String[]{"abcd", "local"});
        apfFilter.setMulticastFilter(true);
        program = ipClientCallback.assertProgramUpdateAndGet();
        assertPass(program, mdnsv4packet);
        assertPass(program, mdnsv6packet);
        // If packet contains more than one qname, pass the packet
        mdnsv4packet = makeMdnsV4Packet("cccc.local", "dddd.local");
        mdnsv6packet = makeMdnsV6Packet("cccc.local", "dddd.local");
        assertPass(program, mdnsv4packet);
        assertPass(program, mdnsv6packet);
        // If packet doesn't contain any qname, pass the packet
        mdnsv4packet = makeMdnsV4Packet();
        mdnsv6packet = makeMdnsV6Packet();
        assertPass(program, mdnsv4packet);
        assertPass(program, mdnsv6packet);

        mdnsv4packet = makeMdnsV4Packet("abcd.local");
        mdnsv6packet = makeMdnsV6Packet("abcd.local");
        assertPass(program, mdnsv4packet);
        assertPass(program, mdnsv6packet);

        // mDNSv4 packet with qname not in the allowlist is dropped
        mdnsv4packet = makeMdnsV4Packet("ffff.local");
        mdnsv6packet = makeMdnsV6Packet("ffff.local");
        assertDrop(program, mdnsv4packet);
        assertDrop(program, mdnsv6packet);

        apfFilter.removeFromAllowList(new String[]{"abcd", "local"});
        program = ipClientCallback.assertProgramUpdateAndGet();
        mdnsv4packet = makeMdnsV4Packet("abcd.local");
        mdnsv6packet = makeMdnsV6Packet("abcd.local");
        assertDrop(program, mdnsv4packet);
        assertDrop(program, mdnsv6packet);

        apfFilter.shutdown();
    }

    private ApfV4Generator generateDnsFilter(boolean ipv6, String... labels) throws Exception {
        ApfV4Generator gen = new ApfV4Generator(MIN_APF_VERSION);
        gen.addLoadImmediate(R1, ipv6 ? IPV6_HEADER_LEN : IPV4_HEADER_LEN);
        DnsUtils.generateFilter(gen, labels);
        return gen;
    }

    private void doTestDnsParsing(boolean expectPass, boolean ipv6, String filterName,
            byte[] pkt) throws Exception {
        final String[] labels = filterName.split(/*regex=*/ "[.]");
        ApfV4Generator gen = generateDnsFilter(ipv6, labels);

        // Hack to prevent the APF instruction limit triggering.
        for (int i = 0; i < 500; i++) {
            addOneByteNoop(gen);
        }

        byte[] program = gen.generate();
        Log.d(TAG, "prog_len=" + program.length);
        if (expectPass) {
            assertPass(program, pkt, 0);
        } else {
            assertDrop(program, pkt, 0);
        }
    }

    private void doTestDnsParsing(boolean expectPass, boolean ipv6, String filterName,
            String... packetNames) throws Exception {
        final byte[] pkt = ipv6 ? makeMdnsV6Packet(packetNames) : makeMdnsV4Packet(packetNames);
        doTestDnsParsing(expectPass, ipv6, filterName, pkt);
    }

    @Test
    public void testDnsParsing() throws Exception {
        final boolean ipv4 = false, ipv6 = true;

        // Packets with one question.
        // Names don't start with _ because DnsPacket thinks such names are invalid.
        doTestDnsParsing(true, ipv6, "googlecast.tcp.local", "googlecast.tcp.local");
        doTestDnsParsing(true, ipv4, "googlecast.tcp.local", "googlecast.tcp.local");
        doTestDnsParsing(false, ipv6, "googlecast.tcp.lozal", "googlecast.tcp.local");
        doTestDnsParsing(false, ipv4, "googlecast.tcp.lozal", "googlecast.tcp.local");
        doTestDnsParsing(false, ipv6, "googlecast.udp.local", "googlecast.tcp.local");
        doTestDnsParsing(false, ipv4, "googlecast.udp.local", "googlecast.tcp.local");

        // Packets with multiple questions that can't be compressed. Not realistic for MDNS since
        // everything ends in .local, but useful to ensure only the non-compression code is tested.
        doTestDnsParsing(true, ipv6, "googlecast.tcp.local",
                "googlecast.tcp.local", "developer.android.com");
        doTestDnsParsing(true, ipv4, "googlecast.tcp.local",
                "developer.android.com", "googlecast.tcp.local");
        doTestDnsParsing(false, ipv4, "googlecast.tcp.local",
                "developer.android.com", "googlecast.tcp.invalid");
        doTestDnsParsing(true, ipv6, "googlecast.tcp.local",
                "developer.android.com", "www.google.co.jp", "googlecast.tcp.local");
        doTestDnsParsing(false, ipv4, "veryverylongservicename.tcp.local",
                "www.google.co.jp", "veryverylongservicename.tcp.invalid");
        doTestDnsParsing(true, ipv6, "googlecast.tcp.local",
                "www.google.co.jp", "googlecast.tcp.local", "developer.android.com");

        // Name with duplicate labels.
        doTestDnsParsing(true, ipv6, "local.tcp.local", "local.tcp.local");

        final byte[] pkt = makeMdnsCompressedV6Packet();
        doTestDnsParsing(true, ipv6, "googlecast.tcp.local", pkt);
        doTestDnsParsing(true, ipv6, "matter.tcp.local", pkt);
        doTestDnsParsing(true, ipv6, "myservice.tcp.local", pkt);
        doTestDnsParsing(false, ipv6, "otherservice.tcp.local", pkt);
    }

    private void doTestDnsParsingProgramLength(int expectedLength,
            String filterName) throws Exception {
        final String[] labels = filterName.split(/*regex=*/ "[.]");

        ApfV4Generator gen = generateDnsFilter(/*ipv6=*/ true, labels);
        assertEquals("Program for " + filterName + " had unexpected length:",
                expectedLength, gen.generate().length);
    }

    /**
     * Rough metric of code size. Checks how large the generated filter is in various scenarios.
     * Helps ensure any changes to the code do not substantially increase APF code size.
     */
    @Test
    public void testDnsParsingProgramLength() throws Exception {
        doTestDnsParsingProgramLength(237, "MyDevice.local");
        doTestDnsParsingProgramLength(285, "_googlecast.tcp.local");
        doTestDnsParsingProgramLength(291, "_googlecast12345.tcp.local");
        doTestDnsParsingProgramLength(244, "_googlecastZtcp.local");
        doTestDnsParsingProgramLength(249, "_googlecastZtcp12345.local");
    }

    private void doTestDnsParsingNecessaryOverhead(int expectedNecessaryOverhead,
            String filterName, byte[] pkt, String description) throws Exception {
        final String[] labels = filterName.split(/*regex=*/ "[.]");

        // Check that the generated code, when the program contains the specified number of extra
        // bytes, is capable of dropping the packet.
        ApfV4Generator gen = generateDnsFilter(/*ipv6=*/ true, labels);
        for (int i = 0; i < expectedNecessaryOverhead; i++) {
            addOneByteNoop(gen);
        }
        final byte[] programWithJustEnoughOverhead = gen.generate();
        assertVerdict(
                "Overhead too low: filter for " + filterName + " with " + expectedNecessaryOverhead
                        + " extra instructions unexpectedly passed " + description,
                DROP, programWithJustEnoughOverhead, pkt, 0);

        if (expectedNecessaryOverhead == 0) return;

        // Check that the generated code, without the specified number of extra program bytes,
        // cannot correctly drop the packet because it hits the interpreter instruction limit.
        gen = generateDnsFilter(/*ipv6=*/ true, labels);
        for (int i = 0; i < expectedNecessaryOverhead - 1; i++) {
            addOneByteNoop(gen);
        }
        final byte[] programWithNotEnoughOverhead = gen.generate();

        assertVerdict(
                "Overhead too high: filter for " + filterName + " with " + expectedNecessaryOverhead
                        + " extra instructions unexpectedly dropped " + description,
                PASS, programWithNotEnoughOverhead, pkt, 0);
    }

    private void doTestDnsParsingNecessaryOverhead(int expectedNecessaryOverhead,
            String filterName, String... packetNames) throws Exception {
        doTestDnsParsingNecessaryOverhead(expectedNecessaryOverhead, filterName,
                makeMdnsV6Packet(packetNames),
                "IPv6 MDNS packet containing: " + Arrays.toString(packetNames));
    }

    /**
     * Rough metric of filter efficiency. Because the filter uses backwards jumps, on complex
     * packets it will not finish running before the interpreter hits the maximum number of allowed
     * instructions (== number of bytes in the program) and unconditionally accepts the packet.
     * This test checks much extra code the program must contain in order for the generated filter
     * to successfully drop the packet. It helps ensure any changes to the code do not reduce the
     * complexity of packets that the APF code can drop.
     */
    @Test
    public void testDnsParsingNecessaryOverhead() throws Exception {
        // Simple packets can be parsed with zero extra code.
        doTestDnsParsingNecessaryOverhead(0, "googlecast.tcp.local",
                "matter.tcp.local", "developer.android.com");

        doTestDnsParsingNecessaryOverhead(0, "googlecast.tcp.local",
                "developer.android.com", "matter.tcp.local");

        doTestDnsParsingNecessaryOverhead(0, "googlecast.tcp.local",
                "developer.android.com", "matter.tcp.local", "www.google.co.jp");

        doTestDnsParsingNecessaryOverhead(0, "googlecast.tcp.local",
                "developer.android.com", "matter.tcp.local", "www.google.co.jp",
                "example.org");

        // More complicated packets cause more instructions to be run and can only be dropped if
        // the program contains lots of extra code.
        doTestDnsParsingNecessaryOverhead(57, "googlecast.tcp.local",
                "developer.android.com", "matter.tcp.local", "www.google.co.jp",
                "example.org", "otherexample.net");

        doTestDnsParsingNecessaryOverhead(115, "googlecast.tcp.local",
                "developer.android.com", "matter.tcp.local", "www.google.co.jp",
                "example.org", "otherexample.net", "docs.new");

        doTestDnsParsingNecessaryOverhead(0, "foo.tcp.local",
                makeMdnsCompressedV6Packet(), "compressed packet");

        doTestDnsParsingNecessaryOverhead(235, "foo.tcp.local",
                makeMdnsCompressedV6PacketWithManyNames(), "compressed packet with many names");
    }

    @Test
    public void testApfFilterMulticast() throws Exception {
        final byte[] unicastIpv4Addr   = {(byte)192,0,2,63};
        final byte[] broadcastIpv4Addr = {(byte)192,0,2,(byte)255};
        final byte[] multicastIpv4Addr = {(byte)224,0,0,1};
        final byte[] multicastIpv6Addr = {(byte)0xff,2,0,0,0,0,0,0,0,0,0,0,0,0,0,(byte)0xfb};

        MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        LinkAddress link = new LinkAddress(InetAddress.getByAddress(unicastIpv4Addr), 24);
        LinkProperties lp = new LinkProperties();
        lp.addLinkAddress(link);

        ApfConfiguration config = getDefaultConfig();
        config.ieee802_3Filter = DROP_802_3_FRAMES;
        TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);
        apfFilter.setLinkProperties(lp);

        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        // Construct IPv4 and IPv6 multicast packets.
        ByteBuffer mcastv4packet = makeIpv4Packet(IPPROTO_UDP);
        put(mcastv4packet, IPV4_DEST_ADDR_OFFSET, multicastIpv4Addr);

        ByteBuffer mcastv6packet = makeIpv6Packet(IPPROTO_UDP);
        put(mcastv6packet, IPV6_DEST_ADDR_OFFSET, multicastIpv6Addr);

        // Construct IPv4 broadcast packet.
        ByteBuffer bcastv4packet1 = makeIpv4Packet(IPPROTO_UDP);
        bcastv4packet1.put(ETH_BROADCAST_MAC_ADDRESS);
        bcastv4packet1.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_IP);
        put(bcastv4packet1, IPV4_DEST_ADDR_OFFSET, multicastIpv4Addr);

        ByteBuffer bcastv4packet2 = makeIpv4Packet(IPPROTO_UDP);
        bcastv4packet2.put(ETH_BROADCAST_MAC_ADDRESS);
        bcastv4packet2.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_IP);
        put(bcastv4packet2, IPV4_DEST_ADDR_OFFSET, IPV4_BROADCAST_ADDRESS);

        // Construct IPv4 broadcast with L2 unicast address packet (b/30231088).
        ByteBuffer bcastv4unicastl2packet = makeIpv4Packet(IPPROTO_UDP);
        bcastv4unicastl2packet.put(TestApfFilter.MOCK_MAC_ADDR);
        bcastv4unicastl2packet.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_IP);
        put(bcastv4unicastl2packet, IPV4_DEST_ADDR_OFFSET, broadcastIpv4Addr);

        // Verify initially disabled multicast filter is off
        assertPass(program, mcastv4packet.array());
        assertPass(program, mcastv6packet.array());
        assertPass(program, bcastv4packet1.array());
        assertPass(program, bcastv4packet2.array());
        assertPass(program, bcastv4unicastl2packet.array());

        // Turn on multicast filter and verify it works
        ipClientCallback.resetApfProgramWait();
        apfFilter.setMulticastFilter(true);
        program = ipClientCallback.assertProgramUpdateAndGet();
        assertDrop(program, mcastv4packet.array());
        assertDrop(program, mcastv6packet.array());
        assertDrop(program, bcastv4packet1.array());
        assertDrop(program, bcastv4packet2.array());
        assertDrop(program, bcastv4unicastl2packet.array());

        // Turn off multicast filter and verify it's off
        ipClientCallback.resetApfProgramWait();
        apfFilter.setMulticastFilter(false);
        program = ipClientCallback.assertProgramUpdateAndGet();
        assertPass(program, mcastv4packet.array());
        assertPass(program, mcastv6packet.array());
        assertPass(program, bcastv4packet1.array());
        assertPass(program, bcastv4packet2.array());
        assertPass(program, bcastv4unicastl2packet.array());

        // Verify it can be initialized to on
        ipClientCallback.resetApfProgramWait();
        apfFilter.shutdown();
        config.multicastFilter = DROP_MULTICAST;
        config.ieee802_3Filter = DROP_802_3_FRAMES;
        apfFilter = new TestApfFilter(mContext, config, ipClientCallback, mNetworkQuirkMetrics);
        apfFilter.setLinkProperties(lp);
        program = ipClientCallback.assertProgramUpdateAndGet();
        assertDrop(program, mcastv4packet.array());
        assertDrop(program, mcastv6packet.array());
        assertDrop(program, bcastv4packet1.array());
        assertDrop(program, bcastv4unicastl2packet.array());

        // Verify that ICMPv6 multicast is not dropped.
        mcastv6packet.put(IPV6_NEXT_HEADER_OFFSET, (byte)IPPROTO_ICMPV6);
        assertPass(program, mcastv6packet.array());

        apfFilter.shutdown();
    }

    @Test
    public void testApfFilterMulticastPingWhileDozing() throws Exception {
        doTestApfFilterMulticastPingWhileDozing(false /* isLightDozing */);
    }

    @Test
    @DevSdkIgnoreRule.IgnoreUpTo(Build.VERSION_CODES.TIRAMISU)
    public void testApfFilterMulticastPingWhileLightDozing() throws Exception {
        doTestApfFilterMulticastPingWhileDozing(true /* isLightDozing */);
    }

    @Test
    @DevSdkIgnoreRule.IgnoreUpTo(Build.VERSION_CODES.TIRAMISU)
    public void testShouldHandleLightDozeKillSwitch() throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        final ApfConfiguration configuration = getDefaultConfig();
        configuration.shouldHandleLightDoze = false;
        final ApfFilter apfFilter = TestApfFilter.createTestApfFilter(mContext, ipClientCallback,
                configuration, mNetworkQuirkMetrics, mDependencies);
        final ArgumentCaptor<BroadcastReceiver> receiverCaptor =
                ArgumentCaptor.forClass(BroadcastReceiver.class);
        verify(mDependencies).addDeviceIdleReceiver(receiverCaptor.capture(), anyBoolean());
        final BroadcastReceiver receiver = receiverCaptor.getValue();
        doReturn(true).when(mPowerManager).isDeviceLightIdleMode();
        receiver.onReceive(mContext, new Intent(ACTION_DEVICE_LIGHT_IDLE_MODE_CHANGED));
        assertFalse(apfFilter.isInDozeMode());
    }

    private void doTestApfFilterMulticastPingWhileDozing(boolean isLightDozing) throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        final ApfConfiguration configuration = getDefaultConfig();
        configuration.shouldHandleLightDoze = true;
        final ApfFilter apfFilter = TestApfFilter.createTestApfFilter(mContext, ipClientCallback,
                configuration, mNetworkQuirkMetrics, mDependencies);
        final ArgumentCaptor<BroadcastReceiver> receiverCaptor =
                ArgumentCaptor.forClass(BroadcastReceiver.class);
        verify(mDependencies).addDeviceIdleReceiver(receiverCaptor.capture(), anyBoolean());
        final BroadcastReceiver receiver = receiverCaptor.getValue();

        // Construct a multicast ICMPv6 ECHO request.
        final byte[] multicastIpv6Addr = {(byte)0xff,2,0,0,0,0,0,0,0,0,0,0,0,0,0,(byte)0xfb};
        final ByteBuffer packet = makeIpv6Packet(IPPROTO_ICMPV6);
        packet.put(ICMP6_TYPE_OFFSET, (byte)ICMPV6_ECHO_REQUEST_TYPE);
        put(packet, IPV6_DEST_ADDR_OFFSET, multicastIpv6Addr);

        // Normally, we let multicast pings alone...
        assertPass(ipClientCallback.assertProgramUpdateAndGet(), packet.array());

        if (isLightDozing) {
            doReturn(true).when(mPowerManager).isDeviceLightIdleMode();
            receiver.onReceive(mContext, new Intent(ACTION_DEVICE_LIGHT_IDLE_MODE_CHANGED));
        } else {
            doReturn(true).when(mPowerManager).isDeviceIdleMode();
            receiver.onReceive(mContext, new Intent(ACTION_DEVICE_IDLE_MODE_CHANGED));
        }
        // ...and even while dozing...
        assertPass(ipClientCallback.assertProgramUpdateAndGet(), packet.array());

        // ...but when the multicast filter is also enabled, drop the multicast pings to save power.
        apfFilter.setMulticastFilter(true);
        assertDrop(ipClientCallback.assertProgramUpdateAndGet(), packet.array());

        // However, we should still let through all other ICMPv6 types.
        ByteBuffer raPacket = ByteBuffer.wrap(packet.array().clone());
        setIpv6VersionFields(packet);
        packet.put(IPV6_NEXT_HEADER_OFFSET, (byte) IPPROTO_ICMPV6);
        raPacket.put(ICMP6_TYPE_OFFSET, (byte) NetworkStackConstants.ICMPV6_ROUTER_ADVERTISEMENT);
        assertPass(ipClientCallback.assertProgramUpdateAndGet(), raPacket.array());

        // Now wake up from doze mode to ensure that we no longer drop the packets.
        // (The multicast filter is still enabled at this point).
        if (isLightDozing) {
            doReturn(false).when(mPowerManager).isDeviceLightIdleMode();
            receiver.onReceive(mContext, new Intent(ACTION_DEVICE_LIGHT_IDLE_MODE_CHANGED));
        } else {
            doReturn(false).when(mPowerManager).isDeviceIdleMode();
            receiver.onReceive(mContext, new Intent(ACTION_DEVICE_IDLE_MODE_CHANGED));
        }
        assertPass(ipClientCallback.assertProgramUpdateAndGet(), packet.array());

        apfFilter.shutdown();
    }

    @Test
    public void testApfFilter802_3() throws Exception {
        MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        ApfConfiguration config = getDefaultConfig();
        ApfFilter apfFilter = TestApfFilter.createTestApfFilter(mContext, ipClientCallback, config,
                mNetworkQuirkMetrics, mDependencies);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        // Verify empty packet of 100 zero bytes is passed
        // Note that eth-type = 0 makes it an IEEE802.3 frame
        ByteBuffer packet = ByteBuffer.wrap(new byte[100]);
        assertPass(program, packet.array());

        // Verify empty packet with IPv4 is passed
        setIpv4VersionFields(packet);
        assertPass(program, packet.array());

        // Verify empty IPv6 packet is passed
        setIpv6VersionFields(packet);
        assertPass(program, packet.array());

        // Now turn on the filter
        ipClientCallback.resetApfProgramWait();
        apfFilter.shutdown();
        config.ieee802_3Filter = DROP_802_3_FRAMES;
        apfFilter = TestApfFilter.createTestApfFilter(mContext, ipClientCallback, config,
                mNetworkQuirkMetrics, mDependencies);
        program = ipClientCallback.assertProgramUpdateAndGet();

        // Verify that IEEE802.3 frame is dropped
        // In this case ethtype is used for payload length
        packet.putShort(ETH_ETHERTYPE_OFFSET, (short)(100 - 14));
        assertDrop(program, packet.array());

        // Verify that IPv4 (as example of Ethernet II) frame will pass
        setIpv4VersionFields(packet);
        assertPass(program, packet.array());

        // Verify that IPv6 (as example of Ethernet II) frame will pass
        setIpv6VersionFields(packet);
        assertPass(program, packet.array());

        apfFilter.shutdown();
    }

    @Test
    public void testApfFilterEthTypeBL() throws Exception {
        final int[] emptyBlackList = {};
        final int[] ipv4BlackList = {ETH_P_IP};
        final int[] ipv4Ipv6BlackList = {ETH_P_IP, ETH_P_IPV6};

        MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        ApfConfiguration config = getDefaultConfig();
        ApfFilter apfFilter = TestApfFilter.createTestApfFilter(mContext, ipClientCallback, config,
                mNetworkQuirkMetrics, mDependencies);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        // Verify empty packet of 100 zero bytes is passed
        // Note that eth-type = 0 makes it an IEEE802.3 frame
        ByteBuffer packet = ByteBuffer.wrap(new byte[100]);
        assertPass(program, packet.array());

        // Verify empty packet with IPv4 is passed
        setIpv4VersionFields(packet);
        assertPass(program, packet.array());

        // Verify empty IPv6 packet is passed
        setIpv6VersionFields(packet);
        assertPass(program, packet.array());

        // Now add IPv4 to the black list
        ipClientCallback.resetApfProgramWait();
        apfFilter.shutdown();
        config.ethTypeBlackList = ipv4BlackList;
        apfFilter = TestApfFilter.createTestApfFilter(mContext, ipClientCallback, config,
                mNetworkQuirkMetrics, mDependencies);
        program = ipClientCallback.assertProgramUpdateAndGet();

        // Verify that IPv4 frame will be dropped
        setIpv4VersionFields(packet);
        assertDrop(program, packet.array());

        // Verify that IPv6 frame will pass
        setIpv6VersionFields(packet);
        assertPass(program, packet.array());

        // Now let us have both IPv4 and IPv6 in the black list
        ipClientCallback.resetApfProgramWait();
        apfFilter.shutdown();
        config.ethTypeBlackList = ipv4Ipv6BlackList;
        apfFilter = TestApfFilter.createTestApfFilter(mContext, ipClientCallback, config,
                mNetworkQuirkMetrics, mDependencies);
        program = ipClientCallback.assertProgramUpdateAndGet();

        // Verify that IPv4 frame will be dropped
        setIpv4VersionFields(packet);
        assertDrop(program, packet.array());

        // Verify that IPv6 frame will be dropped
        setIpv6VersionFields(packet);
        assertDrop(program, packet.array());

        apfFilter.shutdown();
    }

    private byte[] getProgram(MockIpClientCallback cb, ApfFilter filter, LinkProperties lp) {
        cb.resetApfProgramWait();
        filter.setLinkProperties(lp);
        return cb.assertProgramUpdateAndGet();
    }

    private void verifyArpFilter(byte[] program, int filterResult) {
        // Verify ARP request packet
        assertPass(program, arpRequestBroadcast(MOCK_IPV4_ADDR));
        assertVerdict(filterResult, program, arpRequestBroadcast(ANOTHER_IPV4_ADDR));
        assertDrop(program, arpRequestBroadcast(IPV4_ANY_HOST_ADDR));

        // Verify ARP reply packets from different source ip
        assertDrop(program, arpReply(IPV4_ANY_HOST_ADDR, IPV4_ANY_HOST_ADDR));
        assertPass(program, arpReply(ANOTHER_IPV4_SOURCE_ADDR, IPV4_ANY_HOST_ADDR));
        assertPass(program, arpReply(BUG_PROBE_SOURCE_ADDR1, IPV4_ANY_HOST_ADDR));
        assertPass(program, arpReply(BUG_PROBE_SOURCE_ADDR2, IPV4_ANY_HOST_ADDR));

        // Verify unicast ARP reply packet is always accepted.
        assertPass(program, arpReply(IPV4_SOURCE_ADDR, MOCK_IPV4_ADDR));
        assertPass(program, arpReply(IPV4_SOURCE_ADDR, ANOTHER_IPV4_ADDR));
        assertPass(program, arpReply(IPV4_SOURCE_ADDR, IPV4_ANY_HOST_ADDR));

        // Verify GARP reply packets are always filtered
        assertDrop(program, garpReply());
    }

    @Test
    public void testApfFilterArp() throws Exception {
        MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        ApfConfiguration config = getDefaultConfig();
        config.multicastFilter = DROP_MULTICAST;
        config.ieee802_3Filter = DROP_802_3_FRAMES;
        TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);

        // Verify initially ARP request filter is off, and GARP filter is on.
        verifyArpFilter(ipClientCallback.assertProgramUpdateAndGet(), PASS);

        // Inform ApfFilter of our address and verify ARP filtering is on
        LinkAddress linkAddress = new LinkAddress(InetAddress.getByAddress(MOCK_IPV4_ADDR), 24);
        LinkProperties lp = new LinkProperties();
        assertTrue(lp.addLinkAddress(linkAddress));
        verifyArpFilter(getProgram(ipClientCallback, apfFilter, lp), DROP);

        // Inform ApfFilter of loss of IP and verify ARP filtering is off
        verifyArpFilter(getProgram(ipClientCallback, apfFilter, new LinkProperties()), PASS);

        apfFilter.shutdown();
    }

    private static byte[] arpReply(byte[] sip, byte[] tip) {
        ByteBuffer packet = ByteBuffer.wrap(new byte[100]);
        packet.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_ARP);
        put(packet, ARP_HEADER_OFFSET, ARP_IPV4_REPLY_HEADER);
        put(packet, ARP_SOURCE_IP_ADDRESS_OFFSET, sip);
        put(packet, ARP_TARGET_IP_ADDRESS_OFFSET, tip);
        return packet.array();
    }

    private static byte[] arpRequestBroadcast(byte[] tip) {
        ByteBuffer packet = ByteBuffer.wrap(new byte[100]);
        packet.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_ARP);
        put(packet, ETH_DEST_ADDR_OFFSET, ETH_BROADCAST_MAC_ADDRESS);
        put(packet, ARP_HEADER_OFFSET, ARP_IPV4_REQUEST_HEADER);
        put(packet, ARP_TARGET_IP_ADDRESS_OFFSET, tip);
        return packet.array();
    }

    private static byte[] garpReply() {
        ByteBuffer packet = ByteBuffer.wrap(new byte[100]);
        packet.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_ARP);
        put(packet, ETH_DEST_ADDR_OFFSET, ETH_BROADCAST_MAC_ADDRESS);
        put(packet, ARP_HEADER_OFFSET, ARP_IPV4_REPLY_HEADER);
        put(packet, ARP_TARGET_IP_ADDRESS_OFFSET, IPV4_ANY_HOST_ADDR);
        return packet.array();
    }

    private static final byte[] IPV4_KEEPALIVE_SRC_ADDR = {10, 0, 0, 5};
    private static final byte[] IPV4_KEEPALIVE_DST_ADDR = {10, 0, 0, 6};
    private static final byte[] IPV4_ANOTHER_ADDR = {10, 0 , 0, 7};
    private static final byte[] IPV6_KEEPALIVE_SRC_ADDR =
            {(byte) 0x24, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xfa, (byte) 0xf1};
    private static final byte[] IPV6_KEEPALIVE_DST_ADDR =
            {(byte) 0x24, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xfa, (byte) 0xf2};
    private static final byte[] IPV6_ANOTHER_ADDR =
            {(byte) 0x24, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xfa, (byte) 0xf5};

    @Test
    public void testApfFilterKeepaliveAck() throws Exception {
        final MockIpClientCallback cb = new MockIpClientCallback();
        final ApfConfiguration config = getDefaultConfig();
        config.multicastFilter = DROP_MULTICAST;
        config.ieee802_3Filter = DROP_802_3_FRAMES;
        final TestApfFilter apfFilter = new TestApfFilter(mContext, config, cb,
                mNetworkQuirkMetrics);
        byte[] program;
        final int srcPort = 12345;
        final int dstPort = 54321;
        final int seqNum = 2123456789;
        final int ackNum = 1234567890;
        final int anotherSrcPort = 23456;
        final int anotherDstPort = 65432;
        final int anotherSeqNum = 2123456780;
        final int anotherAckNum = 1123456789;
        final int slot1 = 1;
        final int slot2 = 2;
        final int window = 14480;
        final int windowScale = 4;

        // src: 10.0.0.5, port: 12345
        // dst: 10.0.0.6, port: 54321
        InetAddress srcAddr = InetAddress.getByAddress(IPV4_KEEPALIVE_SRC_ADDR);
        InetAddress dstAddr = InetAddress.getByAddress(IPV4_KEEPALIVE_DST_ADDR);

        final TcpKeepalivePacketDataParcelable parcel = new TcpKeepalivePacketDataParcelable();
        parcel.srcAddress = srcAddr.getAddress();
        parcel.srcPort = srcPort;
        parcel.dstAddress = dstAddr.getAddress();
        parcel.dstPort = dstPort;
        parcel.seq = seqNum;
        parcel.ack = ackNum;

        apfFilter.addTcpKeepalivePacketFilter(slot1, parcel);
        program = cb.assertProgramUpdateAndGet();

        // Verify IPv4 keepalive ack packet is dropped
        // src: 10.0.0.6, port: 54321
        // dst: 10.0.0.5, port: 12345
        assertDrop(program,
                ipv4TcpPacket(IPV4_KEEPALIVE_DST_ADDR, IPV4_KEEPALIVE_SRC_ADDR,
                        dstPort, srcPort, ackNum, seqNum + 1, 0 /* dataLength */));
        // Verify IPv4 non-keepalive ack packet from the same source address is passed
        assertPass(program,
                ipv4TcpPacket(IPV4_KEEPALIVE_DST_ADDR, IPV4_KEEPALIVE_SRC_ADDR,
                        dstPort, srcPort, ackNum + 100, seqNum, 0 /* dataLength */));
        assertPass(program,
                ipv4TcpPacket(IPV4_KEEPALIVE_DST_ADDR, IPV4_KEEPALIVE_SRC_ADDR,
                        dstPort, srcPort, ackNum, seqNum + 1, 10 /* dataLength */));
        // Verify IPv4 packet from another address is passed
        assertPass(program,
                ipv4TcpPacket(IPV4_ANOTHER_ADDR, IPV4_KEEPALIVE_SRC_ADDR, anotherSrcPort,
                        anotherDstPort, anotherSeqNum, anotherAckNum, 0 /* dataLength */));

        // Remove IPv4 keepalive filter
        apfFilter.removeKeepalivePacketFilter(slot1);

        try {
            // src: 2404:0:0:0:0:0:faf1, port: 12345
            // dst: 2404:0:0:0:0:0:faf2, port: 54321
            srcAddr = InetAddress.getByAddress(IPV6_KEEPALIVE_SRC_ADDR);
            dstAddr = InetAddress.getByAddress(IPV6_KEEPALIVE_DST_ADDR);

            final TcpKeepalivePacketDataParcelable ipv6Parcel =
                    new TcpKeepalivePacketDataParcelable();
            ipv6Parcel.srcAddress = srcAddr.getAddress();
            ipv6Parcel.srcPort = srcPort;
            ipv6Parcel.dstAddress = dstAddr.getAddress();
            ipv6Parcel.dstPort = dstPort;
            ipv6Parcel.seq = seqNum;
            ipv6Parcel.ack = ackNum;

            apfFilter.addTcpKeepalivePacketFilter(slot1, ipv6Parcel);
            program = cb.assertProgramUpdateAndGet();

            // Verify IPv6 keepalive ack packet is dropped
            // src: 2404:0:0:0:0:0:faf2, port: 54321
            // dst: 2404:0:0:0:0:0:faf1, port: 12345
            assertDrop(program,
                    ipv6TcpPacket(IPV6_KEEPALIVE_DST_ADDR, IPV6_KEEPALIVE_SRC_ADDR,
                            dstPort, srcPort, ackNum, seqNum + 1));
            // Verify IPv6 non-keepalive ack packet from the same source address is passed
            assertPass(program,
                    ipv6TcpPacket(IPV6_KEEPALIVE_DST_ADDR, IPV6_KEEPALIVE_SRC_ADDR,
                            dstPort, srcPort, ackNum + 100, seqNum));
            // Verify IPv6 packet from another address is passed
            assertPass(program,
                    ipv6TcpPacket(IPV6_ANOTHER_ADDR, IPV6_KEEPALIVE_SRC_ADDR, anotherSrcPort,
                            anotherDstPort, anotherSeqNum, anotherAckNum));

            // Remove IPv6 keepalive filter
            apfFilter.removeKeepalivePacketFilter(slot1);

            // Verify multiple filters
            apfFilter.addTcpKeepalivePacketFilter(slot1, parcel);
            apfFilter.addTcpKeepalivePacketFilter(slot2, ipv6Parcel);
            program = cb.assertProgramUpdateAndGet();

            // Verify IPv4 keepalive ack packet is dropped
            // src: 10.0.0.6, port: 54321
            // dst: 10.0.0.5, port: 12345
            assertDrop(program,
                    ipv4TcpPacket(IPV4_KEEPALIVE_DST_ADDR, IPV4_KEEPALIVE_SRC_ADDR,
                            dstPort, srcPort, ackNum, seqNum + 1, 0 /* dataLength */));
            // Verify IPv4 non-keepalive ack packet from the same source address is passed
            assertPass(program,
                    ipv4TcpPacket(IPV4_KEEPALIVE_DST_ADDR, IPV4_KEEPALIVE_SRC_ADDR,
                            dstPort, srcPort, ackNum + 100, seqNum, 0 /* dataLength */));
            // Verify IPv4 packet from another address is passed
            assertPass(program,
                    ipv4TcpPacket(IPV4_ANOTHER_ADDR, IPV4_KEEPALIVE_SRC_ADDR, anotherSrcPort,
                            anotherDstPort, anotherSeqNum, anotherAckNum, 0 /* dataLength */));

            // Verify IPv6 keepalive ack packet is dropped
            // src: 2404:0:0:0:0:0:faf2, port: 54321
            // dst: 2404:0:0:0:0:0:faf1, port: 12345
            assertDrop(program,
                    ipv6TcpPacket(IPV6_KEEPALIVE_DST_ADDR, IPV6_KEEPALIVE_SRC_ADDR,
                            dstPort, srcPort, ackNum, seqNum + 1));
            // Verify IPv6 non-keepalive ack packet from the same source address is passed
            assertPass(program,
                    ipv6TcpPacket(IPV6_KEEPALIVE_DST_ADDR, IPV6_KEEPALIVE_SRC_ADDR,
                            dstPort, srcPort, ackNum + 100, seqNum));
            // Verify IPv6 packet from another address is passed
            assertPass(program,
                    ipv6TcpPacket(IPV6_ANOTHER_ADDR, IPV6_KEEPALIVE_SRC_ADDR, anotherSrcPort,
                            anotherDstPort, anotherSeqNum, anotherAckNum));

            // Remove keepalive filters
            apfFilter.removeKeepalivePacketFilter(slot1);
            apfFilter.removeKeepalivePacketFilter(slot2);
        } catch (UnsupportedOperationException e) {
            // TODO: support V6 packets
        }

        program = cb.assertProgramUpdateAndGet();

        // Verify IPv4, IPv6 packets are passed
        assertPass(program,
                ipv4TcpPacket(IPV4_KEEPALIVE_DST_ADDR, IPV4_KEEPALIVE_SRC_ADDR,
                        dstPort, srcPort, ackNum, seqNum + 1, 0 /* dataLength */));
        assertPass(program,
                ipv6TcpPacket(IPV6_KEEPALIVE_DST_ADDR, IPV6_KEEPALIVE_SRC_ADDR,
                        dstPort, srcPort, ackNum, seqNum + 1));
        assertPass(program,
                ipv4TcpPacket(IPV4_ANOTHER_ADDR, IPV4_KEEPALIVE_SRC_ADDR, srcPort,
                        dstPort, anotherSeqNum, anotherAckNum, 0 /* dataLength */));
        assertPass(program,
                ipv6TcpPacket(IPV6_ANOTHER_ADDR, IPV6_KEEPALIVE_SRC_ADDR, srcPort,
                        dstPort, anotherSeqNum, anotherAckNum));

        apfFilter.shutdown();
    }

    private static byte[] ipv4TcpPacket(byte[] sip, byte[] dip, int sport,
            int dport, int seq, int ack, int dataLength) {
        final int totalLength = dataLength + IPV4_HEADER_LEN + IPV4_TCP_HEADER_LEN;

        ByteBuffer packet = ByteBuffer.wrap(new byte[totalLength + ETH_HEADER_LEN]);

        // Ethertype and IPv4 header
        setIpv4VersionFields(packet);
        packet.putShort(IPV4_TOTAL_LENGTH_OFFSET, (short) totalLength);
        packet.put(IPV4_PROTOCOL_OFFSET, (byte) IPPROTO_TCP);
        put(packet, IPV4_SRC_ADDR_OFFSET, sip);
        put(packet, IPV4_DEST_ADDR_OFFSET, dip);
        packet.putShort(IPV4_TCP_SRC_PORT_OFFSET, (short) sport);
        packet.putShort(IPV4_TCP_DEST_PORT_OFFSET, (short) dport);
        packet.putInt(IPV4_TCP_SEQ_NUM_OFFSET, seq);
        packet.putInt(IPV4_TCP_ACK_NUM_OFFSET, ack);

        // TCP header length 5(20 bytes), reserved 3 bits, NS=0
        packet.put(IPV4_TCP_HEADER_LENGTH_OFFSET, (byte) 0x50);
        // TCP flags: ACK set
        packet.put(IPV4_TCP_HEADER_FLAG_OFFSET, (byte) 0x10);
        return packet.array();
    }

    private static byte[] ipv6TcpPacket(byte[] sip, byte[] tip, int sport,
            int dport, int seq, int ack) {
        ByteBuffer packet = ByteBuffer.wrap(new byte[100]);
        setIpv6VersionFields(packet);
        packet.put(IPV6_NEXT_HEADER_OFFSET, (byte) IPPROTO_TCP);
        put(packet, IPV6_SRC_ADDR_OFFSET, sip);
        put(packet, IPV6_DEST_ADDR_OFFSET, tip);
        packet.putShort(IPV6_TCP_SRC_PORT_OFFSET, (short) sport);
        packet.putShort(IPV6_TCP_DEST_PORT_OFFSET, (short) dport);
        packet.putInt(IPV6_TCP_SEQ_NUM_OFFSET, seq);
        packet.putInt(IPV6_TCP_ACK_NUM_OFFSET, ack);
        return packet.array();
    }

    @Test
    public void testApfFilterNattKeepalivePacket() throws Exception {
        final MockIpClientCallback cb = new MockIpClientCallback();
        final ApfConfiguration config = getDefaultConfig();
        config.multicastFilter = DROP_MULTICAST;
        config.ieee802_3Filter = DROP_802_3_FRAMES;
        final TestApfFilter apfFilter = new TestApfFilter(mContext, config, cb,
                mNetworkQuirkMetrics);
        byte[] program;
        final int srcPort = 1024;
        final int dstPort = 4500;
        final int slot1 = 1;
        // NAT-T keepalive
        final byte[] kaPayload = {(byte) 0xff};
        final byte[] nonKaPayload = {(byte) 0xfe};

        // src: 10.0.0.5, port: 1024
        // dst: 10.0.0.6, port: 4500
        InetAddress srcAddr = InetAddress.getByAddress(IPV4_KEEPALIVE_SRC_ADDR);
        InetAddress dstAddr = InetAddress.getByAddress(IPV4_KEEPALIVE_DST_ADDR);

        final NattKeepalivePacketDataParcelable parcel = new NattKeepalivePacketDataParcelable();
        parcel.srcAddress = srcAddr.getAddress();
        parcel.srcPort = srcPort;
        parcel.dstAddress = dstAddr.getAddress();
        parcel.dstPort = dstPort;

        apfFilter.addNattKeepalivePacketFilter(slot1, parcel);
        program = cb.assertProgramUpdateAndGet();

        // Verify IPv4 keepalive packet is dropped
        // src: 10.0.0.6, port: 4500
        // dst: 10.0.0.5, port: 1024
        byte[] pkt = ipv4UdpPacket(IPV4_KEEPALIVE_DST_ADDR,
                    IPV4_KEEPALIVE_SRC_ADDR, dstPort, srcPort, 1 /* dataLength */);
        System.arraycopy(kaPayload, 0, pkt, IPV4_UDP_PAYLOAD_OFFSET, kaPayload.length);
        assertDrop(program, pkt);

        // Verify a packet with payload length 1 byte but it is not 0xff will pass the filter.
        System.arraycopy(nonKaPayload, 0, pkt, IPV4_UDP_PAYLOAD_OFFSET, nonKaPayload.length);
        assertPass(program, pkt);

        // Verify IPv4 non-keepalive response packet from the same source address is passed
        assertPass(program,
                ipv4UdpPacket(IPV4_KEEPALIVE_DST_ADDR, IPV4_KEEPALIVE_SRC_ADDR,
                        dstPort, srcPort, 10 /* dataLength */));

        // Verify IPv4 non-keepalive response packet from other source address is passed
        assertPass(program,
                ipv4UdpPacket(IPV4_ANOTHER_ADDR, IPV4_KEEPALIVE_SRC_ADDR,
                        dstPort, srcPort, 10 /* dataLength */));

        apfFilter.removeKeepalivePacketFilter(slot1);
        apfFilter.shutdown();
    }

    private static byte[] ipv4UdpPacket(byte[] sip, byte[] dip, int sport,
            int dport, int dataLength) {
        final int totalLength = dataLength + IPV4_HEADER_LEN + UDP_HEADER_LEN;
        final int udpLength = UDP_HEADER_LEN + dataLength;
        ByteBuffer packet = ByteBuffer.wrap(new byte[totalLength + ETH_HEADER_LEN]);

        // Ethertype and IPv4 header
        setIpv4VersionFields(packet);
        packet.putShort(IPV4_TOTAL_LENGTH_OFFSET, (short) totalLength);
        packet.put(IPV4_PROTOCOL_OFFSET, (byte) IPPROTO_UDP);
        put(packet, IPV4_SRC_ADDR_OFFSET, sip);
        put(packet, IPV4_DEST_ADDR_OFFSET, dip);
        packet.putShort(IPV4_UDP_SRC_PORT_OFFSET, (short) sport);
        packet.putShort(IPV4_UDP_DEST_PORT_OFFSET, (short) dport);
        packet.putShort(IPV4_UDP_LENGTH_OFFSET, (short) udpLength);

        return packet.array();
    }

    private static class RaPacketBuilder {
        final ByteArrayOutputStream mPacket = new ByteArrayOutputStream();
        int mFlowLabel = 0x12345;
        int mReachableTime = 30_000;
        int mRetransmissionTimer = 1000;

        public RaPacketBuilder(int routerLft) throws Exception {
            InetAddress src = InetAddress.getByName("fe80::1234:abcd");
            ByteBuffer buffer = ByteBuffer.allocate(ICMP6_RA_OPTION_OFFSET);

            buffer.putShort(ETH_ETHERTYPE_OFFSET, (short) ETH_P_IPV6);
            buffer.position(ETH_HEADER_LEN);

            // skip version, tclass, flowlabel; set in build()
            buffer.position(buffer.position() + 4);

            buffer.putShort((short) 0);                     // Payload length; updated later
            buffer.put((byte) IPPROTO_ICMPV6);              // Next header
            buffer.put((byte) 0xff);                        // Hop limit
            buffer.put(src.getAddress());                   // Source address
            buffer.put(IPV6_ALL_NODES_ADDRESS);             // Destination address

            buffer.put((byte) ICMP6_ROUTER_ADVERTISEMENT);  // Type
            buffer.put((byte) 0);                           // Code (0)
            buffer.putShort((short) 0);                     // Checksum (ignored)
            buffer.put((byte) 64);                          // Hop limit
            buffer.put((byte) 0);                           // M/O, reserved
            buffer.putShort((short) routerLft);             // Router lifetime
            // skip reachable time; set in build()
            // skip retransmission timer; set in build();

            mPacket.write(buffer.array(), 0, buffer.capacity());
        }

        public RaPacketBuilder setFlowLabel(int flowLabel) {
            mFlowLabel = flowLabel;
            return this;
        }

        public RaPacketBuilder setReachableTime(int reachable) {
            mReachableTime = reachable;
            return this;
        }

        public RaPacketBuilder setRetransmissionTimer(int retrans) {
            mRetransmissionTimer = retrans;
            return this;
        }

        public RaPacketBuilder addPioOption(int valid, int preferred, String prefixString)
                throws Exception {
            ByteBuffer buffer = ByteBuffer.allocate(ICMP6_PREFIX_OPTION_LEN);

            IpPrefix prefix = new IpPrefix(prefixString);
            buffer.put((byte) ICMP6_PREFIX_OPTION_TYPE);  // Type
            buffer.put((byte) 4);                         // Length in 8-byte units
            buffer.put((byte) prefix.getPrefixLength());  // Prefix length
            buffer.put((byte) 0b11000000);                // L = 1, A = 1
            buffer.putInt(valid);
            buffer.putInt(preferred);
            buffer.putInt(0);                             // Reserved
            buffer.put(prefix.getRawAddress());

            mPacket.write(buffer.array(), 0, buffer.capacity());
            return this;
        }

        public RaPacketBuilder addRioOption(int lifetime, String prefixString) throws Exception {
            IpPrefix prefix = new IpPrefix(prefixString);

            int optionLength;
            if (prefix.getPrefixLength() == 0) {
                optionLength = 1;
            } else if (prefix.getPrefixLength() <= 64) {
                optionLength = 2;
            } else {
                optionLength = 3;
            }

            ByteBuffer buffer = ByteBuffer.allocate(optionLength * 8);

            buffer.put((byte) ICMP6_ROUTE_INFO_OPTION_TYPE);  // Type
            buffer.put((byte) optionLength);                  // Length in 8-byte units
            buffer.put((byte) prefix.getPrefixLength());      // Prefix length
            buffer.put((byte) 0b00011000);                    // Pref = high
            buffer.putInt(lifetime);                          // Lifetime

            byte[] prefixBytes = prefix.getRawAddress();
            buffer.put(prefixBytes, 0, (optionLength - 1) * 8);

            mPacket.write(buffer.array(), 0, buffer.capacity());
            return this;
        }

        public RaPacketBuilder addDnsslOption(int lifetime, String... domains) {
            ByteArrayOutputStream dnssl = new ByteArrayOutputStream();
            for (String domain : domains) {
                for (String label : domain.split(".")) {
                    final byte[] bytes = label.getBytes(StandardCharsets.UTF_8);
                    dnssl.write((byte) bytes.length);
                    dnssl.write(bytes, 0, bytes.length);
                }
                dnssl.write((byte) 0);
            }

            // Extend with 0s to make it 8-byte aligned.
            while (dnssl.size() % 8 != 0) {
                dnssl.write((byte) 0);
            }

            final int length = ICMP6_4_BYTE_OPTION_LEN + dnssl.size();
            ByteBuffer buffer = ByteBuffer.allocate(length);

            buffer.put((byte) ICMP6_DNSSL_OPTION_TYPE);  // Type
            buffer.put((byte) (length / 8));             // Length
            // skip past reserved bytes
            buffer.position(buffer.position() + 2);
            buffer.putInt(lifetime);                     // Lifetime
            buffer.put(dnssl.toByteArray());             // Domain names

            mPacket.write(buffer.array(), 0, buffer.capacity());
            return this;
        }

        public RaPacketBuilder addRdnssOption(int lifetime, String... servers) throws Exception {
            int optionLength = 1 + 2 * servers.length;   // In 8-byte units
            ByteBuffer buffer = ByteBuffer.allocate(optionLength * 8);

            buffer.put((byte) ICMP6_RDNSS_OPTION_TYPE);  // Type
            buffer.put((byte) optionLength);             // Length
            buffer.putShort((short) 0);                  // Reserved
            buffer.putInt(lifetime);                     // Lifetime
            for (String server : servers) {
                buffer.put(InetAddress.getByName(server).getAddress());
            }

            mPacket.write(buffer.array(), 0, buffer.capacity());
            return this;
        }

        public RaPacketBuilder addZeroLengthOption() throws Exception {
            ByteBuffer buffer = ByteBuffer.allocate(ICMP6_4_BYTE_OPTION_LEN);
            buffer.put((byte) ICMP6_PREFIX_OPTION_TYPE);
            buffer.put((byte) 0);

            mPacket.write(buffer.array(), 0, buffer.capacity());
            return this;
        }

        public byte[] build() {
            ByteBuffer buffer = ByteBuffer.wrap(mPacket.toByteArray());
            // IPv6, traffic class = 0, flow label = mFlowLabel
            buffer.putInt(IP_HEADER_OFFSET, 0x60000000 | (0xFFFFF & mFlowLabel));
            buffer.putShort(IPV6_PAYLOAD_LENGTH_OFFSET, (short) buffer.capacity());

            buffer.position(ICMP6_RA_REACHABLE_TIME_OFFSET);
            buffer.putInt(mReachableTime);
            buffer.putInt(mRetransmissionTimer);

            return buffer.array();
        }
    }

    private byte[] buildLargeRa() throws Exception {
        RaPacketBuilder builder = new RaPacketBuilder(1800 /* router lft */);

        builder.addRioOption(1200, "64:ff9b::/96");
        builder.addRdnssOption(7200, "2001:db8:1::1", "2001:db8:1::2");
        builder.addRioOption(2100, "2000::/3");
        builder.addRioOption(2400, "::/0");
        builder.addPioOption(600, 300, "2001:db8:a::/64");
        builder.addRioOption(1500, "2001:db8:c:d::/64");
        builder.addPioOption(86400, 43200, "fd95:d1e:12::/64");

        return builder.build();
    }

    @Test
    public void testRaToString() throws Exception {
        MockIpClientCallback cb = new MockIpClientCallback();
        ApfConfiguration config = getDefaultConfig();
        TestApfFilter apfFilter = new TestApfFilter(mContext, config, cb, mNetworkQuirkMetrics);

        byte[] packet = buildLargeRa();
        ApfFilter.Ra ra = apfFilter.new Ra(packet, packet.length);
        String expected = "RA fe80::1234:abcd -> ff02::1 1800s "
                + "2001:db8:a::/64 600s/300s fd95:d1e:12::/64 86400s/43200s "
                + "DNS 7200s 2001:db8:1::1 2001:db8:1::2 "
                + "RIO 1200s 64:ff9b::/96 RIO 2100s 2000::/3 "
                + "RIO 2400s ::/0 RIO 1500s 2001:db8:c:d::/64 ";
        assertEquals(expected, ra.toString());
    }

    // Verify that the last program pushed to the IpClient.Callback properly filters the
    // given packet for the given lifetime.
    private void verifyRaLifetime(byte[] program, ByteBuffer packet, int lifetime) {
        verifyRaLifetime(program, packet, lifetime, 0);
    }

    // Verify that the last program pushed to the IpClient.Callback properly filters the
    // given packet for the given lifetime and programInstallTime. programInstallTime is
    // the time difference between when RA is last seen and the program is installed.
    private void verifyRaLifetime(byte[] program, ByteBuffer packet, int lifetime,
            int programInstallTime) {
        final int FRACTION_OF_LIFETIME = 6;
        final int ageLimit = lifetime / FRACTION_OF_LIFETIME - programInstallTime;

        // Verify new program should drop RA for 1/6th its lifetime and pass afterwards.
        assertDrop(program, packet.array());
        assertDrop(program, packet.array(), ageLimit);
        assertPass(program, packet.array(), ageLimit + 1);
        assertPass(program, packet.array(), lifetime);
        // Verify RA checksum is ignored
        final short originalChecksum = packet.getShort(ICMP6_RA_CHECKSUM_OFFSET);
        packet.putShort(ICMP6_RA_CHECKSUM_OFFSET, (short)12345);
        assertDrop(program, packet.array());
        packet.putShort(ICMP6_RA_CHECKSUM_OFFSET, (short)-12345);
        assertDrop(program, packet.array());
        packet.putShort(ICMP6_RA_CHECKSUM_OFFSET, originalChecksum);

        // Verify other changes to RA (e.g., a change in the source address) make it not match.
        final int offset = IPV6_SRC_ADDR_OFFSET + 5;
        final byte originalByte = packet.get(offset);
        packet.put(offset, (byte) (~originalByte));
        assertPass(program, packet.array());
        packet.put(offset, originalByte);
        assertDrop(program, packet.array());
    }

    // Test that when ApfFilter is shown the given packet, it generates a program to filter it
    // for the given lifetime.
    private void verifyRaLifetime(TestApfFilter apfFilter, MockIpClientCallback ipClientCallback,
            ByteBuffer packet, int lifetime) throws IOException, ErrnoException {
        // Verify new program generated if ApfFilter witnesses RA
        apfFilter.pretendPacketReceived(packet.array());
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();
        verifyRaLifetime(program, packet, lifetime);
    }

    private void assertInvalidRa(TestApfFilter apfFilter, MockIpClientCallback ipClientCallback,
            ByteBuffer packet) throws IOException, ErrnoException {
        apfFilter.pretendPacketReceived(packet.array());
        ipClientCallback.assertNoProgramUpdate();
    }

    @Test
    public void testApfFilterRa() throws Exception {
        MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        ApfConfiguration config = getDefaultConfig();
        config.multicastFilter = DROP_MULTICAST;
        config.ieee802_3Filter = DROP_802_3_FRAMES;
        TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        final int ROUTER_LIFETIME = 1000;
        final int PREFIX_VALID_LIFETIME = 200;
        final int PREFIX_PREFERRED_LIFETIME = 100;
        final int RDNSS_LIFETIME  = 300;
        final int ROUTE_LIFETIME  = 400;
        // Note that lifetime of 2000 will be ignored in favor of shorter route lifetime of 1000.
        final int DNSSL_LIFETIME  = 2000;

        // Verify RA is passed the first time
        RaPacketBuilder ra = new RaPacketBuilder(ROUTER_LIFETIME);
        ByteBuffer basePacket = ByteBuffer.wrap(ra.build());
        assertPass(program, basePacket.array());

        verifyRaLifetime(apfFilter, ipClientCallback, basePacket, ROUTER_LIFETIME);

        ra = new RaPacketBuilder(ROUTER_LIFETIME);
        // Check that changes are ignored in every byte of the flow label.
        ra.setFlowLabel(0x56789);
        ByteBuffer newFlowLabelPacket = ByteBuffer.wrap(ra.build());

        // Ensure zero-length options cause the packet to be silently skipped.
        // Do this before we test other packets. http://b/29586253
        ra = new RaPacketBuilder(ROUTER_LIFETIME);
        ra.addZeroLengthOption();
        ByteBuffer zeroLengthOptionPacket = ByteBuffer.wrap(ra.build());
        assertInvalidRa(apfFilter, ipClientCallback, zeroLengthOptionPacket);

        // Generate several RAs with different options and lifetimes, and verify when
        // ApfFilter is shown these packets, it generates programs to filter them for the
        // appropriate lifetime.
        ra = new RaPacketBuilder(ROUTER_LIFETIME);
        ra.addPioOption(PREFIX_VALID_LIFETIME, PREFIX_PREFERRED_LIFETIME, "2001:db8::/64");
        ByteBuffer prefixOptionPacket = ByteBuffer.wrap(ra.build());
        verifyRaLifetime(
                apfFilter, ipClientCallback, prefixOptionPacket, PREFIX_PREFERRED_LIFETIME);

        ra = new RaPacketBuilder(ROUTER_LIFETIME);
        ra.addRdnssOption(RDNSS_LIFETIME, "2001:4860:4860::8888", "2001:4860:4860::8844");
        ByteBuffer rdnssOptionPacket = ByteBuffer.wrap(ra.build());
        verifyRaLifetime(apfFilter, ipClientCallback, rdnssOptionPacket, RDNSS_LIFETIME);

        final int lowLifetime = 60;
        ra = new RaPacketBuilder(ROUTER_LIFETIME);
        ra.addRdnssOption(lowLifetime, "2620:fe::9");
        ByteBuffer lowLifetimeRdnssOptionPacket = ByteBuffer.wrap(ra.build());
        verifyRaLifetime(apfFilter, ipClientCallback, lowLifetimeRdnssOptionPacket,
                ROUTER_LIFETIME);

        ra = new RaPacketBuilder(ROUTER_LIFETIME);
        ra.addRioOption(ROUTE_LIFETIME, "64:ff9b::/96");
        ByteBuffer routeInfoOptionPacket = ByteBuffer.wrap(ra.build());
        verifyRaLifetime(apfFilter, ipClientCallback, routeInfoOptionPacket, ROUTE_LIFETIME);

        // Check that RIOs differing only in the first 4 bytes are different.
        ra = new RaPacketBuilder(ROUTER_LIFETIME);
        ra.addRioOption(ROUTE_LIFETIME, "64:ff9b::/64");
        // Packet should be passed because it is different.
        program = ipClientCallback.assertProgramUpdateAndGet();
        assertPass(program, ra.build());

        ra = new RaPacketBuilder(ROUTER_LIFETIME);
        ra.addDnsslOption(DNSSL_LIFETIME, "test.example.com", "one.more.example.com");
        ByteBuffer dnsslOptionPacket = ByteBuffer.wrap(ra.build());
        verifyRaLifetime(apfFilter, ipClientCallback, dnsslOptionPacket, ROUTER_LIFETIME);

        ByteBuffer largeRaPacket = ByteBuffer.wrap(buildLargeRa());
        verifyRaLifetime(apfFilter, ipClientCallback, largeRaPacket, 300);

        // Verify that current program filters all the RAs (note: ApfFilter.MAX_RAS == 10).
        program = ipClientCallback.assertProgramUpdateAndGet();
        verifyRaLifetime(program, basePacket, ROUTER_LIFETIME);
        verifyRaLifetime(program, newFlowLabelPacket, ROUTER_LIFETIME);
        verifyRaLifetime(program, prefixOptionPacket, PREFIX_PREFERRED_LIFETIME);
        verifyRaLifetime(program, rdnssOptionPacket, RDNSS_LIFETIME);
        verifyRaLifetime(program, lowLifetimeRdnssOptionPacket, ROUTER_LIFETIME);
        verifyRaLifetime(program, routeInfoOptionPacket, ROUTE_LIFETIME);
        verifyRaLifetime(program, dnsslOptionPacket, ROUTER_LIFETIME);
        verifyRaLifetime(program, largeRaPacket, 300);

        apfFilter.shutdown();
    }

    @Test
    public void testRaWithDifferentReachableTimeAndRetransTimer() throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        final ApfConfiguration config = getDefaultConfig();
        config.multicastFilter = DROP_MULTICAST;
        config.ieee802_3Filter = DROP_802_3_FRAMES;
        final TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();
        final int RA_REACHABLE_TIME = 1800;
        final int RA_RETRANSMISSION_TIMER = 1234;

        // Create an Ra packet without options
        // Reachable time = 1800, retransmission timer = 1234
        RaPacketBuilder ra = new RaPacketBuilder(1800 /* router lft */);
        ra.setReachableTime(RA_REACHABLE_TIME);
        ra.setRetransmissionTimer(RA_RETRANSMISSION_TIMER);
        byte[] raPacket = ra.build();
        // First RA passes filter
        assertPass(program, raPacket);

        // Assume apf is shown the given RA, it generates program to filter it.
        apfFilter.pretendPacketReceived(raPacket);
        program = ipClientCallback.assertProgramUpdateAndGet();
        assertDrop(program, raPacket);

        // A packet with different reachable time should be passed.
        // Reachable time = 2300, retransmission timer = 1234
        ra.setReachableTime(RA_REACHABLE_TIME + 500);
        raPacket = ra.build();
        assertPass(program, raPacket);

        // A packet with different retransmission timer should be passed.
        // Reachable time = 1800, retransmission timer = 2234
        ra.setReachableTime(RA_REACHABLE_TIME);
        ra.setRetransmissionTimer(RA_RETRANSMISSION_TIMER + 1000);
        raPacket = ra.build();
        assertPass(program, raPacket);
    }

    // The ByteBuffer is always created by ByteBuffer#wrap in the helper functions
    @SuppressWarnings("ByteBufferBackingArray")
    @Test
    public void testRaWithProgramInstalledSomeTimeAfterLastSeen() throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        final ApfConfiguration config = getDefaultConfig();
        config.multicastFilter = DROP_MULTICAST;
        config.ieee802_3Filter = DROP_802_3_FRAMES;
        final TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        final int routerLifetime = 1000;
        final int timePassedSeconds = 12;

        // Verify that when the program is generated and installed some time after RA is last seen
        // it should be installed with the correct remaining lifetime.
        ByteBuffer basePacket = ByteBuffer.wrap(new RaPacketBuilder(routerLifetime).build());
        verifyRaLifetime(apfFilter, ipClientCallback, basePacket, routerLifetime);
        apfFilter.increaseCurrentTimeSeconds(timePassedSeconds);
        synchronized (apfFilter) {
            apfFilter.installNewProgramLocked();
        }
        program = ipClientCallback.assertProgramUpdateAndGet();
        verifyRaLifetime(program, basePacket, routerLifetime, timePassedSeconds);

        // Packet should be passed if the program is installed after 1/6 * lifetime from last seen
        apfFilter.increaseCurrentTimeSeconds((int) (routerLifetime / 6) - timePassedSeconds - 1);
        synchronized (apfFilter) {
            apfFilter.installNewProgramLocked();
        }
        program = ipClientCallback.assertProgramUpdateAndGet();
        assertDrop(program, basePacket.array());
        apfFilter.increaseCurrentTimeSeconds(1);
        synchronized (apfFilter) {
            apfFilter.installNewProgramLocked();
        }
        program = ipClientCallback.assertProgramUpdateAndGet();
        assertPass(program, basePacket.array());

        apfFilter.shutdown();
    }

    /**
     * Stage a file for testing, i.e. make it native accessible. Given a resource ID,
     * copy that resource into the app's data directory and return the path to it.
     */
    private String stageFile(int rawId) throws Exception {
        File file = new File(InstrumentationRegistry.getContext().getFilesDir(), "staged_file");
        new File(file.getParent()).mkdirs();
        InputStream in = null;
        OutputStream out = null;
        try {
            in = InstrumentationRegistry.getContext().getResources().openRawResource(rawId);
            out = new FileOutputStream(file);
            Streams.copy(in, out);
        } finally {
            if (in != null) in.close();
            if (out != null) out.close();
        }
        return file.getAbsolutePath();
    }

    private static void put(ByteBuffer buffer, int position, byte[] bytes) {
        final int original = buffer.position();
        buffer.position(position);
        buffer.put(bytes);
        buffer.position(original);
    }

    @Test
    public void testRaParsing() throws Exception {
        final int maxRandomPacketSize = 512;
        final Random r = new Random();
        MockIpClientCallback cb = new MockIpClientCallback();
        ApfConfiguration config = getDefaultConfig();
        config.multicastFilter = DROP_MULTICAST;
        config.ieee802_3Filter = DROP_802_3_FRAMES;
        TestApfFilter apfFilter = new TestApfFilter(mContext, config, cb, mNetworkQuirkMetrics);
        for (int i = 0; i < 1000; i++) {
            byte[] packet = new byte[r.nextInt(maxRandomPacketSize + 1)];
            r.nextBytes(packet);
            try {
                apfFilter.new Ra(packet, packet.length);
            } catch (ApfFilter.InvalidRaException e) {
            } catch (Exception e) {
                throw new Exception("bad packet: " + HexDump.toHexString(packet), e);
            }
        }
        apfFilter.shutdown();
    }

    @Test
    public void testRaProcessing() throws Exception {
        final int maxRandomPacketSize = 512;
        final Random r = new Random();
        MockIpClientCallback cb = new MockIpClientCallback();
        ApfConfiguration config = getDefaultConfig();
        config.multicastFilter = DROP_MULTICAST;
        config.ieee802_3Filter = DROP_802_3_FRAMES;
        TestApfFilter apfFilter = new TestApfFilter(mContext, config, cb, mNetworkQuirkMetrics);
        for (int i = 0; i < 1000; i++) {
            byte[] packet = new byte[r.nextInt(maxRandomPacketSize + 1)];
            r.nextBytes(packet);
            try {
                apfFilter.processRa(packet, packet.length);
            } catch (Exception e) {
                throw new Exception("bad packet: " + HexDump.toHexString(packet), e);
            }
        }
        apfFilter.shutdown();
    }

    @Test
    public void testMatchedRaUpdatesLifetime() throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        final TestApfFilter apfFilter = new TestApfFilter(mContext, getDefaultConfig(),
                ipClientCallback, mNetworkQuirkMetrics);

        // Create an RA and build an APF program
        byte[] ra = new RaPacketBuilder(1800 /* router lifetime */).build();
        apfFilter.pretendPacketReceived(ra);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        // lifetime dropped significantly, assert pass
        ra = new RaPacketBuilder(200 /* router lifetime */).build();
        assertPass(program, ra);

        // update program with the new RA
        apfFilter.pretendPacketReceived(ra);
        program = ipClientCallback.assertProgramUpdateAndGet();

        // assert program was updated and new lifetimes were taken into account.
        assertDrop(program, ra);
        apfFilter.shutdown();
    }

    // Test for go/apf-ra-filter Case 1a.
    // Old lifetime is 0
    @Test
    public void testAcceptRaMinLftCase1a() throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        // configure accept_ra_min_lft
        final ApfConfiguration config = getDefaultConfig();
        config.acceptRaMinLft = 180;
        final TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);

        // Create an initial RA and build an APF program
        byte[] ra = new RaPacketBuilder(1800 /* router lifetime */)
                .addPioOption(1800 /*valid*/, 0 /*preferred*/, "2001:db8::/64")
                .build();

        apfFilter.pretendPacketReceived(ra);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        // repeated RA is dropped
        assertDrop(program, ra);

        // PIO preferred lifetime increases
        ra = new RaPacketBuilder(1800 /* router lifetime */)
                .addPioOption(1800 /*valid*/, 1 /*preferred*/, "2001:db8::/64")
                .build();
        assertPass(program, ra);
        apfFilter.shutdown();
    }

    // Test for go/apf-ra-filter Case 2a.
    // Old lifetime is > 0
    @Test
    public void testAcceptRaMinLftCase2a() throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        // configure accept_ra_min_lft
        final ApfConfiguration config = getDefaultConfig();
        config.acceptRaMinLft = 180;
        final TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);

        // Create an initial RA and build an APF program
        byte[] ra = new RaPacketBuilder(1800 /* router lifetime */)
                .addPioOption(1800 /*valid*/, 100 /*preferred*/, "2001:db8::/64")
                .build();

        apfFilter.pretendPacketReceived(ra);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        // repeated RA is dropped
        assertDrop(program, ra);

        // PIO preferred lifetime increases
        ra = new RaPacketBuilder(1800 /* router lifetime */)
                .addPioOption(1800 /*valid*/, 101 /*preferred*/, "2001:db8::/64")
                .build();
        assertPass(program, ra);

        // PIO preferred lifetime decreases significantly
        ra = new RaPacketBuilder(1800 /* router lifetime */)
                .addPioOption(1800 /*valid*/, 33 /*preferred*/, "2001:db8::/64")
                .build();
        assertPass(program, ra);
        apfFilter.shutdown();
    }


    // Test for go/apf-ra-filter Case 1b.
    // Old lifetime is 0
    @Test
    public void testAcceptRaMinLftCase1b() throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        // configure accept_ra_min_lft
        final ApfConfiguration config = getDefaultConfig();
        config.acceptRaMinLft = 180;
        final TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);

        // Create an initial RA and build an APF program
        byte[] ra = new RaPacketBuilder(0 /* router lifetime */).build();

        apfFilter.pretendPacketReceived(ra);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        // repeated RA is dropped
        assertDrop(program, ra);

        // lifetime increases below accept_ra_min_lft
        ra = new RaPacketBuilder(179 /* router lifetime */).build();
        assertDrop(program, ra);

        // lifetime increases to accept_ra_min_lft
        ra = new RaPacketBuilder(180 /* router lifetime */).build();
        assertPass(program, ra);
        apfFilter.shutdown();
    }


    // Test for go/apf-ra-filter Case 2b.
    // Old lifetime is < accept_ra_min_lft (but not 0).
    @Test
    public void testAcceptRaMinLftCase2b() throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        // configure accept_ra_min_lft
        final ApfConfiguration config = getDefaultConfig();
        config.acceptRaMinLft = 180;
        final TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);

        // Create an initial RA and build an APF program
        byte[] ra = new RaPacketBuilder(100 /* router lifetime */).build();

        apfFilter.pretendPacketReceived(ra);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        // repeated RA is dropped
        assertDrop(program, ra);

        // lifetime increases
        ra = new RaPacketBuilder(101 /* router lifetime */).build();
        assertDrop(program, ra);

        // lifetime decreases significantly
        ra = new RaPacketBuilder(1 /* router lifetime */).build();
        assertDrop(program, ra);

        // equals accept_ra_min_lft
        ra = new RaPacketBuilder(180 /* router lifetime */).build();
        assertPass(program, ra);

        // lifetime is 0
        ra = new RaPacketBuilder(0 /* router lifetime */).build();
        assertPass(program, ra);
        apfFilter.shutdown();
    }

    // Test for go/apf-ra-filter Case 3b.
    // Old lifetime is >= accept_ra_min_lft and <= 3 * accept_ra_min_lft
    @Test
    public void testAcceptRaMinLftCase3b() throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        // configure accept_ra_min_lft
        final ApfConfiguration config = getDefaultConfig();
        config.acceptRaMinLft = 180;
        final TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);

        // Create an initial RA and build an APF program
        byte[] ra = new RaPacketBuilder(200 /* router lifetime */).build();

        apfFilter.pretendPacketReceived(ra);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        // repeated RA is dropped
        assertDrop(program, ra);

        // lifetime increases
        ra = new RaPacketBuilder(201 /* router lifetime */).build();
        assertPass(program, ra);

        // lifetime is below accept_ra_min_lft (but not 0)
        ra = new RaPacketBuilder(1 /* router lifetime */).build();
        assertDrop(program, ra);

        // lifetime is 0
        ra = new RaPacketBuilder(0 /* router lifetime */).build();
        assertPass(program, ra);
        apfFilter.shutdown();
    }

    // Test for go/apf-ra-filter Case 4b.
    // Old lifetime is > 3 * accept_ra_min_lft
    @Test
    public void testAcceptRaMinLftCase4b() throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        // configure accept_ra_min_lft
        final ApfConfiguration config = getDefaultConfig();
        config.acceptRaMinLft = 180;
        final TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);

        // Create an initial RA and build an APF program
        byte[] ra = new RaPacketBuilder(1800 /* router lifetime */).build();

        apfFilter.pretendPacketReceived(ra);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        // repeated RA is dropped
        assertDrop(program, ra);

        // lifetime increases
        ra = new RaPacketBuilder(1801 /* router lifetime */).build();
        assertPass(program, ra);

        // lifetime is 1/3 of old lft
        ra = new RaPacketBuilder(600 /* router lifetime */).build();
        assertDrop(program, ra);

        // lifetime is below 1/3 of old lft
        ra = new RaPacketBuilder(599 /* router lifetime */).build();
        assertPass(program, ra);

        // lifetime is below accept_ra_min_lft (but not 0)
        ra = new RaPacketBuilder(1 /* router lifetime */).build();
        assertDrop(program, ra);

        // lifetime is 0
        ra = new RaPacketBuilder(0 /* router lifetime */).build();
        assertPass(program, ra);
        apfFilter.shutdown();
    }

    @Test
    public void testRaFilterIsUpdated() throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        // configure accept_ra_min_lft
        final ApfConfiguration config = getDefaultConfig();
        config.acceptRaMinLft = 180;
        final TestApfFilter apfFilter = new TestApfFilter(mContext, config, ipClientCallback,
                mNetworkQuirkMetrics);

        // Create an initial RA and build an APF program
        byte[] ra = new RaPacketBuilder(1800 /* router lifetime */).build();
        apfFilter.pretendPacketReceived(ra);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        // repeated RA is dropped.
        assertDrop(program, ra);

        // updated RA is passed, repeated RA is dropped after program update.
        ra = new RaPacketBuilder(599 /* router lifetime */).build();
        assertPass(program, ra);
        apfFilter.pretendPacketReceived(ra);
        program = ipClientCallback.assertProgramUpdateAndGet();
        assertDrop(program, ra);

        ra = new RaPacketBuilder(180 /* router lifetime */).build();
        assertPass(program, ra);
        apfFilter.pretendPacketReceived(ra);
        program = ipClientCallback.assertProgramUpdateAndGet();
        assertDrop(program, ra);

        ra = new RaPacketBuilder(0 /* router lifetime */).build();
        assertPass(program, ra);
        apfFilter.pretendPacketReceived(ra);
        program = ipClientCallback.assertProgramUpdateAndGet();
        assertDrop(program, ra);

        ra = new RaPacketBuilder(180 /* router lifetime */).build();
        assertPass(program, ra);
        apfFilter.pretendPacketReceived(ra);
        program = ipClientCallback.assertProgramUpdateAndGet();
        assertDrop(program, ra);

        ra = new RaPacketBuilder(599 /* router lifetime */).build();
        assertPass(program, ra);
        apfFilter.pretendPacketReceived(ra);
        program = ipClientCallback.assertProgramUpdateAndGet();
        assertDrop(program, ra);

        ra = new RaPacketBuilder(1800 /* router lifetime */).build();
        assertPass(program, ra);
        apfFilter.pretendPacketReceived(ra);
        program = ipClientCallback.assertProgramUpdateAndGet();
        assertDrop(program, ra);
        apfFilter.shutdown();
    }

    @Test
    public void testBroadcastAddress() throws Exception {
        assertEqualsIp("255.255.255.255", ApfFilter.ipv4BroadcastAddress(IPV4_ANY_HOST_ADDR, 0));
        assertEqualsIp("0.0.0.0", ApfFilter.ipv4BroadcastAddress(IPV4_ANY_HOST_ADDR, 32));
        assertEqualsIp("0.0.3.255", ApfFilter.ipv4BroadcastAddress(IPV4_ANY_HOST_ADDR, 22));
        assertEqualsIp("0.255.255.255", ApfFilter.ipv4BroadcastAddress(IPV4_ANY_HOST_ADDR, 8));

        assertEqualsIp("255.255.255.255", ApfFilter.ipv4BroadcastAddress(MOCK_IPV4_ADDR, 0));
        assertEqualsIp("10.0.0.1", ApfFilter.ipv4BroadcastAddress(MOCK_IPV4_ADDR, 32));
        assertEqualsIp("10.0.0.255", ApfFilter.ipv4BroadcastAddress(MOCK_IPV4_ADDR, 24));
        assertEqualsIp("10.0.255.255", ApfFilter.ipv4BroadcastAddress(MOCK_IPV4_ADDR, 16));
    }

    public void assertEqualsIp(String expected, int got) throws Exception {
        int want = Inet4AddressUtils.inet4AddressToIntHTH(
                (Inet4Address) InetAddresses.parseNumericAddress(expected));
        assertEquals(want, got);
    }

    private TestAndroidPacketFilter makeTestApfFilter(ApfConfiguration config,
            MockIpClientCallback ipClientCallback, boolean isLegacy) throws Exception {
        final TestAndroidPacketFilter apfFilter;
        if (isLegacy) {
            apfFilter = new TestLegacyApfFilter(mContext, config, ipClientCallback,
                    mIpConnectivityLog, mNetworkQuirkMetrics, mDependencies, mClock);
        } else {
            apfFilter = new TestApfFilter(mContext, config, ipClientCallback, mNetworkQuirkMetrics,
                    mDependencies, mClock);
        }
        return apfFilter;
    }

    // LegacyApfFilter ignores zero lifetime RAs (doesn't update program) but ApfFilter won't.
    private void verifyUpdateProgramForZeroLifetimeRa(MockIpClientCallback ipClientCallback,
            boolean isLegacy) {
        if (isLegacy) {
            ipClientCallback.assertNoProgramUpdate();
        } else {
            ipClientCallback.assertProgramUpdateAndGet();
        }
    }

    private void verifyInstallPacketFilterFailure(boolean isLegacy) throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback(false);
        final ApfConfiguration config = getDefaultConfig();
        final TestAndroidPacketFilter apfFilter =
                makeTestApfFilter(config, ipClientCallback, isLegacy);
        verify(mNetworkQuirkMetrics).setEvent(NetworkQuirkEvent.QE_APF_INSTALL_FAILURE);
        verify(mNetworkQuirkMetrics).statsWrite();
        reset(mNetworkQuirkMetrics);
        synchronized (apfFilter) {
            apfFilter.installNewProgramLocked();
        }
        verify(mNetworkQuirkMetrics).setEvent(NetworkQuirkEvent.QE_APF_INSTALL_FAILURE);
        verify(mNetworkQuirkMetrics).statsWrite();
        apfFilter.shutdown();
    }

    @Test
    public void testInstallPacketFilterFailure() throws Exception {
        verifyInstallPacketFilterFailure(false /* isLegacy */);
    }

    @Test
    public void testInstallPacketFilterFailure_LegacyApfFilter() throws Exception {
        verifyInstallPacketFilterFailure(true /* isLegacy */);
    }

    private void verifyApfProgramOverSize(boolean isLegacy) throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        final ApfConfiguration config = getDefaultConfig();
        final ApfCapabilities capabilities = new ApfCapabilities(2, 512, ARPHRD_ETHER);
        config.apfCapabilities = capabilities;
        final TestAndroidPacketFilter apfFilter =
                makeTestApfFilter(config, ipClientCallback, isLegacy);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();
        final byte[] ra = buildLargeRa();
        apfFilter.pretendPacketReceived(ra);
        // The generated program size will be 529, which is larger than 512
        program = ipClientCallback.assertProgramUpdateAndGet();
        verify(mNetworkQuirkMetrics).setEvent(NetworkQuirkEvent.QE_APF_OVER_SIZE_FAILURE);
        verify(mNetworkQuirkMetrics).statsWrite();
        apfFilter.shutdown();
    }

    @Test
    public void testApfProgramOverSize() throws Exception {
        verifyApfProgramOverSize(false /* isLegacy */);
    }

    @Test
    public void testApfProgramOverSize_LegacyApfFilter() throws Exception {
        verifyApfProgramOverSize(true /* isLegacy */);
    }

    private void verifyGenerateApfProgramException(boolean isLegacy) throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        final ApfConfiguration config = getDefaultConfig();
        final TestAndroidPacketFilter apfFilter;
        if (isLegacy) {
            apfFilter = new TestLegacyApfFilter(mContext, config, ipClientCallback,
                    mIpConnectivityLog, mNetworkQuirkMetrics, mDependencies,
                    true /* throwsExceptionWhenGeneratesProgram */);
        } else {
            apfFilter = new TestApfFilter(mContext, config, ipClientCallback, mNetworkQuirkMetrics,
                    mDependencies, true /* throwsExceptionWhenGeneratesProgram */);
        }
        synchronized (apfFilter) {
            apfFilter.installNewProgramLocked();
        }
        verify(mNetworkQuirkMetrics).setEvent(NetworkQuirkEvent.QE_APF_GENERATE_FILTER_EXCEPTION);
        verify(mNetworkQuirkMetrics).statsWrite();
        apfFilter.shutdown();
    }

    @Test
    public void testGenerateApfProgramException() throws Exception {
        verifyGenerateApfProgramException(false /* isLegacy */);
    }

    @Test
    public void testGenerateApfProgramException_LegacyApfFilter() throws Exception {
        verifyGenerateApfProgramException(true /* isLegacy */);
    }

    private void verifyApfSessionInfoMetrics(boolean isLegacy) throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        final ApfConfiguration config = getDefaultConfig();
        final ApfCapabilities capabilities = new ApfCapabilities(4, 4096, ARPHRD_ETHER);
        config.apfCapabilities = capabilities;
        final long startTimeMs = 12345;
        final long durationTimeMs = config.minMetricsSessionDurationMs;
        doReturn(startTimeMs).when(mClock).elapsedRealtime();
        final TestAndroidPacketFilter apfFilter =
                makeTestApfFilter(config, ipClientCallback, isLegacy);
        int maxProgramSize = 0;
        int numProgramUpdated = 0;
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();
        maxProgramSize = Math.max(maxProgramSize, program.length);
        numProgramUpdated++;

        final byte[] data = new byte[Counter.totalSize()];
        final byte[] expectedData = data.clone();
        final int totalPacketsCounterIdx = Counter.totalSize() + Counter.TOTAL_PACKETS.offset();
        final int passedIpv6IcmpCounterIdx =
                Counter.totalSize() + Counter.PASSED_IPV6_ICMP.offset();
        final int droppedIpv4MulticastIdx =
                Counter.totalSize() + Counter.DROPPED_IPV4_MULTICAST.offset();

        // Receive an RA packet (passed).
        final byte[] ra = buildLargeRa();
        expectedData[totalPacketsCounterIdx + 3] += 1;
        expectedData[passedIpv6IcmpCounterIdx + 3] += 1;
        assertDataMemoryContents(PASS, program, ra, data, expectedData);
        apfFilter.pretendPacketReceived(ra);
        program = ipClientCallback.assertProgramUpdateAndGet();
        maxProgramSize = Math.max(maxProgramSize, program.length);
        numProgramUpdated++;

        apfFilter.setMulticastFilter(true);
        // setMulticastFilter will trigger program installation.
        program = ipClientCallback.assertProgramUpdateAndGet();
        maxProgramSize = Math.max(maxProgramSize, program.length);
        numProgramUpdated++;

        // Receive IPv4 multicast packet (dropped).
        final byte[] multicastIpv4Addr = {(byte) 224, 0, 0, 1};
        ByteBuffer mcastv4packet = makeIpv4Packet(IPPROTO_UDP);
        put(mcastv4packet, IPV4_DEST_ADDR_OFFSET, multicastIpv4Addr);
        expectedData[totalPacketsCounterIdx + 3] += 1;
        expectedData[droppedIpv4MulticastIdx + 3] += 1;
        assertDataMemoryContents(DROP, program, mcastv4packet.array(), data, expectedData);

        // Set data snapshot and update counters.
        apfFilter.setDataSnapshot(data);

        // Write metrics data to statsd pipeline when shutdown.
        doReturn(startTimeMs + durationTimeMs).when(mClock).elapsedRealtime();
        apfFilter.shutdown();
        verify(mApfSessionInfoMetrics).setVersion(4);
        verify(mApfSessionInfoMetrics).setMemorySize(4096);

        // Verify Counters
        final Map<Counter, Long> expectedCounters = Map.of(Counter.TOTAL_PACKETS, 2L,
                Counter.PASSED_IPV6_ICMP, 1L, Counter.DROPPED_IPV4_MULTICAST, 1L);
        final ArgumentCaptor<Counter> counterCaptor = ArgumentCaptor.forClass(Counter.class);
        final ArgumentCaptor<Long> valueCaptor = ArgumentCaptor.forClass(Long.class);
        verify(mApfSessionInfoMetrics, times(expectedCounters.size())).addApfCounter(
                counterCaptor.capture(), valueCaptor.capture());
        final List<Counter> counters = counterCaptor.getAllValues();
        final List<Long> values = valueCaptor.getAllValues();
        final ArrayMap<Counter, Long> capturedCounters = new ArrayMap<>();
        for (int i = 0; i < counters.size(); i++) {
            capturedCounters.put(counters.get(i), values.get(i));
        }
        assertEquals(expectedCounters, capturedCounters);

        verify(mApfSessionInfoMetrics).setApfSessionDurationSeconds(
                (int) (durationTimeMs / DateUtils.SECOND_IN_MILLIS));
        verify(mApfSessionInfoMetrics).setNumOfTimesApfProgramUpdated(numProgramUpdated);
        verify(mApfSessionInfoMetrics).setMaxProgramSize(maxProgramSize);
        verify(mApfSessionInfoMetrics).statsWrite();
    }

    @Test
    public void testApfSessionInfoMetrics() throws Exception {
        verifyApfSessionInfoMetrics(false /* isLegacy */);
    }

    @Test
    public void testApfSessionInfoMetrics_LegacyApfFilter() throws Exception {
        verifyApfSessionInfoMetrics(true /* isLegacy */);
    }

    private void verifyIpClientRaInfoMetrics(boolean isLegacy) throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        final ApfConfiguration config = getDefaultConfig();
        final long startTimeMs = 12345;
        final long durationTimeMs = config.minMetricsSessionDurationMs;
        doReturn(startTimeMs).when(mClock).elapsedRealtime();
        final TestAndroidPacketFilter apfFilter =
                makeTestApfFilter(config, ipClientCallback, isLegacy);
        byte[] program = ipClientCallback.assertProgramUpdateAndGet();

        final int routerLifetime = 1000;
        final int prefixValidLifetime = 200;
        final int prefixPreferredLifetime = 100;
        final int rdnssLifetime  = 300;
        final int routeLifetime  = 400;

        // Construct 2 RAs with partial lifetimes larger than predefined constants
        final RaPacketBuilder ra1 = new RaPacketBuilder(routerLifetime);
        ra1.addPioOption(prefixValidLifetime + 123, prefixPreferredLifetime, "2001:db8::/64");
        ra1.addRdnssOption(rdnssLifetime, "2001:4860:4860::8888", "2001:4860:4860::8844");
        ra1.addRioOption(routeLifetime + 456, "64:ff9b::/96");
        final RaPacketBuilder ra2 = new RaPacketBuilder(routerLifetime + 123);
        ra2.addPioOption(prefixValidLifetime, prefixPreferredLifetime, "2001:db9::/64");
        ra2.addRdnssOption(rdnssLifetime + 456, "2001:4860:4860::8888", "2001:4860:4860::8844");
        ra2.addRioOption(routeLifetime, "64:ff9b::/96");

        // Construct an invalid RA packet
        final RaPacketBuilder raInvalid = new RaPacketBuilder(routerLifetime);
        raInvalid.addZeroLengthOption();

        // Construct 4 different kinds of zero lifetime RAs
        final RaPacketBuilder raZeroRouterLifetime = new RaPacketBuilder(0 /* routerLft */);
        final RaPacketBuilder raZeroPioValidLifetime = new RaPacketBuilder(routerLifetime);
        raZeroPioValidLifetime.addPioOption(0, prefixPreferredLifetime, "2001:db10::/64");
        final RaPacketBuilder raZeroRdnssLifetime = new RaPacketBuilder(routerLifetime);
        raZeroRdnssLifetime.addPioOption(
                prefixValidLifetime, prefixPreferredLifetime, "2001:db11::/64");
        raZeroRdnssLifetime.addRdnssOption(0, "2001:4860:4860::8888", "2001:4860:4860::8844");
        final RaPacketBuilder raZeroRioRouteLifetime = new RaPacketBuilder(routerLifetime);
        raZeroRioRouteLifetime.addPioOption(
                prefixValidLifetime, prefixPreferredLifetime, "2001:db12::/64");
        raZeroRioRouteLifetime.addRioOption(0, "64:ff9b::/96");

        // Inject RA packets. Calling assertProgramUpdateAndGet()/assertNoProgramUpdate() is to make
        // sure that the RA packet has been processed.
        apfFilter.pretendPacketReceived(ra1.build());
        program = ipClientCallback.assertProgramUpdateAndGet();
        apfFilter.pretendPacketReceived(ra2.build());
        program = ipClientCallback.assertProgramUpdateAndGet();
        apfFilter.pretendPacketReceived(raInvalid.build());
        ipClientCallback.assertNoProgramUpdate();
        apfFilter.pretendPacketReceived(raZeroRouterLifetime.build());
        verifyUpdateProgramForZeroLifetimeRa(ipClientCallback, isLegacy);
        apfFilter.pretendPacketReceived(raZeroPioValidLifetime.build());
        verifyUpdateProgramForZeroLifetimeRa(ipClientCallback, isLegacy);
        apfFilter.pretendPacketReceived(raZeroRdnssLifetime.build());
        verifyUpdateProgramForZeroLifetimeRa(ipClientCallback, isLegacy);
        apfFilter.pretendPacketReceived(raZeroRioRouteLifetime.build());
        verifyUpdateProgramForZeroLifetimeRa(ipClientCallback, isLegacy);

        // Write metrics data to statsd pipeline when shutdown.
        doReturn(startTimeMs + durationTimeMs).when(mClock).elapsedRealtime();
        apfFilter.shutdown();

        // Verify each metric fields in IpClientRaInfoMetrics.
        if (isLegacy) {
            // LegacyApfFilter will purge expired RAs before adding new RA. Every time a new zero
            // lifetime RA is received, zero lifetime RAs except the newly added one will be
            // cleared, so the number of distinct RAs is 3 (ra1, ra2 and the newly added RA).
            verify(mIpClientRaInfoMetrics).setMaxNumberOfDistinctRas(3);
        } else {
            verify(mIpClientRaInfoMetrics).setMaxNumberOfDistinctRas(6);
        }
        verify(mIpClientRaInfoMetrics).setNumberOfZeroLifetimeRas(4);
        verify(mIpClientRaInfoMetrics).setNumberOfParsingErrorRas(1);
        verify(mIpClientRaInfoMetrics).setLowestRouterLifetimeSeconds(routerLifetime);
        verify(mIpClientRaInfoMetrics).setLowestPioValidLifetimeSeconds(prefixValidLifetime);
        verify(mIpClientRaInfoMetrics).setLowestRioRouteLifetimeSeconds(routeLifetime);
        verify(mIpClientRaInfoMetrics).setLowestRdnssLifetimeSeconds(rdnssLifetime);
        verify(mIpClientRaInfoMetrics).statsWrite();
    }

    @Test
    public void testIpClientRaInfoMetrics() throws Exception {
        verifyIpClientRaInfoMetrics(false /* isLegacy */);
    }

    @Test
    public void testIpClientRaInfoMetrics_LegacyApfFilter() throws Exception {
        verifyIpClientRaInfoMetrics(true /* isLegacy */);
    }

    private void verifyNoMetricsWrittenForShortDuration(boolean isLegacy) throws Exception {
        final MockIpClientCallback ipClientCallback = new MockIpClientCallback();
        final ApfConfiguration config = getDefaultConfig();
        final long startTimeMs = 12345;
        final long durationTimeMs = config.minMetricsSessionDurationMs;

        // Verify no metrics data written to statsd for duration less than durationTimeMs.
        doReturn(startTimeMs).when(mClock).elapsedRealtime();
        final TestAndroidPacketFilter apfFilter =
                makeTestApfFilter(config, ipClientCallback, isLegacy);
        doReturn(startTimeMs + durationTimeMs - 1).when(mClock).elapsedRealtime();
        apfFilter.shutdown();
        verify(mApfSessionInfoMetrics, never()).statsWrite();
        verify(mIpClientRaInfoMetrics, never()).statsWrite();

        // Verify metrics data written to statsd for duration greater than or equal to
        // durationTimeMs.
        ApfFilter.Clock clock = mock(ApfFilter.Clock.class);
        doReturn(startTimeMs).when(clock).elapsedRealtime();
        final TestAndroidPacketFilter apfFilter2 = new TestApfFilter(mContext, config,
                ipClientCallback, mNetworkQuirkMetrics, mDependencies, clock);
        doReturn(startTimeMs + durationTimeMs).when(clock).elapsedRealtime();
        apfFilter2.shutdown();
        verify(mApfSessionInfoMetrics).statsWrite();
        verify(mIpClientRaInfoMetrics).statsWrite();
    }

    @Test
    public void testNoMetricsWrittenForShortDuration() throws Exception {
        verifyNoMetricsWrittenForShortDuration(false /* isLegacy */);
    }

    @Test
    public void testNoMetricsWrittenForShortDuration_LegacyApfFilter() throws Exception {
        verifyNoMetricsWrittenForShortDuration(true /* isLegacy */);
    }

    @Test
    public void testFullApfV4ProgramGenerationIPV6() throws IllegalInstructionException {
        ApfV4Generator gen = new ApfV4Generator(APF_VERSION_4);
        gen.addLoadImmediate(R1, -4);
        gen.addLoadData(R0, 0);
        gen.addAdd(1);
        gen.addStoreData(R0, 0);
        gen.addLoad16(R0, 12);
        gen.addLoadImmediate(R1, -108);
        gen.addJumpIfR0LessThan(0x600, "LABEL_504");
        gen.addLoadImmediate(R1, -112);
        gen.addJumpIfR0Equals(0x88a2, "LABEL_504");
        gen.addJumpIfR0Equals(0x88a4, "LABEL_504");
        gen.addJumpIfR0Equals(0x88b8, "LABEL_504");
        gen.addJumpIfR0Equals(0x88cd, "LABEL_504");
        gen.addJumpIfR0Equals(0x88e1, "LABEL_504");
        gen.addJumpIfR0Equals(0x88e3, "LABEL_504");
        gen.addJumpIfR0NotEquals(0x806, "LABEL_116");
        gen.addLoadImmediate(R0, 14);
        gen.addLoadImmediate(R1, -36);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("000108000604"), "LABEL_498");
        gen.addLoad16(R0, 20);
        gen.addJumpIfR0Equals(0x1, "LABEL_102");
        gen.addLoadImmediate(R1, -40);
        gen.addJumpIfR0NotEquals(0x2, "LABEL_498");
        gen.addLoad32(R0, 28);
        gen.addLoadImmediate(R1, -116);
        gen.addJumpIfR0Equals(0x0, "LABEL_504");
        gen.addLoadImmediate(R0, 0);
        gen.addLoadImmediate(R1, -44);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("ffffffffffff"), "LABEL_498");

        gen.defineLabel("LABEL_102");
        gen.addLoad32(R0, 38);
        gen.addLoadImmediate(R1, -64);
        gen.addJumpIfR0Equals(0x0, "LABEL_504");
        gen.addLoadImmediate(R1, -8);
        gen.addJump("LABEL_498");

        gen.defineLabel("LABEL_116");
        gen.addLoad16(R0, 12);
        gen.addJumpIfR0NotEquals(0x800, "LABEL_207");
        gen.addLoad8(R0, 23);
        gen.addJumpIfR0NotEquals(0x11, "LABEL_159");
        gen.addLoad16(R0, 20);
        gen.addJumpIfR0AnyBitsSet(0x1fff, "LABEL_159");
        gen.addLoadFromMemory(R1, 13);
        gen.addLoad16Indexed(R0, 16);
        gen.addJumpIfR0NotEquals(0x44, "LABEL_159");
        gen.addLoadImmediate(R0, 50);
        gen.addAddR1();
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("e212507c6345"), "LABEL_159");
        gen.addLoadImmediate(R1, -12);
        gen.addJump("LABEL_498");

        gen.defineLabel("LABEL_159");
        gen.addLoad8(R0, 30);
        gen.addAnd(240);
        gen.addLoadImmediate(R1, -84);
        gen.addJumpIfR0Equals(0xe0, "LABEL_504");
        gen.addLoadImmediate(R1, -76);
        gen.addLoad32(R0, 30);
        gen.addJumpIfR0Equals(0xffffffff, "LABEL_504");
        gen.addLoadImmediate(R1, -24);
        gen.addLoadImmediate(R0, 0);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("ffffffffffff"), "LABEL_498");
        gen.addLoadImmediate(R1, -72);
        gen.addJump("LABEL_504");
        gen.addLoadImmediate(R1, -16);
        gen.addJump("LABEL_498");

        gen.defineLabel("LABEL_207");
        gen.addJumpIfR0Equals(0x86dd, "LABEL_231");
        gen.addLoadImmediate(R0, 0);
        gen.addLoadImmediate(R1, -48);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("ffffffffffff"), "LABEL_498");
        gen.addLoadImmediate(R1, -56);
        gen.addJump("LABEL_504");

        gen.defineLabel("LABEL_231");
        gen.addLoad8(R0, 20);
        gen.addJumpIfR0Equals(0x3a, "LABEL_249");
        gen.addLoadImmediate(R1, -104);
        gen.addLoad8(R0, 38);
        gen.addJumpIfR0Equals(0xff, "LABEL_504");
        gen.addLoadImmediate(R1, -32);
        gen.addJump("LABEL_498");

        gen.defineLabel("LABEL_249");
        gen.addLoad8(R0, 54);
        gen.addLoadImmediate(R1, -88);
        gen.addJumpIfR0Equals(0x85, "LABEL_504");
        gen.addJumpIfR0NotEquals(0x88, "LABEL_283");
        gen.addLoadImmediate(R0, 38);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("ff0200000000000000000000000000"), "LABEL_283");
        gen.addLoadImmediate(R1, -92);
        gen.addJump("LABEL_504");

        gen.defineLabel("LABEL_283");
        gen.addLoadFromMemory(R0, 14);
        gen.addJumpIfR0NotEquals(0xa6, "LABEL_496");
        gen.addLoadFromMemory(R0, 15);
        gen.addJumpIfR0GreaterThan(0x254, "LABEL_496");
        gen.addLoadImmediate(R0, 0);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("e212507c6345648788fd6df086dd68"), "LABEL_496");
        gen.addLoadImmediate(R0, 18);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("00703afffe800000000000002a0079e10abc1539fe80000000000000e01250fffe7c63458600"), "LABEL_496");
        gen.addLoadImmediate(R0, 58);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("4000"), "LABEL_496");
        gen.addLoad16(R0, 60);
        gen.addJumpIfR0LessThan(0x254, "LABEL_496");
        gen.addLoadImmediate(R0, 62);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("0000000000000000"), "LABEL_496");
        gen.addLoadImmediate(R0, 78);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("19050000"), "LABEL_496");
        gen.addLoad32(R0, 82);
        gen.addJumpIfR0LessThan(0x254, "LABEL_496");
        gen.addLoadImmediate(R0, 86);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("2001486048600000000000000000646420014860486000000000000000000064"), "LABEL_496");
        gen.addLoadImmediate(R0, 118);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("030440c0"), "LABEL_496");
        gen.addLoad32(R0, 122);
        gen.addJumpIfR0LessThan(0x254, "LABEL_496");
        gen.addLoad32(R0, 126);
        gen.addJumpIfR0LessThan(0x254, "LABEL_496");
        gen.addLoadImmediate(R0, 130);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("00000000"), "LABEL_496");
        gen.addLoadImmediate(R0, 134);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("2a0079e10abc15390000000000000000"), "LABEL_496");
        gen.addLoadImmediate(R1, -60);
        gen.addJump("LABEL_504");

        gen.defineLabel("LABEL_496");
        gen.addLoadImmediate(R1, -28);

        gen.defineLabel("LABEL_498");
        gen.addLoadData(R0, 0);
        gen.addAdd(1);
        gen.addStoreData(R0, 0);
        gen.addJump(PASS_LABEL);

        gen.defineLabel("LABEL_504");
        gen.addLoadData(R0, 0);
        gen.addAdd(1);
        gen.addStoreData(R0, 0);
        gen.addJump(DROP_LABEL);

        byte[] program = gen.generate();
        final String programString = toHexString(program).toLowerCase();
        final String referenceProgramHexString = "6bfcb03a01b8120c6b949401e906006b907c01e288a27c01dd88a47c01d888b87c01d388cd7c01ce88e17c01c988e384004008066a0e6bdca401af000600010800060412147a1e016bd88401a300021a1c6b8c7c01a00000686bd4a4018c0006ffffffffffff1a266bc07c018900006bf874017e120c84005408000a17821f1112149c00181fffab0d2a108211446a3239a20506e212507c63456bf47401530a1e52f06bac7c014e00e06bb41a1e7e00000141ffffffff6be868a4012d0006ffffffffffff6bb874012e6bf07401237c001386dd686bd0a401100006ffffffffffff6bc87401110a147a0d3a6b980a267c010300ff6be072f90a366ba87af8858218886a26a2040fff02000000000000000000000000006ba472ddaa0e82d0a6aa0f8c00c9025468a2b60fe212507c6345648788fd6df086dd686a12a28b2600703afffe800000000000002a0079e10abc1539fe80000000000000e01250fffe7c634586006a3aa284024000123c94007d02546a3ea2700800000000000000006a4ea26704190500001a5294006002546a56a23b2020014860486000000000000000006464200148604860000000000000000000646a76a23204030440c01a7a94002b02541a7e94002402546c0082a21a04000000006c0086a204102a0079e10abc153900000000000000006bc472086be4b03a01b87206b03a01b87201";
        assertEquals(referenceProgramHexString, programString);
    }

    @Test
    public void testFullApfV4ProgramGenerationIPV4() throws IllegalInstructionException {
        ApfV4Generator gen = new ApfV4Generator(APF_VERSION_4);
        gen.addLoadImmediate(R1, -4);
        gen.addLoadData(R0, 0);
        gen.addAdd(1);
        gen.addStoreData(R0, 0);
        gen.addLoad16(R0, 12);
        gen.addLoadImmediate(R1, -108);
        gen.addJumpIfR0LessThan(0x600, "LABEL_283");
        gen.addLoadImmediate(R1, -112);
        gen.addJumpIfR0Equals(0x88a2, "LABEL_283");
        gen.addJumpIfR0Equals(0x88a4, "LABEL_283");
        gen.addJumpIfR0Equals(0x88b8, "LABEL_283");
        gen.addJumpIfR0Equals(0x88cd, "LABEL_283");
        gen.addJumpIfR0Equals(0x88e1, "LABEL_283");
        gen.addJumpIfR0Equals(0x88e3, "LABEL_283");
        gen.addJumpIfR0NotEquals(0x806, "LABEL_109");
        gen.addLoadImmediate(R0, 14);
        gen.addLoadImmediate(R1, -36);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("000108000604"), "LABEL_277");
        gen.addLoad16(R0, 20);
        gen.addJumpIfR0Equals(0x1, "LABEL_94");
        gen.addLoadImmediate(R1, -40);
        gen.addJumpIfR0NotEquals(0x2, "LABEL_277");
        gen.addLoad32(R0, 28);
        gen.addLoadImmediate(R1, -116);
        gen.addJumpIfR0Equals(0x0, "LABEL_283");
        gen.addLoadImmediate(R0, 0);
        gen.addLoadImmediate(R1, -44);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("ffffffffffff"), "LABEL_277");

        gen.defineLabel("LABEL_94");
        gen.addLoadImmediate(R0, 38);
        gen.addLoadImmediate(R1, -68);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("c0a801b3"), "LABEL_283");
        gen.addLoadImmediate(R1, -8);
        gen.addJump("LABEL_277");

        gen.defineLabel("LABEL_109");
        gen.addLoad16(R0, 12);
        gen.addJumpIfR0NotEquals(0x800, "LABEL_204");
        gen.addLoad8(R0, 23);
        gen.addJumpIfR0NotEquals(0x11, "LABEL_151");
        gen.addLoad16(R0, 20);
        gen.addJumpIfR0AnyBitsSet(0x1fff, "LABEL_151");
        gen.addLoadFromMemory(R1, 13);
        gen.addLoad16Indexed(R0, 16);
        gen.addJumpIfR0NotEquals(0x44, "LABEL_151");
        gen.addLoadImmediate(R0, 50);
        gen.addAddR1();
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("f683d58f832b"), "LABEL_151");
        gen.addLoadImmediate(R1, -12);
        gen.addJump("LABEL_277");

        gen.defineLabel("LABEL_151");
        gen.addLoad8(R0, 30);
        gen.addAnd(240);
        gen.addLoadImmediate(R1, -84);
        gen.addJumpIfR0Equals(0xe0, "LABEL_283");
        gen.addLoadImmediate(R1, -76);
        gen.addLoad32(R0, 30);
        gen.addJumpIfR0Equals(0xffffffff, "LABEL_283");
        gen.addLoadImmediate(R1, -80);
        gen.addJumpIfR0Equals(0xc0a801ff, "LABEL_283");
        gen.addLoadImmediate(R1, -24);
        gen.addLoadImmediate(R0, 0);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("ffffffffffff"), "LABEL_277");
        gen.addLoadImmediate(R1, -72);
        gen.addJump("LABEL_283");
        gen.addLoadImmediate(R1, -16);
        gen.addJump("LABEL_277");

        gen.defineLabel("LABEL_204");
        gen.addJumpIfR0Equals(0x86dd, "LABEL_225");
        gen.addLoadImmediate(R0, 0);
        gen.addLoadImmediate(R1, -48);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("ffffffffffff"), "LABEL_277");
        gen.addLoadImmediate(R1, -56);
        gen.addJump("LABEL_283");

        gen.defineLabel("LABEL_225");
        gen.addLoad8(R0, 20);
        gen.addJumpIfR0Equals(0x3a, "LABEL_241");
        gen.addLoadImmediate(R1, -104);
        gen.addLoad8(R0, 38);
        gen.addJumpIfR0Equals(0xff, "LABEL_283");
        gen.addLoadImmediate(R1, -32);
        gen.addJump("LABEL_277");

        gen.defineLabel("LABEL_241");
        gen.addLoad8(R0, 54);
        gen.addLoadImmediate(R1, -88);
        gen.addJumpIfR0Equals(0x85, "LABEL_283");
        gen.addJumpIfR0NotEquals(0x88, "LABEL_275");
        gen.addLoadImmediate(R0, 38);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("ff0200000000000000000000000000"), "LABEL_275");
        gen.addLoadImmediate(R1, -92);
        gen.addJump("LABEL_283");

        gen.defineLabel("LABEL_275");
        gen.addLoadImmediate(R1, -28);

        gen.defineLabel("LABEL_277");
        gen.addLoadData(R0, 0);
        gen.addAdd(1);
        gen.addStoreData(R0, 0);
        gen.addJump(PASS_LABEL);

        gen.defineLabel("LABEL_283");
        gen.addLoadData(R0, 0);
        gen.addAdd(1);
        gen.addStoreData(R0, 0);
        gen.addJump(DROP_LABEL);

        byte[] program = gen.generate();
        final String programString = toHexString(program).toLowerCase();
        final String referenceProgramHexString = "6bfcb03a01b8120c6b9494010c06006b907c010588a27c010088a47c00fb88b87c00f688cd7c00f188e17c00ec88e384003908066a0e6bdca2d40600010800060412147a18016bd882ca021a1c6b8c7ac900686bd4a2b706ffffffffffff6a266bbca2b204c0a801b36bf872a8120c84005808000a17821e1112149c00171fffab0d2a108210446a3239a20406f683d58f832b6bf4727e0a1e52f06bac7a7be06bb41a1e7e0000006effffffff6bb07e00000063c0a801ff6be868a25106ffffffffffff6bb872536bf072497c001086dd686bd0a23806ffffffffffff6bc8723a0a147a0b3a6b980a267a2eff6be072240a366ba87a23858218886a26a2040fff02000000000000000000000000006ba472086be4b03a01b87206b03a01b87201";
        assertEquals(referenceProgramHexString, programString);
    }

    @Test
    public void testFullApfV4ProgramGenerationNatTKeepAliveV4() throws IllegalInstructionException {
        ApfV4Generator gen = new ApfV4Generator(APF_VERSION_4);
        gen.addLoadImmediate(R1, -4);
        gen.addLoadData(R0, 0);
        gen.addAdd(1);
        gen.addStoreData(R0, 0);
        gen.addLoad16(R0, 12);
        gen.addLoadImmediate(R1, -108);
        gen.addJumpIfR0LessThan(0x600, "LABEL_345");
        gen.addLoadImmediate(R1, -112);
        gen.addJumpIfR0Equals(0x88a2, "LABEL_345");
        gen.addJumpIfR0Equals(0x88a4, "LABEL_345");
        gen.addJumpIfR0Equals(0x88b8, "LABEL_345");
        gen.addJumpIfR0Equals(0x88cd, "LABEL_345");
        gen.addJumpIfR0Equals(0x88e1, "LABEL_345");
        gen.addJumpIfR0Equals(0x88e3, "LABEL_345");
        gen.addJumpIfR0NotEquals(0x806, "LABEL_115");
        gen.addLoadImmediate(R0, 14);
        gen.addLoadImmediate(R1, -36);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("000108000604"), "LABEL_339");
        gen.addLoad16(R0, 20);
        gen.addJumpIfR0Equals(0x1, "LABEL_100");
        gen.addLoadImmediate(R1, -40);
        gen.addJumpIfR0NotEquals(0x2, "LABEL_339");
        gen.addLoad32(R0, 28);
        gen.addLoadImmediate(R1, -116);
        gen.addJumpIfR0Equals(0x0, "LABEL_345");
        gen.addLoadImmediate(R0, 0);
        gen.addLoadImmediate(R1, -44);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("ffffffffffff"), "LABEL_339");

        gen.defineLabel("LABEL_100");
        gen.addLoadImmediate(R0, 38);
        gen.addLoadImmediate(R1, -68);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("c0a801be"), "LABEL_345");
        gen.addLoadImmediate(R1, -8);
        gen.addJump("LABEL_339");

        gen.defineLabel("LABEL_115");
        gen.addLoad16(R0, 12);
        gen.addJumpIfR0NotEquals(0x800, "LABEL_263");
        gen.addLoad8(R0, 23);
        gen.addJumpIfR0NotEquals(0x11, "LABEL_157");
        gen.addLoad16(R0, 20);
        gen.addJumpIfR0AnyBitsSet(0x1fff, "LABEL_157");
        gen.addLoadFromMemory(R1, 13);
        gen.addLoad16Indexed(R0, 16);
        gen.addJumpIfR0NotEquals(0x44, "LABEL_157");
        gen.addLoadImmediate(R0, 50);
        gen.addAddR1();
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("ea42226789c0"), "LABEL_157");
        gen.addLoadImmediate(R1, -12);
        gen.addJump("LABEL_339");

        gen.defineLabel("LABEL_157");
        gen.addLoad8(R0, 30);
        gen.addAnd(240);
        gen.addLoadImmediate(R1, -84);
        gen.addJumpIfR0Equals(0xe0, "LABEL_345");
        gen.addLoadImmediate(R1, -76);
        gen.addLoad32(R0, 30);
        gen.addJumpIfR0Equals(0xffffffff, "LABEL_345");
        gen.addLoadImmediate(R1, -80);
        gen.addJumpIfR0Equals(0xc0a801ff, "LABEL_345");
        gen.addLoad8(R0, 23);
        gen.addJumpIfR0NotEquals(0x11, "LABEL_243");
        gen.addLoadImmediate(R0, 26);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("6b7a1f1fc0a801be"), "LABEL_243");
        gen.addLoadFromMemory(R0, 13);
        gen.addAdd(8);
        gen.addSwap();
        gen.addLoad16(R0, 16);
        gen.addNeg(R1);
        gen.addAddR1();
        gen.addJumpIfR0NotEquals(0x1, "LABEL_243");
        gen.addLoadFromMemory(R0, 13);
        gen.addAdd(14);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("1194ceca"), "LABEL_243");
        gen.addAdd(8);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("ff"), "LABEL_243");
        gen.addLoadImmediate(R1, -128);
        gen.addJump("LABEL_345");

        gen.defineLabel("LABEL_243");
        gen.addLoadImmediate(R1, -24);
        gen.addLoadImmediate(R0, 0);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("ffffffffffff"), "LABEL_339");
        gen.addLoadImmediate(R1, -72);
        gen.addJump("LABEL_345");
        gen.addLoadImmediate(R1, -16);
        gen.addJump("LABEL_339");

        gen.defineLabel("LABEL_263");
        gen.addJumpIfR0Equals(0x86dd, "LABEL_284");
        gen.addLoadImmediate(R0, 0);
        gen.addLoadImmediate(R1, -48);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("ffffffffffff"), "LABEL_339");
        gen.addLoadImmediate(R1, -56);
        gen.addJump("LABEL_345");

        gen.defineLabel("LABEL_284");
        gen.addLoad8(R0, 20);
        gen.addJumpIfR0Equals(0x0, "LABEL_339");
        gen.addJumpIfR0Equals(0x3a, "LABEL_303");
        gen.addLoadImmediate(R1, -104);
        gen.addLoad8(R0, 38);
        gen.addJumpIfR0Equals(0xff, "LABEL_345");
        gen.addLoadImmediate(R1, -32);
        gen.addJump("LABEL_339");

        gen.defineLabel("LABEL_303");
        gen.addLoad8(R0, 54);
        gen.addLoadImmediate(R1, -88);
        gen.addJumpIfR0Equals(0x85, "LABEL_345");
        gen.addJumpIfR0NotEquals(0x88, "LABEL_337");
        gen.addLoadImmediate(R0, 38);
        gen.addJumpIfBytesAtR0NotEqual(hexStringToByteArray("ff0200000000000000000000000000"), "LABEL_337");
        gen.addLoadImmediate(R1, -92);
        gen.addJump("LABEL_345");

        gen.defineLabel("LABEL_337");
        gen.addLoadImmediate(R1, -28);

        gen.defineLabel("LABEL_339");
        gen.addLoadData(R0, 0);
        gen.addAdd(1);
        gen.addStoreData(R0, 0);
        gen.addJump(PASS_LABEL);

        gen.defineLabel("LABEL_345");
        gen.addLoadData(R0, 0);
        gen.addAdd(1);
        gen.addStoreData(R0, 0);
        gen.addJump(DROP_LABEL);

        byte[] program = gen.generate();
        final String programString = toHexString(program).toLowerCase();
        final String referenceProgramHexString = "6bfcb03a01b8120c6b9494014a06006b907c014388a27c013e88a47c013988b87c013488cd7c012f88e17c012a88e384003f08066a0e6bdca40110000600010800060412147a1c016bd884010400021a1c6b8c7c01010000686bd4a2ef06ffffffffffff6a266bbca2ea04c0a801be6bf872e0120c84008d08000a17821e1112149c00171fffab0d2a108210446a3239a20406ea42226789c06bf472b60a1e52f06bac7ab3e06bb41a1e7e000000a6ffffffff6bb07e0000009bc0a801ff0a178230116a1aa223086b7a1f1fc0a801beaa0d3a08aa221210ab2139821501aa0d3a0ea20a041194ceca3a08a20401ff6b8072666be868a25406ffffffffffff6bb872566bf0724c7c001086dd686bd0a23b06ffffffffffff6bc8723d0a147a32007a0b3a6b980a267a2eff6be072240a366ba87a23858218886a26a2040fff02000000000000000000000000006ba472086be4b03a01b87206b03a01b87201";
        assertEquals(referenceProgramHexString, programString);
    }
}