summaryrefslogtreecommitdiff
path: root/sys/net/pf.c
blob: acf1137541261f554844e849cf9f5c0acce782e2 (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
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
/*	$OpenBSD: pf.c,v 1.150 2001/09/15 03:54:40 frantzen Exp $ */

/*
 * Copyright (c) 2001 Daniel Hartmeier
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *    - Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *    - Redistributions in binary form must reproduce the above
 *      copyright notice, this list of conditions and the following
 *      disclaimer in the documentation and/or other materials provided
 *      with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/mbuf.h>
#include <sys/filio.h>
#include <sys/fcntl.h>
#include <sys/socket.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/time.h>
#include <sys/pool.h>

#include <net/if.h>
#include <net/if_types.h>
#include <net/bpf.h>
#include <net/route.h>
#include <net/if_pflog.h>

#include <netinet/in.h>
#include <netinet/in_var.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_var.h>
#include <netinet/tcp.h>
#include <netinet/tcp_fsm.h>
#include <netinet/tcp_seq.h>
#include <netinet/udp.h>
#include <netinet/ip_icmp.h>

#include <dev/rndvar.h>
#include <net/pfvar.h>

#include "bpfilter.h"
#include "pflog.h"

#ifdef INET6
#include <netinet/ip6.h>
#include <netinet/in_pcb.h>
#include <netinet/icmp6.h>
#endif /* INET6 */


#define DPFPRINTF(n, x)	if (pf_status.debug >= (n)) printf x

/*
 * Tree data structure
 */

struct pf_tree_node {
	struct pf_tree_key	 key;
	struct pf_state		*state;
	struct pf_tree_node	*parent;
	struct pf_tree_node	*left;
	struct pf_tree_node	*right;
	int			 balance;
};

struct pf_port_node {
	LIST_ENTRY(pf_port_node)	next;
	u_int16_t			port;
};
LIST_HEAD(pf_port_list, pf_port_node);

/* structure for ipsec and ipv6 option header template */
struct _opt6 {
	u_int8_t	opt6_nxt;	/* next header */
	u_int8_t	opt6_hlen;	/* header extension length */
	u_int16_t       _pad;
	u_int32_t       ah_spi;		/* security parameter index
					   for authentication header */
};

/*
 * Global variables
 */

TAILQ_HEAD(pf_natqueue, pf_nat)		pf_nats[2];
TAILQ_HEAD(pf_binatqueue, pf_binat)	pf_binats[2];
TAILQ_HEAD(pf_rdrqueue, pf_rdr)		pf_rdrs[2];
struct pf_rulequeue	 pf_rules[2];
struct pf_rulequeue	*pf_rules_active;
struct pf_rulequeue	*pf_rules_inactive;
struct pf_natqueue	*pf_nats_active;
struct pf_natqueue	*pf_nats_inactive;
struct pf_binatqueue	*pf_binats_active;
struct pf_binatqueue	*pf_binats_inactive;
struct pf_rdrqueue	*pf_rdrs_active;
struct pf_rdrqueue	*pf_rdrs_inactive;
struct pf_tree_node	*tree_lan_ext, *tree_ext_gwy;
struct timeval		 pftv;
struct pf_status	 pf_status;
struct ifnet		*status_ifp;

u_int32_t		 pf_last_purge;
u_int32_t		 ticket_rules_active;
u_int32_t		 ticket_rules_inactive;
u_int32_t		 ticket_nats_active;
u_int32_t		 ticket_nats_inactive;
u_int32_t		 ticket_binats_active;
u_int32_t		 ticket_binats_inactive;
u_int32_t		 ticket_rdrs_active;
u_int32_t		 ticket_rdrs_inactive;
struct pf_port_list	 pf_tcp_ports;
struct pf_port_list	 pf_udp_ports;

/* Timeouts */
int			 pftm_tcp_first_packet = 60;	/* First TCP packet */
int			 pftm_tcp_opening = 30;		/* No response yet */
int			 pftm_tcp_established = 24*60*60;  /* established  */
int			 pftm_tcp_closing = 5 * 60;	/* Got a FIN */
int			 pftm_tcp_fin_wait = 2 * 60;	/* Got both FINs */
int			 pftm_tcp_closed = 1 * 60;	/* Got a RST */

int			 pftm_udp_first_packet = 60;	/* First UDP packet */
int			 pftm_udp_single = 30;		/* Unidirectional */
int			 pftm_udp_multiple = 60;	/* Bidirectional */

int			 pftm_icmp_first_packet = 20;	/* First ICMP packet */
int			 pftm_icmp_error_reply = 10;	/* Got error response */

int			 pftm_frag = 30;		/* Fragment expire */

int			 pftm_interval = 10;		/* expire interval */

int			*pftm_timeouts[PFTM_MAX] = { &pftm_tcp_first_packet,
				&pftm_tcp_opening, &pftm_tcp_established,
				&pftm_tcp_closing, &pftm_tcp_fin_wait,
				&pftm_tcp_closed, &pftm_udp_first_packet,
				&pftm_udp_single, &pftm_udp_multiple,
				&pftm_icmp_first_packet, &pftm_icmp_error_reply,
				&pftm_frag, &pftm_interval };


struct pool		 pf_tree_pl, pf_rule_pl, pf_nat_pl, pf_sport_pl;
struct pool		 pf_rdr_pl, pf_state_pl, pf_binat_pl;

int			 pf_tree_key_compare(struct pf_tree_key *,
			    struct pf_tree_key *);
int			 pf_compare_addr(struct pf_addr *, struct pf_addr *,
			    u_int8_t);
void			 pf_addrcpy(struct pf_addr *, struct pf_addr *,
			    u_int8_t);
int			 pf_compare_rules(struct pf_rule *,
			    struct pf_rule *);
int			 pf_compare_nats(struct pf_nat *, struct pf_nat *);
int			 pf_compare_binats(struct pf_binat *, 
			    struct pf_binat *);
int			 pf_compare_rdrs(struct pf_rdr *, struct pf_rdr *);
void			 pf_tree_rotate_left(struct pf_tree_node **);
void			 pf_tree_rotate_right(struct pf_tree_node **);
struct pf_tree_node	*pf_tree_first(struct pf_tree_node *);
struct pf_tree_node	*pf_tree_next(struct pf_tree_node *);
struct pf_tree_node	*pf_tree_search(struct pf_tree_node *,
			    struct pf_tree_key *);
void			 pf_insert_state(struct pf_state *);
void			 pf_purge_expired_states(void);

void			 pf_print_host(struct pf_addr *, u_int16_t, u_int8_t);
void			 pf_print_state(struct pf_state *);
void			 pf_print_flags(u_int8_t);

void			 pfattach(int);
int			 pfopen(dev_t, int, int, struct proc *);
int			 pfclose(dev_t, int, int, struct proc *);
int			 pfioctl(dev_t, u_long, caddr_t, int, struct proc *);

u_int16_t		 pf_cksum_fixup(u_int16_t, u_int16_t, u_int16_t,
			    u_int8_t);
void			 pf_change_ap(struct pf_addr *, u_int16_t *,
			    u_int16_t *, u_int16_t *, struct pf_addr *,
			    u_int16_t, u_int8_t, int);
void			 pf_change_a(u_int32_t *, u_int16_t *, u_int32_t,
			    u_int8_t);
#ifdef INET6
void			 pf_change_a6(struct pf_addr *, u_int16_t *,
			    struct pf_addr *, u_int8_t);
#endif /* INET6 */
void			 pf_change_icmp(struct pf_addr *, u_int16_t *,
			    struct pf_addr *, struct pf_addr *, u_int16_t,
			    u_int16_t *, u_int16_t *, u_int16_t *,
			    u_int16_t *, u_int8_t, int);
void			 pf_send_reset(int, struct tcphdr *,
			    struct pf_pdesc *, int);
void			 pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t, int);
u_int16_t		 pf_map_port_range(struct pf_rdr *, u_int16_t);
struct pf_nat		*pf_get_nat(struct ifnet *, u_int8_t,
			    struct pf_addr *, struct pf_addr *, int);
struct pf_binat		*pf_get_binat(int, struct ifnet *, u_int8_t,
			    struct pf_addr *, struct pf_addr *, int);
struct pf_rdr		*pf_get_rdr(struct ifnet *, u_int8_t,
			    struct pf_addr *, struct pf_addr *, u_int16_t, int);
int			 pf_test_tcp(int, struct ifnet *, struct mbuf *, int,
			    int, void *, struct pf_pdesc *);
int			 pf_test_udp(int, struct ifnet *, struct mbuf *, int,
			    int, void *, struct pf_pdesc *);
int			 pf_test_icmp(int, struct ifnet *, struct mbuf *,
			    int, int, void *, struct pf_pdesc *);
int			 pf_test_other(int, struct ifnet *, struct mbuf *,
			    void *, struct pf_pdesc *);
int			 pf_test_state_tcp(struct pf_state **, int,
			    struct ifnet *, struct mbuf *, int, int,
			    void *, struct pf_pdesc *);
int			 pf_test_state_udp(struct pf_state **, int,
			    struct ifnet *, struct mbuf *, int, int,
			    void *, struct pf_pdesc *);
int			 pf_test_state_icmp(struct pf_state **, int,
			    struct ifnet *, struct mbuf *, int, int,
			    void *, struct pf_pdesc *);
void			*pf_pull_hdr(struct mbuf *, int, void *, int,
			    u_short *, u_short *, int);
void			 pf_calc_skip_steps(struct pf_rulequeue *);

int			 pf_get_sport(u_int8_t, u_int16_t, u_int16_t,
			    u_int16_t *);
void			 pf_put_sport(u_int8_t, u_int16_t);
int			 pf_add_sport(struct pf_port_list *, u_int16_t);
int			 pf_chk_sport(struct pf_port_list *, u_int16_t);
int			 pf_normalize_tcp(int, struct ifnet *, struct mbuf *,
			     int, int, void *, struct pf_pdesc *);


#if NPFLOG > 0
#define	PFLOG_PACKET(x,a,b,c,d,e) \
	do { \
		if (b == AF_INET) { \
			HTONS(((struct ip *)x)->ip_len); \
			HTONS(((struct ip *)x)->ip_off); \
			pflog_packet(a,b,c,d,e); \
			NTOHS(((struct ip *)x)->ip_len); \
			NTOHS(((struct ip *)x)->ip_off); \
		} else { \
			pflog_packet(a,b,c,d,e); \
		} \
	} while (0)
#else
#define	PFLOG_PACKET(x,a,b,c,d,e)	((void)0)
#endif

#define	STATE_TRANSLATE(s) \
	(s)->lan.addr.addr32[0] != (s)->gwy.addr.addr32[0] || \
	((s)->af == AF_INET6 && \
	((s)->lan.addr.addr32[1] != (s)->gwy.addr.addr32[1] || \
	(s)->lan.addr.addr32[2] != (s)->gwy.addr.addr32[2] || \
	(s)->lan.addr.addr32[3] != (s)->gwy.addr.addr32[3])) || \
	(s)->lan.port != (s)->gwy.port

int
pf_tree_key_compare(struct pf_tree_key *a, struct pf_tree_key *b)
{
	register int diff;

	/*
	 * could use memcmp(), but with the best manual order, we can
	 * minimize the number of average compares. what is faster?
	 */
	if ((diff = a->proto - b->proto) != 0)
		return (diff);
	if ((diff = a->af - b->af) != 0)
		return (diff);
	switch (a->af) {
#ifdef INET
	case AF_INET:
		if (a->addr[0].addr32[0] > b->addr[0].addr32[0])
			return 1;
		if (a->addr[0].addr32[0] < b->addr[0].addr32[0])
			return -1;
		if (a->addr[1].addr32[0] > b->addr[1].addr32[0])
			return 1;
		if (a->addr[1].addr32[0] < b->addr[1].addr32[0])
			return -1;
		break;
#endif /* INET */
#ifdef INET6
	case AF_INET6:
		if (a->addr[0].addr32[0] > b->addr[0].addr32[0])
			return 1;
		if (a->addr[0].addr32[0] < b->addr[0].addr32[0])
			return -1;
		if (a->addr[0].addr32[1] > b->addr[0].addr32[1])
			return 1;
		if (a->addr[0].addr32[1] < b->addr[0].addr32[1])
			return -1;
		if (a->addr[0].addr32[2] > b->addr[0].addr32[2])
			return 1;
		if (a->addr[0].addr32[2] < b->addr[0].addr32[2])
			return -1;
		if (a->addr[0].addr32[3] > b->addr[0].addr32[3])
			return 1;
		if (a->addr[0].addr32[3] < b->addr[0].addr32[3])
			return -1;
		if (a->addr[1].addr32[0] > b->addr[1].addr32[0])
			return 1;
		if (a->addr[1].addr32[0] < b->addr[1].addr32[0])
			return -1;
		if (a->addr[1].addr32[1] > b->addr[1].addr32[1])
			return 1;
		if (a->addr[1].addr32[1] < b->addr[1].addr32[1])
			return -1;
		if (a->addr[1].addr32[2] > b->addr[1].addr32[2])
			return 1;
		if (a->addr[1].addr32[2] < b->addr[1].addr32[2])
			return -1;
		if (a->addr[1].addr32[3] > b->addr[1].addr32[3])
			return 1;
		if (a->addr[1].addr32[3] < b->addr[1].addr32[3])
			return -1;
		break;
#endif /* INET6 */
	}
	
	if ((diff = a->port[0] - b->port[0]) != 0)
		return (diff);
	if ((diff = a->port[1] - b->port[1]) != 0)
		return (diff);

	return (0);
}

#ifdef INET6
void
pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, u_int8_t af)
{
	switch(af) {
#ifdef INET
	case AF_INET:
		dst->addr32[0] = src->addr32[0];
		break;
#endif /* INET */
	case AF_INET6:
		dst->addr32[0] = src->addr32[0];
		dst->addr32[1] = src->addr32[1];
		dst->addr32[2] = src->addr32[2];
		dst->addr32[3] = src->addr32[3];
		break;
	} 
}
#endif

int
pf_compare_rules(struct pf_rule *a, struct pf_rule *b)
{
	if (a->return_icmp != b->return_icmp ||
	    a->action != b->action ||
	    a->direction != b->direction ||
	    a->log != b->log ||
	    a->quick != b->quick ||
	    a->keep_state != b->keep_state ||
	    a->af != b->af ||
	    a->proto != b->proto ||
	    a->type != b->type ||
	    a->code != b->code ||
	    a->flags != b->flags ||
	    a->flagset != b->flagset ||
	    a->rule_flag != b->rule_flag ||
	    a->min_ttl != b->min_ttl)
		return (1);
	if (memcmp(&a->src, &b->src, sizeof(struct pf_rule_addr)))
		return (1);
	if (memcmp(&a->dst, &b->dst, sizeof(struct pf_rule_addr)))
		return (1);
	if (strcmp(a->ifname, b->ifname))
		return (1);
	return (0);
}

int
pf_compare_nats(struct pf_nat *a, struct pf_nat *b)
{
	if (a->proto != b->proto ||
	    a->af != b->af ||
	    a->snot != b->snot ||
	    a->dnot != b->dnot ||
	    a->ifnot != b->ifnot)
		return (1);
	if (PF_ANEQ(&a->saddr, &b->saddr, a->af))
		return (1);
	if (PF_ANEQ(&a->smask, &b->smask, a->af))
		return (1);
	if (PF_ANEQ(&a->daddr, &b->daddr, a->af))
		return (1);
	if (PF_ANEQ(&a->dmask, &b->dmask, a->af))
		return (1);
	if (PF_ANEQ(&a->raddr, &b->raddr, a->af))
		return (1);
	if (strcmp(a->ifname, b->ifname))
		return (1);
	return (0);
}

int
pf_compare_binats(struct pf_binat *a, struct pf_binat *b)
{
	if (PF_ANEQ(&a->saddr, &b->saddr, a->af))
		return (1);
	if (PF_ANEQ(&a->daddr, &b->daddr, a->af))
		return (1);
	if (PF_ANEQ(&a->dmask, &b->dmask, a->af))
		return (1);
	if (PF_ANEQ(&a->raddr, &b->raddr, a->af))
		return (1);
	if (a->proto != b->proto ||
	    a->dnot != b->dnot ||
	    a->af != b->af)
		return (1);
	if (strcmp(a->ifname, b->ifname))
		return (1);
	return (0);
}

int
pf_compare_rdrs(struct pf_rdr *a, struct pf_rdr *b)
{
	if (a->dport != b->dport ||
	    a->dport2 != b->dport2 ||
	    a->rport != b->rport ||
	    a->proto != b->proto ||
	    a->af != b->af ||
	    a->snot != b->snot ||
	    a->dnot != b->dnot ||
	    a->ifnot != b->ifnot ||
	    a->opts != b->opts)
		return (1);
	if (PF_ANEQ(&a->saddr, &b->saddr, a->af))
		return (1);
	if (PF_ANEQ(&a->smask, &b->smask, a->af))
		return (1);
	if (PF_ANEQ(&a->daddr, &b->daddr, a->af))
		return (1);
	if (PF_ANEQ(&a->dmask, &b->dmask, a->af))
		return (1);
	if (PF_ANEQ(&a->raddr, &b->raddr, a->af))
		return (1);
	if (strcmp(a->ifname, b->ifname))
		return (1);
	return (0);
}

void
pf_tree_rotate_left(struct pf_tree_node **n)
{
	struct pf_tree_node *q = *n, *p = (*n)->parent;

	(*n)->parent = (*n)->right;
	*n = (*n)->right;
	(*n)->parent = p;
	q->right = (*n)->left;
	if (q->right)
		q->right->parent = q;
	(*n)->left = q;
	q->balance--;
	if ((*n)->balance > 0)
		q->balance -= (*n)->balance;
	(*n)->balance--;
	if (q->balance < 0)
		(*n)->balance += q->balance;
}

void
pf_tree_rotate_right(struct pf_tree_node **n)
{
	struct pf_tree_node *q = *n, *p = (*n)->parent;

	(*n)->parent = (*n)->left;
	*n = (*n)->left;
	(*n)->parent = p;
	q->left = (*n)->right;
	if (q->left)
		q->left->parent = q;
	(*n)->right = q;
	q->balance++;
	if ((*n)->balance < 0)
		q->balance -= (*n)->balance;
	(*n)->balance++;
	if (q->balance > 0)
		(*n)->balance += q->balance;
}

int
pf_tree_insert(struct pf_tree_node **n, struct pf_tree_node *p,
    struct pf_tree_key *key, struct pf_state *state)
{
	int deltaH = 0;

	if (*n == NULL) {
		*n = pool_get(&pf_tree_pl, PR_NOWAIT);
		if (*n == NULL)
			return (0);
		bcopy(key, &(*n)->key, sizeof(struct pf_tree_key));
		(*n)->state = state;
		(*n)->balance = 0;
		(*n)->parent = p;
		(*n)->left = (*n)->right = NULL;
		deltaH = 1;
	} else if (pf_tree_key_compare(key, &(*n)->key) > 0) {
		if (pf_tree_insert(&(*n)->right, *n, key, state)) {
			(*n)->balance++;
			if ((*n)->balance == 1)
				deltaH = 1;
			else if ((*n)->balance == 2) {
				if ((*n)->right->balance == -1)
					pf_tree_rotate_right(&(*n)->right);
				pf_tree_rotate_left(n);
			}
		}
	} else {
		if (pf_tree_insert(&(*n)->left, *n, key, state)) {
			(*n)->balance--;
			if ((*n)->balance == -1)
				deltaH = 1;
			else if ((*n)->balance == -2) {
				if ((*n)->left->balance == 1)
					pf_tree_rotate_left(&(*n)->left);
				pf_tree_rotate_right(n);
			}
		}
	}
	return (deltaH);
}

int
pf_tree_remove(struct pf_tree_node **n, struct pf_tree_node *p,
    struct pf_tree_key *key)
{
	int deltaH = 0;
	int c;

	if (*n == NULL)
		return (0);
	c = pf_tree_key_compare(key, &(*n)->key);
	if (c < 0) {
		if (pf_tree_remove(&(*n)->left, *n, key)) {
			(*n)->balance++;
			if ((*n)->balance == 0)
				deltaH = 1;
			else if ((*n)->balance == 2) {
				if ((*n)->right->balance == -1)
					pf_tree_rotate_right(&(*n)->right);
				pf_tree_rotate_left(n);
				if ((*n)->balance == 0)
					deltaH = 1;
			}
		}
	} else if (c > 0) {
		if (pf_tree_remove(&(*n)->right, *n, key)) {
			(*n)->balance--;
			if ((*n)->balance == 0)
				deltaH = 1;
			else if ((*n)->balance == -2) {
				if ((*n)->left->balance == 1)
					pf_tree_rotate_left(&(*n)->left);
				pf_tree_rotate_right(n);
				if ((*n)->balance == 0)
					deltaH = 1;
			}
		}
	} else {
		if ((*n)->right == NULL) {
			struct pf_tree_node *n0 = *n;

			*n = (*n)->left;
			if (*n != NULL)
				(*n)->parent = p;
			pool_put(&pf_tree_pl, n0);
			deltaH = 1;
		} else if ((*n)->left == NULL) {
			struct pf_tree_node *n0 = *n;

			*n = (*n)->right;
			if (*n != NULL)
				(*n)->parent = p;
			pool_put(&pf_tree_pl, n0);
			deltaH = 1;
		} else {
			struct pf_tree_node **qq = &(*n)->left;

			while ((*qq)->right != NULL)
				qq = &(*qq)->right;
			bcopy(&(*qq)->key, &(*n)->key,
			    sizeof(struct pf_tree_key));
			(*n)->state = (*qq)->state;
			bcopy(key, &(*qq)->key, sizeof(struct pf_tree_key));
			if (pf_tree_remove(&(*n)->left, *n, key)) {
				(*n)->balance++;
				if ((*n)->balance == 0)
					deltaH = 1;
				else if ((*n)->balance == 2) {
					if ((*n)->right->balance == -1)
						pf_tree_rotate_right(
						    &(*n)->right);
					pf_tree_rotate_left(n);
					if ((*n)->balance == 0)
						deltaH = 1;
				}
			}
		}
	}
	return (deltaH);
}

int
pflog_packet(struct mbuf *m, int af, u_short dir, u_short reason,
    struct pf_rule *rm)
{
#if NBPFILTER > 0
	struct ifnet *ifn, *ifp = NULL;
	struct pfloghdr hdr;
	struct mbuf m1;

	if (m == NULL)
		return(-1);

	hdr.af = htonl(af);
	/* Set the right interface name */
	if (rm != NULL)
		ifp = rm->ifp;
	if (m->m_pkthdr.rcvif != NULL)
		ifp = m->m_pkthdr.rcvif;
	if (ifp != NULL)
		memcpy(hdr.ifname, ifp->if_xname, sizeof(hdr.ifname));
	else
		strcpy(hdr.ifname, "unkn");

	hdr.rnr = htons(rm->nr);
	hdr.reason = htons(reason);
	hdr.dir = htons(dir);
	hdr.action = htons(rm->action);

	m1.m_next = m;
	m1.m_len = PFLOG_HDRLEN;
	m1.m_data = (char *) &hdr;

	ifn = &(pflogif[0].sc_if);

	if (ifn->if_bpf)
		bpf_mtap(ifn->if_bpf, &m1);
#endif

	return (0);
}

struct pf_tree_node *
pf_tree_first(struct pf_tree_node *n)
{
	if (n == NULL)
		return (NULL);
	while (n->parent)
		n = n->parent;
	while (n->left)
		n = n->left;
	return (n);
}

struct pf_tree_node *
pf_tree_next(struct pf_tree_node *n)
{
	if (n == NULL)
		return (NULL);
	if (n->right) {
		n = n->right;
		while (n->left)
			n = n->left;
	} else {
		if (n->parent && (n == n->parent->left))
			n = n->parent;
		else {
			while (n->parent && (n == n->parent->right))
				n = n->parent;
			n = n->parent;
		}
	}
	return (n);
}

struct pf_tree_node *
pf_tree_search(struct pf_tree_node *n, struct pf_tree_key *key)
{
	int c;

	while (n && (c = pf_tree_key_compare(&n->key, key)))
		if (c > 0)
			n = n->left;
		else
			n = n->right;
	pf_status.fcounters[FCNT_STATE_SEARCH]++;
	return (n);
}

struct pf_state *
pf_find_state(struct pf_tree_node *n, struct pf_tree_key *key)
{
	n = pf_tree_search(n, key);
	if (n)
		return (n->state);
	else
		return (NULL);
}

void
pf_insert_state(struct pf_state *state)
{
	struct pf_tree_key key;
	struct pf_state *s;

	key.af = state->af;
	key.proto = state->proto;
	PF_ACPY(&key.addr[0], &state->lan.addr, state->af);
	key.port[0] = state->lan.port;
	PF_ACPY(&key.addr[1], &state->ext.addr, state->af);
	key.port[1] = state->ext.port;
	/* sanity checks can be removed later, should never occur */
	if ((s = pf_find_state(tree_lan_ext, &key)) != NULL) {
		if (pf_status.debug >= PF_DEBUG_URGENT) {
			printf("pf: ERROR! insert invalid\n");
			printf("    key already in tree_lan_ext\n");
			printf("    key: proto = %u, lan = ", state->proto);
			pf_print_host(&key.addr[0], key.port[0], key.af);
			printf(", ext = ");
			pf_print_host(&key.addr[1], key.port[1], key.af);
			printf("\n    state: ");
			pf_print_state(s);
			printf("\n");
		}
	} else {
		pf_tree_insert(&tree_lan_ext, NULL, &key, state);
		if (pf_find_state(tree_lan_ext, &key) != state)
			DPFPRINTF(PF_DEBUG_URGENT,
			    ("pf: ERROR! insert failed\n"));
	}

	key.af = state->af;
	key.proto = state->proto;
	PF_ACPY(&key.addr[0], &state->ext.addr, state->af);
	key.port[0] = state->ext.port;
	PF_ACPY(&key.addr[1], &state->gwy.addr, state->af);
	key.port[1] = state->gwy.port;
	if ((s = pf_find_state(tree_ext_gwy, &key)) != NULL) {
		if (pf_status.debug >= PF_DEBUG_URGENT) {
			printf("pf: ERROR! insert invalid\n");
			printf("    key already in tree_ext_gwy\n");
			printf("    key: proto = %u, ext = ", state->proto);
			pf_print_host(&key.addr[0], key.port[0], key.af);
			printf(", gwy = ");
			pf_print_host(&key.addr[1], key.port[1], key.af);
			printf("\n    state: ");
			pf_print_state(s);
			printf("\n");
		}
	} else {
		pf_tree_insert(&tree_ext_gwy, NULL, &key, state);
		if (pf_find_state(tree_ext_gwy, &key) != state)
			DPFPRINTF(PF_DEBUG_URGENT,
			    ("pf: ERROR! insert failed\n"));
	}
	pf_status.fcounters[FCNT_STATE_INSERT]++;
	pf_status.states++;
}

void
pf_purge_expired_states(void)
{
	struct pf_tree_node *cur, *next;
	struct pf_tree_key key;

	cur = pf_tree_first(tree_ext_gwy);
	while (cur != NULL) {
		if (cur->state->expire <= pftv.tv_sec) {
			key.af = cur->state->af;
			key.proto = cur->state->proto;
			PF_ACPY(&key.addr[0], &cur->state->lan.addr,
			    cur->state->af);
			key.port[0] = cur->state->lan.port;
			PF_ACPY(&key.addr[1], &cur->state->ext.addr,
			    cur->state->af);
			key.port[1] = cur->state->ext.port;
			/* remove state from second tree */
			if (pf_find_state(tree_lan_ext, &key) != cur->state)
				DPFPRINTF(PF_DEBUG_URGENT,
				    ("pf: ERROR: remove invalid!\n"));
			pf_tree_remove(&tree_lan_ext, NULL, &key);
			if (pf_find_state(tree_lan_ext, &key) != NULL)
				DPFPRINTF(PF_DEBUG_URGENT,
				    ("pf: ERROR: remove failed\n"));
			if (STATE_TRANSLATE(cur->state))
				pf_put_sport(cur->state->proto,
					htons(cur->state->gwy.port));
			/* free state */
			pool_put(&pf_state_pl, cur->state);
			/*
			 * remove state from tree being traversed, use next
			 * state's key to search after removal, since removal
			 * can invalidate pointers.
			 */
			next = pf_tree_next(cur);
			if (next) {
				key = next->key;
				pf_tree_remove(&tree_ext_gwy, NULL, &cur->key);
				cur = pf_tree_search(tree_ext_gwy, &key);
				if (cur == NULL)
					DPFPRINTF(PF_DEBUG_URGENT,
					    ("pf: ERROR: next not found\n"));
			} else {
				pf_tree_remove(&tree_ext_gwy, NULL, &cur->key);
				cur = NULL;
			}
			pf_status.fcounters[FCNT_STATE_REMOVALS]++;
			pf_status.states--;
		} else
			cur = pf_tree_next(cur);
	}
}

void
pf_print_host(struct pf_addr *addr, u_int16_t p, u_int8_t af)
{
	switch(af) {
#ifdef INET
	case AF_INET: {
		u_int32_t a = ntohl(addr->addr32[0]);
		p = ntohs(p);
		printf("%u.%u.%u.%u:%u", (a>>24)&255, (a>>16)&255,
		    (a>>8)&255, a&255, p);
		break;
	} 
#endif /* INET */
#ifdef INET6
	case AF_INET6: {
		u_int16_t b;
		u_int8_t i, curstart = 255, curend = 0,
		    maxstart = 0, maxend = 0;
		for (i = 0; i < 8; i++) {
			if (!addr->addr16[i]) {
				if (curstart == 255)
					curstart = i;
				else
					curend = i;
			} else {
				if (curstart) {
					if ((curend - curstart) >
					    (maxend - maxstart)) {
						maxstart = curstart;
						maxend = curend;
						curstart = 255;
					}
				}
			}
		}
		for (i = 0; i < 8; i++) {
			if (i >= maxstart && i <= maxend) {
				if (maxend != 7) {
					if (i == maxstart) 
						printf(":");
				} else {
					if (i == maxend)
						printf(":");
				}
			} else {
				b = ntohs(addr->addr16[i]);
				printf("%x", b);
				if (i < 7)
					printf(":");
			}
		}
		p = ntohs(p);
		printf("[%u]", p);
		break;
	}
#endif /* INET6 */
	}
}

void
pf_print_state(struct pf_state *s)
{
	switch (s->proto) {
	case IPPROTO_TCP:
		printf("TCP ");
		break;
	case IPPROTO_UDP:
		printf("UDP ");
		break;
	case IPPROTO_ICMP:
		printf("ICMP ");
		break;
	default:
		printf("%u ", s->proto);
		break;
	}
	pf_print_host(&s->lan.addr, s->lan.port, s->af);
	printf(" ");
	pf_print_host(&s->gwy.addr, s->gwy.port, s->af);
	printf(" ");
	pf_print_host(&s->ext.addr, s->ext.port, s->af);
	printf(" [lo=%lu high=%lu win=%u modulator=%u]", s->src.seqlo,
	    s->src.seqhi, s->src.max_win, s->src.seqdiff);
	printf(" [lo=%lu high=%lu win=%u modulator=%u]", s->dst.seqlo,
	    s->dst.seqhi, s->dst.max_win, s->dst.seqdiff);
	printf(" %u:%u", s->src.state, s->dst.state);
}

void
pf_print_flags(u_int8_t f)
{
	if (f)
		printf(" ");
	if (f & TH_FIN)
		printf("F");
	if (f & TH_SYN)
		printf("S");
	if (f & TH_RST)
		printf("R");
	if (f & TH_PUSH)
		printf("P");
	if (f & TH_ACK)
		printf("A");
	if (f & TH_URG)
		printf("U");
}

void
pfattach(int num)
{
	/* XXX - no M_* tags, but they are not used anyway */
	pool_init(&pf_tree_pl, sizeof(struct pf_tree_node), 0, 0, 0, "pftrpl",
	    0, NULL, NULL, 0);
	pool_init(&pf_rule_pl, sizeof(struct pf_rule), 0, 0, 0, "pfrulepl",
	    0, NULL, NULL, 0);
	pool_init(&pf_nat_pl, sizeof(struct pf_nat), 0, 0, 0, "pfnatpl",
	    0, NULL, NULL, 0);
	pool_init(&pf_binat_pl, sizeof(struct pf_binat), 0, 0, 0, "pfbinatpl",
	    0, NULL, NULL, 0);
	pool_init(&pf_rdr_pl, sizeof(struct pf_rdr), 0, 0, 0, "pfrdrpl",
	    0, NULL, NULL, 0);
	pool_init(&pf_state_pl, sizeof(struct pf_state), 0, 0, 0, "pfstatepl",
	    0, NULL, NULL, 0);
	pool_init(&pf_sport_pl, sizeof(struct pf_port_node), 0, 0, 0, "pfsport",
	    0, NULL, NULL, 0);

	TAILQ_INIT(&pf_rules[0]);
	TAILQ_INIT(&pf_rules[1]);
	TAILQ_INIT(&pf_nats[0]);
	TAILQ_INIT(&pf_nats[1]);
	TAILQ_INIT(&pf_binats[0]);
	TAILQ_INIT(&pf_binats[1]);
	TAILQ_INIT(&pf_rdrs[0]);
	TAILQ_INIT(&pf_rdrs[1]);
	pf_rules_active = &pf_rules[0];
	pf_rules_inactive = &pf_rules[1];
	pf_nats_active = &pf_nats[0];
	pf_nats_inactive = &pf_nats[1];
	pf_binats_active = &pf_binats[0];
	pf_binats_inactive = &pf_binats[1];
	pf_rdrs_active = &pf_rdrs[0];
	pf_rdrs_inactive = &pf_rdrs[1];

	LIST_INIT(&pf_tcp_ports);
	LIST_INIT(&pf_udp_ports);

	pf_normalize_init();
}

int
pfopen(dev_t dev, int flags, int fmt, struct proc *p)
{
	if (minor(dev) >= 1)
		return (ENXIO);
	return (0);
}

int
pfclose(dev_t dev, int flags, int fmt, struct proc *p)
{
	if (minor(dev) >= 1)
		return (ENXIO);
	return (0);
}

int
pfioctl(dev_t dev, u_long cmd, caddr_t addr, int flags, struct proc *p)
{
	int error = 0;
	int s;

	if (!(flags & FWRITE))
		return (EACCES);

	if (securelevel > 1)
		switch (cmd) {
		case DIOCSTART:
		case DIOCSTOP:
		case DIOCBEGINRULES:
		case DIOCADDRULE:
		case DIOCCOMMITRULES:
		case DIOCBEGINNATS:
		case DIOCADDNAT:
		case DIOCCOMMITNATS:
		case DIOCBEGINBINATS:
		case DIOCADDBINAT:
		case DIOCCOMMITBINATS:
		case DIOCBEGINRDRS:
		case DIOCADDRDR:
		case DIOCCOMMITRDRS:
		case DIOCCLRSTATES:
		case DIOCCHANGERULE:
		case DIOCCHANGENAT:
		case DIOCCHANGERDR:
		case DIOCSETTIMEOUT:
			return EPERM;
		}

	switch (cmd) {

	case DIOCSTART:
		if (pf_status.running)
			error = EEXIST;
		else {
			u_int32_t states = pf_status.states;
			bzero(&pf_status, sizeof(struct pf_status));
			pf_status.running = 1;
			pf_status.states = states;
			microtime(&pftv);
			pf_status.since = pftv.tv_sec;
			DPFPRINTF(PF_DEBUG_MISC, ("pf: started\n"));
		}
		break;

	case DIOCSTOP:
		if (!pf_status.running)
			error = ENOENT;
		else {
			pf_status.running = 0;
			DPFPRINTF(PF_DEBUG_MISC, ("pf: stopped\n"));
		}
		break;

	case DIOCBEGINRULES: {
		u_int32_t *ticket = (u_int32_t *)addr;
		struct pf_rule *rule;

		while ((rule = TAILQ_FIRST(pf_rules_inactive)) != NULL) {
			TAILQ_REMOVE(pf_rules_inactive, rule, entries);
			pool_put(&pf_rule_pl, rule);
		}
		*ticket = ++ticket_rules_inactive;
		break;
	}

	case DIOCADDRULE: {
		struct pfioc_rule *pr = (struct pfioc_rule *)addr;
		struct pf_rule *rule, *tail;

		if (pr->ticket != ticket_rules_inactive) {
			error = EBUSY;
			break;
		}
		rule = pool_get(&pf_rule_pl, PR_NOWAIT);
		if (rule == NULL) {
			error = ENOMEM;
			break;
		}
		bcopy(&pr->rule, rule, sizeof(struct pf_rule));
#ifndef INET
		if (rule->af == AF_INET) {
			error = EAFNOSUPPORT;
			break;
		}
#endif /* INET */
#ifndef INET6
		if (rule->af == AF_INET6) {
			error = EAFNOSUPPORT;
			break;
		}
#endif /* INET6 */
		tail = TAILQ_LAST(pf_rules_inactive, pf_rulequeue);
		if (tail)
			rule->nr = tail->nr + 1;
		else
			rule->nr = 0;
		rule->ifp = NULL;
		if (rule->ifname[0]) {
			rule->ifp = ifunit(rule->ifname);
			if (rule->ifp == NULL) {
				pool_put(&pf_rule_pl, rule);
				error = EINVAL;
				break;
			}
		} else
			rule->ifp = NULL;
		rule->evaluations = rule->packets = rule->bytes = 0;
		TAILQ_INSERT_TAIL(pf_rules_inactive, rule, entries);
		break;
	}

	case DIOCCOMMITRULES: {
		u_int32_t *ticket = (u_int32_t *)addr;
		struct pf_rulequeue *old_rules;
		struct pf_rule *rule;
		struct pf_tree_node *n;

		if (*ticket != ticket_rules_inactive) {
			error = EBUSY;
			break;
		}

		/* Swap rules, keep the old. */
		s = splsoftnet();
		/*
		 * Rules are about to get freed, clear rule pointers in states
		 */
		for (n = pf_tree_first(tree_ext_gwy); n != NULL;
		    n = pf_tree_next(n))
			n->state->rule = NULL;
		old_rules = pf_rules_active;
		pf_rules_active = pf_rules_inactive;
		pf_rules_inactive = old_rules;
		ticket_rules_active = ticket_rules_inactive;
		pf_calc_skip_steps(pf_rules_active);
		splx(s);

		/* Purge the old rule list. */
		while ((rule = TAILQ_FIRST(old_rules)) != NULL) {
			TAILQ_REMOVE(old_rules, rule, entries);
			pool_put(&pf_rule_pl, rule);
		}
		break;
	}

	case DIOCGETRULES: {
		struct pfioc_rule *pr = (struct pfioc_rule *)addr;
		struct pf_rule *tail;

		s = splsoftnet();
		tail = TAILQ_LAST(pf_rules_active, pf_rulequeue);
		if (tail)
			pr->nr = tail->nr + 1;
		else
			pr->nr = 0;
		pr->ticket = ticket_rules_active;
		splx(s);
		break;
	}

	case DIOCGETRULE: {
		struct pfioc_rule *pr = (struct pfioc_rule *)addr;
		struct pf_rule *rule;

		if (pr->ticket != ticket_rules_active) {
			error = EBUSY;
			break;
		}
		s = splsoftnet();
		rule = TAILQ_FIRST(pf_rules_active);
		while ((rule != NULL) && (rule->nr != pr->nr))
			rule = TAILQ_NEXT(rule, entries);
		if (rule == NULL) {
			error = EBUSY;
			splx(s);
			break;
		}
		bcopy(rule, &pr->rule, sizeof(struct pf_rule));
		splx(s);
		break;
	}

	case DIOCCHANGERULE: {
		struct pfioc_changerule *pcr = (struct pfioc_changerule *)addr;
		struct pf_rule *oldrule = NULL, *newrule = NULL;
		u_int32_t nr = 0;

		if (pcr->action < PF_CHANGE_ADD_HEAD ||
		    pcr->action > PF_CHANGE_REMOVE) {
			error = EINVAL;
			break;
		}

		if (pcr->action != PF_CHANGE_REMOVE) {
			newrule = pool_get(&pf_rule_pl, PR_NOWAIT);
			if (newrule == NULL) {
				error = ENOMEM;
				break;
			}
			bcopy(&pcr->newrule, newrule, sizeof(struct pf_rule));
#ifndef INET
			if (newrule->af == AF_INET) {
				error = EAFNOSUPPORT;
				break;
			}
#endif /* INET */
#ifndef INET6
			if (newrule->af == AF_INET6) {
				error = EAFNOSUPPORT;
				break;
			}
#endif /* INET6 */
			newrule->ifp = NULL;
			if (newrule->ifname[0]) {
				newrule->ifp = ifunit(newrule->ifname);
				if (newrule->ifp == NULL) {
					pool_put(&pf_rule_pl, newrule);
					error = EINVAL;
					break;
				}
			}
			newrule->evaluations = newrule->packets = 0;
			newrule->bytes = 0;
		}

		s = splsoftnet();

		if (pcr->action == PF_CHANGE_ADD_HEAD)
			oldrule = TAILQ_FIRST(pf_rules_active);
		else if (pcr->action == PF_CHANGE_ADD_TAIL)
			oldrule = TAILQ_LAST(pf_rules_active, pf_rulequeue);
		else {
			oldrule = TAILQ_FIRST(pf_rules_active);
			while ((oldrule != NULL) && pf_compare_rules(oldrule,
			    &pcr->oldrule))
				oldrule = TAILQ_NEXT(oldrule, entries);
			if (oldrule == NULL) {
				error = EINVAL;
				splx(s);
				break;
			}
		}

		if (pcr->action == PF_CHANGE_REMOVE) {
			struct pf_tree_node *n;

			for (n = pf_tree_first(tree_ext_gwy); n != NULL;
			    n = pf_tree_next(n))
				if (n->state->rule == oldrule)
					n->state->rule = NULL;
			TAILQ_REMOVE(pf_rules_active, oldrule, entries);
			pool_put(&pf_rule_pl, oldrule);
		} else {
			if (oldrule == NULL)
				TAILQ_INSERT_TAIL(pf_rules_active, newrule,
				    entries);
			else if (pcr->action == PF_CHANGE_ADD_HEAD ||
			    pcr->action == PF_CHANGE_ADD_BEFORE)
				TAILQ_INSERT_BEFORE(oldrule, newrule, entries);
			else
				TAILQ_INSERT_AFTER(pf_rules_active, oldrule,
				    newrule, entries);
		}

		TAILQ_FOREACH(oldrule, pf_rules_active, entries)
			oldrule->nr = nr++;

		pf_calc_skip_steps(pf_rules_active);

		ticket_rules_active++;
		splx(s);
		break;
	}

	case DIOCBEGINNATS: {
		u_int32_t *ticket = (u_int32_t *)addr;
		struct pf_nat *nat;

		while ((nat = TAILQ_FIRST(pf_nats_inactive)) != NULL) {
			TAILQ_REMOVE(pf_nats_inactive, nat, entries);
			pool_put(&pf_nat_pl, nat);
		}
		*ticket = ++ticket_nats_inactive;
		break;
	}

	case DIOCADDNAT: {
		struct pfioc_nat *pn = (struct pfioc_nat *)addr;
		struct pf_nat *nat;

		if (pn->ticket != ticket_nats_inactive) {
			error = EBUSY;
			break;
		}
		nat = pool_get(&pf_nat_pl, PR_NOWAIT);
		if (nat == NULL) {
			error = ENOMEM;
			break;
		}
		bcopy(&pn->nat, nat, sizeof(struct pf_nat));
#ifndef INET
		if (nat->af == AF_INET) {
			error = EAFNOSUPPORT;
			break;
		}
#endif /* INET */
#ifndef INET6
		if (nat->af == AF_INET6) {
			error = EAFNOSUPPORT;
			break;
		}
#endif /* INET6 */
		if (nat->ifname[0]) {
			nat->ifp = ifunit(nat->ifname);
			if (nat->ifp == NULL) {
				pool_put(&pf_nat_pl, nat);
				error = EINVAL;
				break;
			}
		} else
			nat->ifp = NULL;
		TAILQ_INSERT_TAIL(pf_nats_inactive, nat, entries);
		break;
	}

	case DIOCCOMMITNATS: {
		u_int32_t *ticket = (u_int32_t *)addr;
		struct pf_natqueue *old_nats;
		struct pf_nat *nat;

		if (*ticket != ticket_nats_inactive) {
			error = EBUSY;
			break;
		}

		/* Swap nats, keep the old. */
		s = splsoftnet();
		old_nats = pf_nats_active;
		pf_nats_active = pf_nats_inactive;
		pf_nats_inactive = old_nats;
		ticket_nats_active = ticket_nats_inactive;
		splx(s);

		/* Purge the old nat list */
		while ((nat = TAILQ_FIRST(old_nats)) != NULL) {
			TAILQ_REMOVE(old_nats, nat, entries);
			pool_put(&pf_nat_pl, nat);
		}
		break;
	}

	case DIOCGETNATS: {
		struct pfioc_nat *pn = (struct pfioc_nat *)addr;
		struct pf_nat *nat;

		pn->nr = 0;
		s = splsoftnet();
		TAILQ_FOREACH(nat, pf_nats_active, entries)
			pn->nr++;
		pn->ticket = ticket_nats_active;
		splx(s);
		break;
	}

	case DIOCGETNAT: {
		struct pfioc_nat *pn = (struct pfioc_nat *)addr;
		struct pf_nat *nat;
		u_int32_t nr;

		if (pn->ticket != ticket_nats_active) {
			error = EBUSY;
			break;
		}
		nr = 0;
		s = splsoftnet();
		nat = TAILQ_FIRST(pf_nats_active);
		while ((nat != NULL) && (nr < pn->nr)) {
			nat = TAILQ_NEXT(nat, entries);
			nr++;
		}
		if (nat == NULL) {
			error = EBUSY;
			splx(s);
			break;
		}
		bcopy(nat, &pn->nat, sizeof(struct pf_nat));
		splx(s);
		break;
	}

	case DIOCCHANGENAT: {
		struct pfioc_changenat *pcn = (struct pfioc_changenat *)addr;
		struct pf_nat *oldnat = NULL, *newnat = NULL;

		if (pcn->action < PF_CHANGE_ADD_HEAD ||
		    pcn->action > PF_CHANGE_REMOVE) {
			error = EINVAL;
			break;
		}

		if (pcn->action != PF_CHANGE_REMOVE) {
			newnat = pool_get(&pf_nat_pl, PR_NOWAIT);
			if (newnat == NULL) {
				error = ENOMEM;
				break;
			}
			bcopy(&pcn->newnat, newnat, sizeof(struct pf_nat));
#ifndef INET
			if (newnat->af == AF_INET) {
				error = EAFNOSUPPORT;
				break;
			}
#endif /* INET */
#ifndef INET6
			if (newnat->af == AF_INET6) {
				error = EAFNOSUPPORT;
				break;
			}
#endif /* INET6 */
			newnat->ifp = NULL;
			if (newnat->ifname[0]) {
				newnat->ifp = ifunit(newnat->ifname);
				if (newnat->ifp == NULL) {
					pool_put(&pf_nat_pl, newnat);
					error = EINVAL;
					break;
				}
			}
		}

		s = splsoftnet();

		if (pcn->action == PF_CHANGE_ADD_HEAD)
			oldnat = TAILQ_FIRST(pf_nats_active);
		else if (pcn->action == PF_CHANGE_ADD_TAIL)
			oldnat = TAILQ_LAST(pf_nats_active, pf_natqueue);
		else {
			oldnat = TAILQ_FIRST(pf_nats_active);
			while ((oldnat != NULL) && pf_compare_nats(oldnat,
			    &pcn->oldnat))
				oldnat = TAILQ_NEXT(oldnat, entries);
			if (oldnat == NULL) {
				error = EINVAL;
				splx(s);
				break;
			}
		}

		if (pcn->action == PF_CHANGE_REMOVE) {
			TAILQ_REMOVE(pf_nats_active, oldnat, entries);
			pool_put(&pf_nat_pl, oldnat);
		} else {
			if (oldnat == NULL)
				TAILQ_INSERT_TAIL(pf_nats_active, newnat,
				    entries);
			else if (pcn->action == PF_CHANGE_ADD_HEAD ||
			    pcn->action == PF_CHANGE_ADD_BEFORE)
				TAILQ_INSERT_BEFORE(oldnat, newnat, entries);
			else
				TAILQ_INSERT_AFTER(pf_nats_active, oldnat,
				     newnat, entries);
		}

		ticket_nats_active++;
		splx(s);
		break;
	}

	case DIOCBEGINBINATS: {
		u_int32_t *ticket = (u_int32_t *)addr;
		struct pf_binat *binat;

		while ((binat = TAILQ_FIRST(pf_binats_inactive)) != NULL) {
			TAILQ_REMOVE(pf_binats_inactive, binat, entries);
			pool_put(&pf_binat_pl, binat);
		}
		*ticket = ++ticket_binats_inactive;
		break;
	}

	case DIOCADDBINAT: {
		struct pfioc_binat *pb = (struct pfioc_binat *)addr;
		struct pf_binat *binat;

		if (pb->ticket != ticket_binats_inactive) {
			error = EBUSY;
			break;
		}
		binat = pool_get(&pf_binat_pl, PR_NOWAIT);
		if (binat == NULL) {
			error = ENOMEM;
			break;
		}
		bcopy(&pb->binat, binat, sizeof(struct pf_binat));
#ifndef INET
		if (binat->af == AF_INET) {
			error = EAFNOSUPPORT;
			break;
		}
#endif /* INET */
#ifndef INET6
		if (binat->af == AF_INET6) {
			error = EAFNOSUPPORT;
			break;
		}
#endif /* INET6 */
		if (binat->ifname[0]) {
			binat->ifp = ifunit(binat->ifname);
			if (binat->ifp == NULL) {
				pool_put(&pf_binat_pl, binat);
				error = EINVAL;
				break;
			}
		} else
			binat->ifp = NULL;
		TAILQ_INSERT_TAIL(pf_binats_inactive, binat, entries);
		break;
	}

	case DIOCCOMMITBINATS: {
		u_int32_t *ticket = (u_int32_t *)addr;
		struct pf_binatqueue *old_binats;
		struct pf_binat *binat;

		if (*ticket != ticket_binats_inactive) {
			error = EBUSY;
			break;
		}

		/* Swap binats, keep the old. */
		s = splsoftnet();
		old_binats = pf_binats_active;
		pf_binats_active = pf_binats_inactive;
		pf_binats_inactive = old_binats;
		ticket_binats_active = ticket_binats_inactive;
		splx(s);

		/* Purge the old binat list */
		while ((binat = TAILQ_FIRST(old_binats)) != NULL) {
			TAILQ_REMOVE(old_binats, binat, entries);
			pool_put(&pf_binat_pl, binat);
		}
		break;
	}

	case DIOCGETBINATS: {
		struct pfioc_binat *pb = (struct pfioc_binat *)addr;
		struct pf_binat *binat;

		pb->nr = 0;
		s = splsoftnet();
		TAILQ_FOREACH(binat, pf_binats_active, entries)
			pb->nr++;
		pb->ticket = ticket_binats_active;
		splx(s);
		break;
	}

	case DIOCGETBINAT: {
		struct pfioc_binat *pb = (struct pfioc_binat *)addr;
		struct pf_binat *binat;
		u_int32_t nr;

		if (pb->ticket != ticket_binats_active) {
			error = EBUSY;
			break;
		}
		nr = 0;
		s = splsoftnet();
		binat = TAILQ_FIRST(pf_binats_active);
		while ((binat != NULL) && (nr < pb->nr)) {
			binat = TAILQ_NEXT(binat, entries);
			nr++;
		}
		if (binat == NULL) {
			error = EBUSY;
			splx(s);
			break;
		}
		bcopy(binat, &pb->binat, sizeof(struct pf_binat));
		splx(s);
		break;
	}

	case DIOCCHANGEBINAT: {
		struct pfioc_changebinat *pcn = (struct pfioc_changebinat *)addr;
		struct pf_binat *oldbinat = NULL, *newbinat = NULL;

		if (pcn->action < PF_CHANGE_ADD_HEAD ||
		    pcn->action > PF_CHANGE_REMOVE) {
			error = EINVAL;
			break;
		}

		if (pcn->action != PF_CHANGE_REMOVE) {
			newbinat = pool_get(&pf_binat_pl, PR_NOWAIT);
			if (newbinat == NULL) {
				error = ENOMEM;
				break;
			}
			bcopy(&pcn->newbinat, newbinat,
				sizeof(struct pf_binat));
#ifndef INET
			if (newbinat->af == AF_INET) {
				error = EAFNOSUPPORT;
				break;
			}
#endif /* INET */
#ifndef INET6
			if (newbinat->af == AF_INET6) {
				error = EAFNOSUPPORT;
				break;
			}
#endif /* INET6 */
			newbinat->ifp = NULL;
			if (newbinat->ifname[0]) {
				newbinat->ifp = ifunit(newbinat->ifname);
				if (newbinat->ifp == NULL) {
					pool_put(&pf_binat_pl, newbinat);
					error = EINVAL;
					break;
				}
			}
		}

		s = splsoftnet();

		if (pcn->action == PF_CHANGE_ADD_HEAD)
			oldbinat = TAILQ_FIRST(pf_binats_active);
		else if (pcn->action == PF_CHANGE_ADD_TAIL)
			oldbinat = TAILQ_LAST(pf_binats_active, pf_binatqueue);
		else {
			oldbinat = TAILQ_FIRST(pf_binats_active);
			while ((oldbinat != NULL) && pf_compare_binats(oldbinat,
			    &pcn->oldbinat))
				oldbinat = TAILQ_NEXT(oldbinat, entries);
			if (oldbinat == NULL) {
				error = EINVAL;
				splx(s);
				break;
			}
		}

		if (pcn->action == PF_CHANGE_REMOVE) {
			TAILQ_REMOVE(pf_binats_active, oldbinat, entries);
			pool_put(&pf_binat_pl, oldbinat);
		} else {
			if (oldbinat == NULL)
				TAILQ_INSERT_TAIL(pf_binats_active, newbinat,
				    entries);
			else if (pcn->action == PF_CHANGE_ADD_HEAD ||
			    pcn->action == PF_CHANGE_ADD_BEFORE)
				TAILQ_INSERT_BEFORE(oldbinat, newbinat, 
				    entries);
			else
				TAILQ_INSERT_AFTER(pf_binats_active, oldbinat,
				     newbinat, entries);
		}

		ticket_binats_active++;
		splx(s);
		break;
	}

	case DIOCBEGINRDRS: {
		u_int32_t *ticket = (u_int32_t *)addr;
		struct pf_rdr *rdr;

		while ((rdr = TAILQ_FIRST(pf_rdrs_inactive)) != NULL) {
			TAILQ_REMOVE(pf_rdrs_inactive, rdr, entries);
			pool_put(&pf_rdr_pl, rdr);
		}
		*ticket = ++ticket_rdrs_inactive;
		break;
	}

	case DIOCADDRDR: {
		struct pfioc_rdr *pr = (struct pfioc_rdr *)addr;
		struct pf_rdr *rdr;

		if (pr->ticket != ticket_rdrs_inactive) {
			error = EBUSY;
			break;
		}
		rdr = pool_get(&pf_rdr_pl, PR_NOWAIT);
		if (rdr == NULL) {
			error = ENOMEM;
			break;
		}
		bcopy(&pr->rdr, rdr, sizeof(struct pf_rdr));
#ifndef INET
		if (rdr->af == AF_INET) {
			error = EAFNOSUPPORT;
			break;
		}
#endif /* INET */
#ifndef INET6
		if (rdr->af == AF_INET6) {
			error = EAFNOSUPPORT;
			break;
		}
#endif /* INET6 */
		if (rdr->ifname[0]) {
			rdr->ifp = ifunit(rdr->ifname);
			if (rdr->ifp == NULL) {
				pool_put(&pf_rdr_pl, rdr);
				error = EINVAL;
				break;
			}
		} else
			rdr->ifp = NULL;
		TAILQ_INSERT_TAIL(pf_rdrs_inactive, rdr, entries);
		break;
	}

	case DIOCCOMMITRDRS: {
		u_int32_t *ticket = (u_int32_t *)addr;
		struct pf_rdrqueue *old_rdrs;
		struct pf_rdr *rdr;

		if (*ticket != ticket_rdrs_inactive) {
			error = EBUSY;
			break;
		}

		/* Swap rdrs, keep the old. */
		s = splsoftnet();
		old_rdrs = pf_rdrs_active;
		pf_rdrs_active = pf_rdrs_inactive;
		pf_rdrs_inactive = old_rdrs;
		ticket_rdrs_active = ticket_rdrs_inactive;
		splx(s);

		/* Purge the old rdr list */
		while ((rdr = TAILQ_FIRST(old_rdrs)) != NULL) {
			TAILQ_REMOVE(old_rdrs, rdr, entries);
			pool_put(&pf_rdr_pl, rdr);
		}
		break;
	}

	case DIOCGETRDRS: {
		struct pfioc_rdr *pr = (struct pfioc_rdr *)addr;
		struct pf_rdr *rdr;

		pr->nr = 0;
		s = splsoftnet();
		TAILQ_FOREACH(rdr, pf_rdrs_active, entries)
			pr->nr++;
		pr->ticket = ticket_rdrs_active;
		splx(s);
		break;
	}

	case DIOCGETRDR: {
		struct pfioc_rdr *pr = (struct pfioc_rdr *)addr;
		struct pf_rdr *rdr;
		u_int32_t nr;

		if (pr->ticket != ticket_rdrs_active) {
			error = EBUSY;
			break;
		}
		nr = 0;
		s = splsoftnet();
		rdr = TAILQ_FIRST(pf_rdrs_active);
		while ((rdr != NULL) && (nr < pr->nr)) {
			rdr = TAILQ_NEXT(rdr, entries);
			nr++;
		}
		if (rdr == NULL) {
			error = EBUSY;
			splx(s);
			break;
		}
		bcopy(rdr, &pr->rdr, sizeof(struct pf_rdr));
		splx(s);
		break;
	}

	case DIOCCHANGERDR: {
		struct pfioc_changerdr *pcn = (struct pfioc_changerdr *)addr;
		struct pf_rdr *oldrdr = NULL, *newrdr = NULL;

		if (pcn->action < PF_CHANGE_ADD_HEAD ||
		    pcn->action > PF_CHANGE_REMOVE) {
			error = EINVAL;
			break;
		}

		if (pcn->action != PF_CHANGE_REMOVE) {
			newrdr = pool_get(&pf_rdr_pl, PR_NOWAIT);
			if (newrdr == NULL) {
				error = ENOMEM;
				break;
			}
			bcopy(&pcn->newrdr, newrdr, sizeof(struct pf_rdr));
#ifndef INET
			if (newrdr->af == AF_INET) {
				error = EAFNOSUPPORT;
				break;
			}
#endif /* INET */
#ifndef INET6
			if (newrdr->af == AF_INET6) {
				error = EAFNOSUPPORT;
				break;
			}
#endif /* INET6 */
			newrdr->ifp = NULL;
			if (newrdr->ifname[0]) {
				newrdr->ifp = ifunit(newrdr->ifname);
				if (newrdr->ifp == NULL) {
					pool_put(&pf_rdr_pl, newrdr);
					error = EINVAL;
					break;
				}
			}
		}

		s = splsoftnet();

		if (pcn->action == PF_CHANGE_ADD_HEAD)
			oldrdr = TAILQ_FIRST(pf_rdrs_active);
		else if (pcn->action == PF_CHANGE_ADD_TAIL)
			oldrdr = TAILQ_LAST(pf_rdrs_active, pf_rdrqueue);
		else {
			oldrdr = TAILQ_FIRST(pf_rdrs_active);
			while ((oldrdr != NULL) && pf_compare_rdrs(oldrdr,
			    &pcn->oldrdr))
				oldrdr = TAILQ_NEXT(oldrdr, entries);
			if (oldrdr == NULL) {
				error = EINVAL;
				splx(s);
				break;
			}
		}

		if (pcn->action == PF_CHANGE_REMOVE) {
			TAILQ_REMOVE(pf_rdrs_active, oldrdr, entries);
			pool_put(&pf_rdr_pl, oldrdr);
		} else {
			if (oldrdr == NULL)
				TAILQ_INSERT_TAIL(pf_rdrs_active, newrdr,
				    entries);
			else if (pcn->action == PF_CHANGE_ADD_HEAD ||
			    pcn->action == PF_CHANGE_ADD_BEFORE)
				TAILQ_INSERT_BEFORE(oldrdr, newrdr, entries);
			else
				TAILQ_INSERT_AFTER(pf_rdrs_active, oldrdr,
				     newrdr, entries);
		}

		ticket_rdrs_active++;
		splx(s);
		break;
	}

	case DIOCCLRSTATES: {
		struct pf_tree_node *n;

		s = splsoftnet();
		for (n = pf_tree_first(tree_ext_gwy); n != NULL;
		    n = pf_tree_next(n))
			n->state->expire = 0;
		pf_purge_expired_states();
		splx(s);
		break;
	}

	case DIOCGETSTATE: {
		struct pfioc_state *ps = (struct pfioc_state *)addr;
		struct pf_tree_node *n;
		u_int32_t nr;

		nr = 0;
		s = splsoftnet();
		n = pf_tree_first(tree_ext_gwy);
		while ((n != NULL) && (nr < ps->nr)) {
			n = pf_tree_next(n);
			nr++;
		}
		if (n == NULL) {
			error = EBUSY;
			splx(s);
			break;
		}
		bcopy(n->state, &ps->state, sizeof(struct pf_state));
		splx(s);
		microtime(&pftv);
		ps->state.creation = pftv.tv_sec - ps->state.creation;
		if (ps->state.expire <= pftv.tv_sec)
			ps->state.expire = 0;
		else
			ps->state.expire -= pftv.tv_sec;
		break;
	}

	case DIOCGETSTATES: {
		struct pfioc_states *ps = (struct pfioc_states *)addr;
		struct pf_tree_node *n;
		struct pf_state *p, pstore;
		u_int32_t nr = 0;
		int space = ps->ps_len;

		if (space == 0) {
			s = splsoftnet();
			n = pf_tree_first(tree_ext_gwy);
			while (n != NULL) {
				n = pf_tree_next(n);
				nr++;
			}
			splx(s);
			ps->ps_len = sizeof(struct pf_state) * nr;
			return (0);
		}

		microtime(&pftv);
		s = splsoftnet();
		p = ps->ps_states;
		n = pf_tree_first(tree_ext_gwy);
		while (n && (nr + 1) * sizeof(*p) <= ps->ps_len) {
			bcopy(n->state, &pstore, sizeof(pstore));
			pstore.creation = pftv.tv_sec - pstore.creation;
			if (pstore.expire <= pftv.tv_sec)
				pstore.expire = 0;
			else
				pstore.expire -= pftv.tv_sec;
			error = copyout(&pstore, p, sizeof(*p));
			if (error) {
				splx(s);
				goto fail;
			}
			p++;
			nr++;
			n = pf_tree_next(n);
		}
		ps->ps_len = sizeof(struct pf_state) * nr;
		splx(s);
		break;
	}

	case DIOCSETSTATUSIF: {
		struct pfioc_if *pi = (struct pfioc_if *)addr;
		struct ifnet *ifp;

		if ((ifp = ifunit(pi->ifname)) == NULL)
			error = EINVAL;
		else
			status_ifp = ifp;
		break;
	}

	case DIOCGETSTATUS: {
		struct pf_status *s = (struct pf_status *)addr;
		bcopy(&pf_status, s, sizeof(struct pf_status));
		break;
	}

	case DIOCCLRSTATUS: {
		u_int8_t running = pf_status.running;
		u_int32_t states = pf_status.states;

		bzero(&pf_status, sizeof(struct pf_status));
		pf_status.running = running;
		pf_status.states = states;
		break;
	}

	case DIOCNATLOOK: {
		struct pfioc_natlook *pnl = (struct pfioc_natlook *)addr;
		struct pf_state *st;
		struct pf_tree_key key;
		int direction = pnl->direction;

		key.af = pnl->af;
		key.proto = pnl->proto;

		/*
		 * userland gives us source and dest of connetion, reverse
		 * the lookup so we ask for what happens with the return
		 * traffic, enabling us to find it in the state tree.
		 */
		PF_ACPY(&key.addr[1], &pnl->saddr, pnl->af);
		key.port[1] = pnl->sport;
		PF_ACPY(&key.addr[0], &pnl->daddr, pnl->af);
		key.port[0] = pnl->dport;

		if (!pnl->proto || 
		    !PF_AZERO(&pnl->saddr, pnl->af) ||
		    !PF_AZERO(&pnl->daddr, pnl->af) ||
		    !pnl->dport || !pnl->sport)
			error = EINVAL;
		else {
			s = splsoftnet();
			if (direction == PF_IN)
				st = pf_find_state(tree_ext_gwy, &key);
			else
				st = pf_find_state(tree_lan_ext, &key);
			if (st != NULL) {
				if (direction  == PF_IN) {
					PF_ACPY(&pnl->rsaddr, &st->lan.addr,
					    st->af);
					pnl->rsport = st->lan.port;
					PF_ACPY(&pnl->rdaddr, &pnl->daddr,
					    pnl->af);
					pnl->rdport = pnl->dport;
				} else {
					PF_ACPY(&pnl->rdaddr, &st->gwy.addr,
					    st->af);
					pnl->rdport = st->gwy.port;
					PF_ACPY(&pnl->rsaddr, &pnl->saddr,
					    pnl->af);
					pnl->rsport = pnl->sport;
				}
			} else
				error = ENOENT;
			splx(s);
		}
		break;
	}

	case DIOCSETTIMEOUT: {
		struct pfioc_tm *pt = (struct pfioc_tm *)addr;
		int old;

		if (pt->timeout < 0 || pt->timeout >= PFTM_MAX ||
		    pt->seconds < 0) {
			error = EINVAL;
			goto fail;
		}
		old = *pftm_timeouts[pt->timeout];
		*pftm_timeouts[pt->timeout] = pt->seconds;
		pt->seconds = old;
		break;
	}

	case DIOCGETTIMEOUT: {
		struct pfioc_tm *pt = (struct pfioc_tm *)addr;

		if (pt->timeout < 0 || pt->timeout >= PFTM_MAX) {
			error = EINVAL;
			goto fail;
		}
		pt->seconds = *pftm_timeouts[pt->timeout];
		break;
	}

	case DIOCSETDEBUG: {
		u_int32_t *level = (u_int32_t *)addr;
		pf_status.debug = *level;
		break;
	}

	default:
		error = ENODEV;
		break;
	}
fail:

	return (error);
}

#define		 PF_CALC_SKIP_STEP(i, c) \
		do { \
			if (a & 1 << i) { \
				if (c) \
					r->skip[i] = TAILQ_NEXT(s, entries); \
				else \
					a ^= 1 << i; \
			} \
		} while (0)

void
pf_calc_skip_steps(struct pf_rulequeue *rules)
{
	struct pf_rule *r, *s;
	int a, i;

	r = TAILQ_FIRST(rules);
	while (r != NULL) {
		a = 0;
		for (i = 0; i < 6; ++i) {
			a |= 1 << i;
			r->skip[i] = TAILQ_NEXT(r, entries);
		}
		s = TAILQ_NEXT(r, entries);
		while (a && s != NULL) {
			PF_CALC_SKIP_STEP(0, s->ifp == r->ifp);
			PF_CALC_SKIP_STEP(1, s->af == r->af);
			PF_CALC_SKIP_STEP(2, s->proto == r->proto);
			PF_CALC_SKIP_STEP(3,
			    PF_AEQ(&s->src.addr, &r->src.addr, r->af) &&
			    PF_AEQ(&s->src.mask, &r->src.mask, r->af) &&
			    s->src.not == r->src.not);
			PF_CALC_SKIP_STEP(4,
			    s->src.port[0] == r->src.port[0] &&	
			    s->src.port[1] == r->src.port[1] &&
			    s->src.port_op == r->src.port_op);
			PF_CALC_SKIP_STEP(5,
			    PF_AEQ(&s->dst.addr, &r->dst.addr, r->af) &&
			    PF_AEQ(&s->dst.mask, &r->dst.mask, r->af) &&
			    s->dst.not == r->dst.not);
			PF_CALC_SKIP_STEP(6,
			    s->dst.port[0] == r->dst.port[0] &&
			    s->dst.port[1] == r->dst.port[1] &&
			    s->dst.port_op == r->dst.port_op);
			s = TAILQ_NEXT(s, entries);
		}
		r = TAILQ_NEXT(r, entries);
	}
}

u_int16_t
pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
{
	u_int32_t l;

	if (udp && !cksum)
		return 0x0000;
	l = cksum + old - new;
	l = (l >> 16) + (l & 65535);
	l = l & 65535;
	if (udp && !l)
		return 0xFFFF;
	return (l);
}

void
pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
    struct pf_addr *an, u_int16_t pn, u_int8_t u, int af)
{
	struct pf_addr ao;
	u_int16_t po = *p;

	PF_ACPY(&ao, a, af);
	PF_ACPY(a, an, af);

	*p = pn;

	switch (af) {
#ifdef INET
	case AF_INET:
		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
		    ao.addr16[0], an->addr16[0], 0),
		    ao.addr16[1], an->addr16[1], 0);
		*p = pn;
		*pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
		    ao.addr16[0], an->addr16[0], u),
		    ao.addr16[1], an->addr16[1], u),
		    po, pn, u);
		break;
#endif /* INET */
#ifdef INET6
	case AF_INET6:
		*pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
		    ao.addr16[0], an->addr16[0], u),
		    ao.addr16[1], an->addr16[1], u),
		    ao.addr16[2], an->addr16[2], u),
		    ao.addr16[3], an->addr16[3], u),
		    ao.addr16[4], an->addr16[4], u),
		    ao.addr16[5], an->addr16[5], u),
       		    ao.addr16[6], an->addr16[6], u),
		    ao.addr16[7], an->addr16[7], u),
		    po, pn, u); 
		break;
#endif /* INET6 */
	}
}

void
pf_change_a(u_int32_t *a, u_int16_t *c, u_int32_t an, u_int8_t u)
{
	u_int32_t ao = *a;

	*a = an;
	*c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
	   ao % 65536, an % 65536, u);
}

#ifdef INET6
void
pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
{
        struct pf_addr ao;

	PF_ACPY(&ao, a, AF_INET6);
	PF_ACPY(a, an, AF_INET6);

	*c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
	    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
	    pf_cksum_fixup(pf_cksum_fixup(*c,
	    ao.addr16[0], an->addr16[0], u),
	    ao.addr16[1], an->addr16[1], u),
	    ao.addr16[2], an->addr16[2], u),
	    ao.addr16[3], an->addr16[3], u),
	    ao.addr16[4], an->addr16[4], u),
	    ao.addr16[5], an->addr16[5], u),
       	    ao.addr16[6], an->addr16[6], u),
	    ao.addr16[7], an->addr16[7], u);
}
#endif /* INET6 */

void
pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
    struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
    u_int16_t *ic, u_int16_t *hc, u_int8_t u, int af)
{
	struct pf_addr oia, ooa;
	u_int32_t opc, oh2c = *h2c;
	u_int16_t oip = *ip;

	PF_ACPY(&oia, ia, af);
	PF_ACPY(&ooa, oa, af);

	if (pc != NULL)
		opc = *pc;
	/* Change inner protocol port, fix inner protocol checksum. */
	*ip = np;
	if (pc != NULL)
		*pc = pf_cksum_fixup(*pc, oip, *ip, u);
	*ic = pf_cksum_fixup(*ic, oip, *ip, 0);
	if (pc != NULL)
		*ic = pf_cksum_fixup(*ic, opc, *pc, 0);
	PF_ACPY(ia, na, af);
	/* Change inner ip address, fix inner ipv4 checksum and icmp checksum. */
	switch (af) {
#ifdef INET
	case AF_INET:
		*h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
		    oia.addr16[0], ia->addr16[0], 0),
		    oia.addr16[1], ia->addr16[1], 0);
		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
		    oia.addr16[0], ia->addr16[0], 0),
		    oia.addr16[1], ia->addr16[1], 0);
		break;
#endif /* INET */
#ifdef INET6
	case AF_INET6:
		*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
		    pf_cksum_fixup(pf_cksum_fixup(*ic,
		    oia.addr16[0], ia->addr16[0], u),
		    oia.addr16[1], ia->addr16[1], u),
		    oia.addr16[2], ia->addr16[2], u),
		    oia.addr16[3], ia->addr16[3], u),
		    oia.addr16[4], ia->addr16[4], u),
		    oia.addr16[5], ia->addr16[5], u),
       		    oia.addr16[6], ia->addr16[6], u),
		    oia.addr16[7], ia->addr16[7], u);
		break;
#endif /* INET6 */
	}
	*ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
	/* Change outer ip address, fix outer ipv4 or icmpv6 checksum. */
	PF_ACPY(oa, na, af);
	switch (af) {
#ifdef INET
	case AF_INET:
		*hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
		    ooa.addr16[0], oa->addr16[0], 0),
		    ooa.addr16[1], oa->addr16[1], 0);
		break;
#endif /* INET */
#ifdef INET6
	case AF_INET6:
		*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
		    pf_cksum_fixup(pf_cksum_fixup(*ic,
		    ooa.addr16[0], oa->addr16[0], u),
		    ooa.addr16[1], oa->addr16[1], u),
		    ooa.addr16[2], oa->addr16[2], u),
		    ooa.addr16[3], oa->addr16[3], u),
		    ooa.addr16[4], oa->addr16[4], u),
		    ooa.addr16[5], oa->addr16[5], u),
       		    ooa.addr16[6], oa->addr16[6], u),
		    ooa.addr16[7], oa->addr16[7], u);
		break;
#endif /* INET6 */
	}
}

void
pf_send_reset(int off, struct tcphdr *th, struct pf_pdesc *pd, int af)
{
	struct mbuf *m;
	struct m_tag *mtag;
	int len;
#ifdef INET
	struct ip *h2;
#endif /* INET */
#ifdef INET6
	struct ip6_hdr *h2_6;
#endif /* INET6 */
	struct tcphdr *th2;

	switch (af) {
#ifdef INET
	case AF_INET:
		len = sizeof(struct ip) + sizeof(struct tcphdr);
		break;
#endif /* INET */
#ifdef INET6
	case AF_INET6:
		len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
		break;
#endif /* INET6 */
	}

	/* don't reply to RST packets */
	if (th->th_flags & TH_RST)
		return;

	/* create outgoing mbuf */
	mtag = m_tag_get(PACKET_TAG_PF_GENERATED, 0, M_NOWAIT);
	if (mtag == NULL)
		return;
	m = m_gethdr(M_DONTWAIT, MT_HEADER);
	if (m == NULL) {
		m_tag_free(mtag);
		return;
	}
	m_tag_prepend(m, mtag);
	m->m_data += max_linkhdr;
	m->m_pkthdr.len = m->m_len = len;
	m->m_pkthdr.rcvif = NULL;
	bzero(m->m_data, len);
	switch (af) {
#ifdef INET
	case AF_INET:
		h2 = mtod(m, struct ip *);

		/* IP header fields included in the TCP checksum */
		h2->ip_p = IPPROTO_TCP;
		h2->ip_len = htons(sizeof(*th2));
		h2->ip_src.s_addr = pd->dst->v4.s_addr;
		h2->ip_dst.s_addr = pd->src->v4.s_addr;

		th2 = (struct tcphdr *)((caddr_t)h2 + sizeof(struct ip));
		break;
#endif /* INET */
#ifdef INET6
	case AF_INET6:
		h2_6 = mtod(m, struct ip6_hdr *);

		/* IP header fields included in the TCP checksum */
		h2_6->ip6_nxt = IPPROTO_TCP;
		h2_6->ip6_plen = htons(sizeof(*th2));
		memcpy(&h2_6->ip6_src, pd->dst, sizeof(struct in6_addr));
		memcpy(&h2_6->ip6_dst, pd->src, sizeof(struct in6_addr));  

		th2 = (struct tcphdr *)((caddr_t)h2_6 + sizeof(struct ip6_hdr));
		break;
#endif /* INET6 */
	}

	/* TCP header */
	th2->th_sport = th->th_dport;
	th2->th_dport = th->th_sport;
	if (th->th_flags & TH_ACK) {
		th2->th_seq = th->th_ack;
		th2->th_flags = TH_RST;
	} else {
		int tlen = pd->p_len - off - (th->th_off << 2);
		if (th->th_flags & TH_SYN)
			tlen++;
		if (th->th_flags & TH_FIN)
			tlen++;
		th2->th_ack = htonl(ntohl(th->th_seq) + tlen);
		th2->th_flags = TH_RST | TH_ACK;
	}
	th2->th_off = sizeof(*th2) >> 2;

	switch (af) {
#ifdef INET
	case AF_INET:
		/* TCP checksum */
		th2->th_sum = in_cksum(m, len);

		/* Finish the IP header */
		h2->ip_v = 4;
		h2->ip_hl = sizeof(*h2) >> 2;
		h2->ip_ttl = 128;
		h2->ip_sum = 0;
		h2->ip_len = len;
		h2->ip_off = 0;
		ip_output(m, NULL, NULL, 0, NULL, NULL);
		break;
#endif /* INET */
#ifdef INET6
	case AF_INET6:
		/* TCP checksum */
		th2->th_sum = in6_cksum(m, IPPROTO_TCP,
		    sizeof(struct ip6_hdr), sizeof(*th));

		h2_6->ip6_hlim = 128;

		ip6_output(m, NULL, NULL, 0, NULL, NULL);
#endif /* INET6 */
	}
}

void
pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, int af)
{
	struct m_tag *mtag;
	struct mbuf *m0;

	mtag = m_tag_get(PACKET_TAG_PF_GENERATED, 0, M_NOWAIT);
	if (mtag == NULL)
		return;
	m0 = m_copy(m, 0, M_COPYALL);
	if (m0 == NULL) {
		m_tag_free(mtag);
		return;
	}
	m_tag_prepend(m0, mtag);
	switch (af) {
#ifdef INET
	case AF_INET:
		icmp_error(m0, type, code, 0, 0);
		break;
#endif /* INET */
#ifdef INET6
	case AF_INET6:
		icmp6_error(m0, type, code, 0);
		break;
#endif /* INET6 */
	}
}

/*
 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
 * If n is 0, they match if they are equal. If n is != 0, they match if they
 * are different.
 */
int
pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
    struct pf_addr *b, int af)
{
	int match = 0;
	switch (af) {
#ifdef INET
	case AF_INET:
		if ((a->addr32[0] & m->addr32[0]) ==
		    (b->addr32[0] & m->addr32[0]))
			match++;
		break;
#endif /* INET */
#ifdef INET6
	case AF_INET6:
		if (((a->addr32[0] & m->addr32[0]) == 
		     (b->addr32[0] & m->addr32[0])) && 
		    ((a->addr32[1] & m->addr32[1]) == 
		     (b->addr32[1] & m->addr32[1])) && 
		    ((a->addr32[2] & m->addr32[2]) == 
		     (b->addr32[2] & m->addr32[2])) && 
		    ((a->addr32[3] & m->addr32[3]) == 
		     (b->addr32[3] & m->addr32[3]))) 
			match++;
		break;
#endif /* INET6 */
	} 
	if (match) {
		if (n)
			return (0);
		else
			return (1);
	} else {
		if (n)
			return (1);
		else
			return (0);
	}
}

int
pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
{
	NTOHS(a1);
	NTOHS(a2);
	NTOHS(p);
	switch (op) {
	case PF_OP_IRG:
		return (p > a1) && (p < a2);
	case PF_OP_XRG:
		return (p < a1) || (p > a2);
	case PF_OP_EQ:
		return (p == a1);
	case PF_OP_NE:
		return (p != a1);
	case PF_OP_LT:
		return (p < a1);
	case PF_OP_LE:
		return (p <= a1);
	case PF_OP_GT:
		return (p > a1);
	case PF_OP_GE:
		return (p >= a1);
	}
	return (0); /* never reached */
}

int
pf_chk_sport(struct pf_port_list *plist, u_int16_t port)
{
	struct pf_port_node	*pnode;

	LIST_FOREACH(pnode, plist, next) {
		if (pnode->port == port)
			return (1);
	}

	return (0);
}

int
pf_add_sport(struct pf_port_list *plist, u_int16_t port)
{
	struct pf_port_node *pnode;

	pnode = pool_get(&pf_sport_pl, M_NOWAIT);
	if (pnode == NULL)
		return (ENOMEM);

	pnode->port = port;
	LIST_INSERT_HEAD(plist, pnode, next);

	return (0);
}

void
pf_put_sport(u_int8_t proto, u_int16_t port)
{
	struct pf_port_list	*plist;
	struct pf_port_node	*pnode;

	if (proto == IPPROTO_TCP)
		plist = &pf_tcp_ports;
	else if (proto == IPPROTO_UDP)
		plist = &pf_udp_ports;
	else
		return;

	LIST_FOREACH(pnode, plist, next) {
		if (pnode->port == port) {
			LIST_REMOVE(pnode, next);
			pool_put(&pf_sport_pl, pnode);
			break;
		}
	}
}

int
pf_get_sport(u_int8_t proto, u_int16_t low, u_int16_t high, u_int16_t *port)
{
	struct pf_port_list	*plist;
	int			step;
	u_int16_t		cut;

	if (proto == IPPROTO_TCP)
		plist = &pf_tcp_ports;
	else if (proto == IPPROTO_UDP)
		plist = &pf_udp_ports;
	else
		return (EINVAL);

	/* port search; start random, step; similar 2 portloop in in_pcbbind */
	if (low == high) {
		*port = low;
		if (!pf_chk_sport(plist, *port))
			goto found;
		return (1);
	} else if (low < high) {
		step = 1;
		cut = arc4random() % (high - low) + low;
	} else {
		step = -1;
		cut = arc4random() % (low - high) + high;
	}

	*port = cut - step;
	do {
		*port += step;
		if (!pf_chk_sport(plist, *port))
			goto found;
	} while (*port != low && *port != high);

	step = -step;
	*port = cut;
	do {
		*port += step;
		if (!pf_chk_sport(plist, *port))
			goto found;
	} while (*port != low && *port != high);

	return (1);					/* none available */

found:
	return (pf_add_sport(plist, *port));
}

struct pf_nat *
pf_get_nat(struct ifnet *ifp, u_int8_t proto, struct pf_addr *saddr,
    struct pf_addr *daddr, int af)
{
	struct pf_nat *n, *nm = NULL;

	n = TAILQ_FIRST(pf_nats_active);
	while (n && nm == NULL) {
		if (((n->ifp == NULL) || (n->ifp == ifp && !n->ifnot) ||
		    (n->ifp != ifp && n->ifnot)) &&
		    (!n->proto || n->proto == proto) &&
		    (!n->af || n->af == af) &&
		    PF_MATCHA(n->snot, &n->saddr, &n->smask, saddr, af) &&
		    PF_MATCHA(n->dnot, &n->daddr, &n->dmask, daddr, af))
			nm = n;
		else
			n = TAILQ_NEXT(n, entries);
	}
	return (nm);
}

struct pf_binat *
pf_get_binat(int direction, struct ifnet *ifp, u_int8_t proto,
    struct pf_addr *saddr, struct pf_addr *daddr, int af)
{
	struct pf_binat *b, *bm = NULL;
	struct pf_addr fullmask; 

	memset(&fullmask, 0xff, sizeof(fullmask));

	b = TAILQ_FIRST(pf_binats_active);
	while (b && bm == NULL) {
		if (direction == PF_OUT && b->ifp == ifp &&
		    (!b->proto || b->proto == proto) &&
		    (!b->af || b->af == af) &&
		    PF_MATCHA(0, &b->saddr, &fullmask, saddr, af) &&
		    PF_MATCHA(b->dnot, &b->daddr, &b->dmask, daddr, af))
			bm = b;
                else if (direction == PF_IN && b->ifp == ifp &&
		    (!b->proto || b->proto == proto) &&
		    (!b->af || b->af == af) &&
		    PF_MATCHA(0, &b->raddr, &fullmask, saddr, af) &&
		    PF_MATCHA(b->dnot, &b->daddr, &b->dmask, daddr, af))
			bm = b;
		else
			b = TAILQ_NEXT(b, entries);
	}
	return (bm);
}

struct pf_rdr *
pf_get_rdr(struct ifnet *ifp, u_int8_t proto, struct pf_addr *saddr,
    struct pf_addr *daddr, u_int16_t dport, int af)
{
	struct pf_rdr *r, *rm = NULL;

	r = TAILQ_FIRST(pf_rdrs_active);
	while (r && rm == NULL) {
		if (((r->ifp == NULL) || (r->ifp == ifp && !r->ifnot) ||
		    (r->ifp != ifp && r->ifnot)) &&
		    (!r->proto || r->proto == proto) &&
		    (!r->af || r->af == af) &&
		    PF_MATCHA(r->snot, &r->saddr, &r->smask, saddr, af) &&
		    PF_MATCHA(r->dnot, &r->daddr, &r->dmask, daddr, af) &&
		    ((!r->dport2 && dport == r->dport) ||
		    (r->dport2 && (ntohs(dport) >= ntohs(r->dport)) &&
		    ntohs(dport) <= ntohs(r->dport2))))
			rm = r;
		else
			r = TAILQ_NEXT(r, entries);
	}
	return (rm);
}

u_int16_t
pf_map_port_range(struct pf_rdr *rdr, u_int16_t port)
{
	u_int32_t nport;

	nport = ntohs(rdr->rport) - ntohs(rdr->dport) + ntohs(port);
	/* wrap around if necessary */
	if (nport > 65535)
		nport -= 65535;
	return htons((u_int16_t)nport);
}


int
pf_test_tcp(int direction, struct ifnet *ifp, struct mbuf *m,
    int ipoff, int off, void *h, struct pf_pdesc *pd)
{
	struct pf_nat *nat = NULL;
	struct pf_binat *binat = NULL;
	struct pf_rdr *rdr = NULL;
	struct pf_addr *saddr = pd->src, *daddr = pd->dst, baddr;
	struct tcphdr *th = pd->hdr.tcp;
	struct pf_rule *r, *rm = NULL;
	u_int16_t bport, nport = 0, af = pd->af;
	u_short reason;
	int rewrite = 0, error;

	if (direction == PF_OUT) {
		/* check outgoing packet for BINAT */
		if ((binat = pf_get_binat(PF_OUT, ifp, IPPROTO_TCP,
		    saddr, daddr, af)) != NULL) {
			PF_ACPY(&baddr, saddr, af);
			bport = th->th_sport;
			pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
			    &th->th_sum, &binat->raddr, th->th_sport, 0, af);
			rewrite++;
		}
		/* check outgoing packet for NAT */
		else if ((nat = pf_get_nat(ifp, IPPROTO_TCP,
		    saddr, daddr, af)) != NULL) {
			bport = th->th_sport;
			error = pf_get_sport(IPPROTO_TCP, 50001,
			    65535, &nport);
			if (error)
				return (PF_DROP);
			PF_ACPY(&baddr, saddr, af);
			pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
			    &th->th_sum, &nat->raddr, htons(nport), 0, af);
			rewrite++;
		}
	} else {
		/* check incoming packet for RDR */
		if ((rdr = pf_get_rdr(ifp, IPPROTO_TCP, saddr, daddr,
		    th->th_dport, af)) != NULL) {
			bport = th->th_dport;
			if (rdr->opts & PF_RPORT_RANGE)
				nport = pf_map_port_range(rdr, th->th_dport);
			else
				nport = rdr->rport;
			PF_ACPY(&baddr, daddr, af);
			pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
			    &th->th_sum, &rdr->raddr, nport, 0, af);
			rewrite++;
		}
		/* check incoming packet for BINAT */
		else if ((binat = pf_get_binat(PF_IN, ifp, IPPROTO_TCP,
		    daddr, saddr, af)) != NULL) {
			PF_ACPY(&baddr, daddr, af);
			bport = th->th_dport;
			pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
			    &th->th_sum, &binat->saddr, th->th_dport, 0, af);
			rewrite++;
		}
	}

	r = TAILQ_FIRST(pf_rules_active);
	while (r != NULL) {
		if (r->action == PF_SCRUB) {
			r = TAILQ_NEXT(r, entries);
			continue;
		}
		r->evaluations++;
		if (r->ifp != NULL && r->ifp != ifp)
			r = r->skip[0];
		else if (r->af && r->af != af)
			r = r->skip[1];
		else if (r->proto && r->proto != IPPROTO_TCP)
			r = r->skip[2];
		else if (!PF_AZERO(&r->src.mask, af) && !PF_MATCHA(r->src.not,
		    &r->src.addr, &r->src.mask, saddr, af))
			r = r->skip[3];
		else if (r->src.port_op && !pf_match_port(r->src.port_op,
		    r->src.port[0], r->src.port[1], th->th_sport))
			r = r->skip[4];
		else if (!PF_AZERO(&r->dst.mask, af) && !PF_MATCHA(r->dst.not,
		    &r->dst.addr, &r->dst.mask, daddr, af))
			r = r->skip[5];
		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
		    r->dst.port[0], r->dst.port[1], th->th_dport))
			r = r->skip[6];
		else if (r->direction != direction)
			r = TAILQ_NEXT(r, entries);
		else if ((r->flagset & th->th_flags) != r->flags)
			r = TAILQ_NEXT(r, entries);
		else {
			rm = r;
			if (rm->quick)
				break;
			r = TAILQ_NEXT(r, entries);
		}
	}

	if (rm != NULL) {
		rm->packets++;
		rm->bytes += pd->tot_len;
		REASON_SET(&reason, PFRES_MATCH);

		/* XXX will log packet before rewrite */
		if (rm->log)
			PFLOG_PACKET(h, m, af, direction, reason, rm);

		if ((rm->action == PF_DROP) &&
		    ((rm->rule_flag & PFRULE_RETURNRST) || rm->return_icmp)) {
			/* undo NAT/RST changes, if they have taken place */
			if (nat != NULL ||
			    (binat != NULL && direction == PF_OUT)) {
				pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
				    &th->th_sum, &baddr, bport, 0, af);
				rewrite++;
			} else if (rdr != NULL ||
			    (binat != NULL && direction == PF_IN)) {
				pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
				    &th->th_sum, &baddr, bport, 0, af);
				rewrite++;
			}
			if (rm->rule_flag & PFRULE_RETURNRST)
				pf_send_reset(off, th, pd, af);
			else 
				pf_send_icmp(m, rm->return_icmp >> 8,
				    rm->return_icmp & 255, af);
		}

		if (rm->action == PF_DROP) {
			if (nport && nat != NULL)
				pf_put_sport(IPPROTO_TCP, nport);
			return (PF_DROP);
		}
	}

	if (((rm != NULL) && rm->keep_state) || nat != NULL || binat != NULL || rdr != NULL) {
		/* create new state */
		u_int16_t len;
		struct pf_state *s;

		len = pd->tot_len - off - (th->th_off << 2);
		s = pool_get(&pf_state_pl, PR_NOWAIT);
		if (s == NULL) {
			if (nport && nat != NULL)
				pf_put_sport(IPPROTO_TCP, nport);
			return (PF_DROP);
		}

		s->rule = rm;
		s->log = rm && (rm->log & 2);
		s->proto = IPPROTO_TCP;
		s->direction = direction;
		s->af = af;
		if (direction == PF_OUT) {
			PF_ACPY(&s->gwy.addr, saddr, af);
			s->gwy.port = th->th_sport;		/* sport */
			PF_ACPY(&s->ext.addr, daddr, af);
			s->ext.port = th->th_dport;
			if (nat != NULL || binat != NULL) {
				PF_ACPY(&s->lan.addr, &baddr, af);
				s->lan.addr = baddr;
				s->lan.port = bport;
			} else {
				PF_ACPY(&s->lan.addr, &s->gwy.addr, af);
				s->lan.port = s->gwy.port;
			}
		} else {
			PF_ACPY(&s->lan.addr, daddr, af);
			s->lan.port = th->th_dport;
			PF_ACPY(&s->ext.addr, saddr, af);
			s->ext.port = th->th_sport;
			if (binat != NULL ||rdr != NULL) {
				PF_ACPY(&s->gwy.addr, &baddr, af);
				s->gwy.port = bport;
			} else {
				PF_ACPY(&s->gwy.addr, &s->lan.addr, af);
				s->gwy.port = s->lan.port;
			}
		}

		s->src.seqlo = ntohl(th->th_seq);
		s->src.seqhi = s->src.seqlo + len + 1;
		if (th->th_flags == TH_SYN && rm != NULL
		    && rm->keep_state == PF_STATE_MODULATE) {
			/* Generate sequence number modulator */
			while ((s->src.seqdiff = arc4random()) == 0)
				;
			pf_change_a(&th->th_seq, &th->th_sum,
			    htonl(s->src.seqlo + s->src.seqdiff), 0);
			rewrite = 1;
		} else
			s->src.seqdiff = 0;
		if (th->th_flags & TH_SYN)
			s->src.seqhi++;
		if (th->th_flags & TH_FIN)
			s->src.seqhi++;
		s->src.max_win = MAX(ntohs(th->th_win), 1);
		s->dst.seqlo = 0;	/* Haven't seen these yet */
		s->dst.seqhi = 1;
		s->dst.max_win = 1;
		s->dst.seqdiff = 0;	/* Defer random generation */
		s->src.state = TCPS_SYN_SENT;
		s->dst.state = TCPS_CLOSED;
		s->creation = pftv.tv_sec;
		s->expire = pftv.tv_sec + pftm_tcp_first_packet;
		s->packets = 1;
		s->bytes = pd->tot_len;
		pf_insert_state(s);
	}

	/* copy back packet headers if we performed NAT operations */
	if (rewrite)
		m_copyback(m, off, sizeof(*th), (caddr_t)th);

	return (PF_PASS);
}

int
pf_test_udp(int direction, struct ifnet *ifp, struct mbuf *m,
    int ipoff, int off, void *h, struct pf_pdesc *pd)
{
	struct pf_nat *nat = NULL;
	struct pf_binat *binat = NULL;
	struct pf_rdr *rdr = NULL;
	struct pf_addr *saddr = pd->src, *daddr = pd->dst, baddr;
	struct udphdr *uh = pd->hdr.udp;
	u_int16_t bport, nport = 0, af = pd->af;
	struct pf_rule *r, *rm = NULL;
	u_short reason;
	int rewrite = 0, error;

	if (direction == PF_OUT) {
		/* check outgoing packet for BINAT */
		if ((binat = pf_get_binat(PF_OUT, ifp, IPPROTO_UDP,
		    saddr, daddr, af)) != NULL) {
			PF_ACPY(&baddr, saddr, af);
			bport = uh->uh_sport;
			pf_change_ap(saddr, &uh->uh_sport, pd->ip_sum,
			    &uh->uh_sum, &binat->raddr, uh->uh_sport, 1, af);
			rewrite++;
		}
		/* check outgoing packet for NAT */
		else if ((nat = pf_get_nat(ifp, IPPROTO_UDP,
		    saddr, daddr, af)) != NULL) {
			bport = uh->uh_sport;
			error = pf_get_sport(IPPROTO_UDP, 50001,
			    65535, &nport);
			if (error)
				return (PF_DROP);
			PF_ACPY(&baddr, saddr, af);
			pf_change_ap(saddr, &uh->uh_sport, pd->ip_sum,
			    &uh->uh_sum, &nat->raddr, htons(nport), 1, af);
			rewrite++;
		}
	} else {
		/* check incoming packet for RDR */
		if ((rdr = pf_get_rdr(ifp, IPPROTO_UDP, saddr, daddr, 
		    uh->uh_dport, af)) != NULL) {
			bport = uh->uh_dport;
			if (rdr->opts & PF_RPORT_RANGE)
				nport = pf_map_port_range(rdr, uh->uh_dport);
			else
				nport = rdr->rport;

			PF_ACPY(&baddr, daddr, af);
			pf_change_ap(daddr, &uh->uh_dport, pd->ip_sum,
			    &uh->uh_sum, &rdr->raddr, nport, 1, af);
			rewrite++;
		}
		/* check incoming packet for BINAT */
		else if ((binat = pf_get_binat(PF_IN, ifp, IPPROTO_UDP,
		    daddr, daddr, af)) != NULL) {
			PF_ACPY(&baddr, daddr, af);
			bport = uh->uh_dport;
			pf_change_ap(daddr, &uh->uh_dport, pd->ip_sum,
			    &uh->uh_sum, &binat->saddr, uh->uh_dport, 1, af);
			rewrite++;
		}
	}

	r = TAILQ_FIRST(pf_rules_active);
	while (r != NULL) {
		if (r->action == PF_SCRUB) {
			r = TAILQ_NEXT(r, entries);
			continue;
		}
		r->evaluations++;

		if (r->ifp != NULL && r->ifp != ifp)
			r = r->skip[0];
		else if (r->af && r->af != af)
			r = r->skip[1];
		else if (r->proto && r->proto != IPPROTO_UDP)
			r = r->skip[2];
		else if (!PF_AZERO(&r->src.mask, af) &&
		    !PF_MATCHA(r->src.not, &r->src.addr, &r->src.mask,
			saddr, af))
			r = r->skip[3];
		else if (r->src.port_op && !pf_match_port(r->src.port_op,
                    r->src.port[0], r->src.port[1], uh->uh_sport))
                        r = r->skip[4];
		else if (!PF_AZERO(&r->dst.mask, af) &&
		    !PF_MATCHA(r->dst.not, &r->dst.addr, &r->dst.mask,
			daddr, af))
			r = r->skip[5];
		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
		    r->dst.port[0], r->dst.port[1], uh->uh_dport))
			r = r->skip[6];
		else if (r->direction != direction)
			r = TAILQ_NEXT(r, entries);
		else {
			rm = r;
			if (rm->quick)
				break;
			r = TAILQ_NEXT(r, entries);
		}
	}

	if (rm != NULL) {
		rm->packets++;
		rm->bytes += pd->tot_len;
		REASON_SET(&reason, PFRES_MATCH);

		/* XXX will log packet before rewrite */
		if (rm->log)
			PFLOG_PACKET(h, m, af, direction, reason, rm);

		if ((rm->action == PF_DROP) && rm->return_icmp) {
			/* undo NAT/RST changes, if they have taken place */
			if (nat != NULL ||
			    (binat != NULL && direction == PF_OUT)) {
				pf_change_ap(saddr, &uh->uh_sport, pd->ip_sum,
				    &uh->uh_sum, &baddr, bport, 1, af);
				rewrite++;
			} else if (rdr != NULL ||
			    (binat != NULL && direction == PF_IN)) {
				pf_change_ap(daddr, &uh->uh_dport, pd->ip_sum,
				    &uh->uh_sum, &baddr, bport, 1, af);
				rewrite++;
		
			}
			pf_send_icmp(m, rm->return_icmp >> 8,
			    rm->return_icmp & 255, af);
		}

		if (rm->action == PF_DROP) {
			if (nport && nat != NULL)
				pf_put_sport(IPPROTO_UDP, nport);
			return (PF_DROP);
		}
	}

	if ((rm != NULL && rm->keep_state) || nat != NULL || binat != NULL || rdr != NULL) {
		/* create new state */
		u_int16_t len;
		struct pf_state *s;

		len = pd->tot_len - off - sizeof(*uh);
		s = pool_get(&pf_state_pl, PR_NOWAIT);
		if (s == NULL) {
			if (nport && nat != NULL)
				pf_put_sport(IPPROTO_UDP, nport);
			return (PF_DROP);
		}

		s->rule = rm;
		s->log = rm && (rm->log & 2);
		s->proto = IPPROTO_UDP;
		s->direction = direction;
		s->af = af;
		if (direction == PF_OUT) {
			PF_ACPY(&s->gwy.addr, saddr, af);
			s->gwy.port = uh->uh_sport;
			PF_ACPY(&s->ext.addr, daddr, af);
			s->ext.port = uh->uh_dport;
			if (nat != NULL || binat != NULL) {
				PF_ACPY(&s->lan.addr, &baddr, af);
				s->lan.port = bport;
			} else {
				PF_ACPY(&s->lan.addr, &s->gwy.addr, af);
				s->lan.port = s->gwy.port;
			}
		} else {
			PF_ACPY(&s->lan.addr, daddr, af);
			s->lan.port = uh->uh_dport;
			PF_ACPY(&s->ext.addr, saddr, af);
			s->ext.port = uh->uh_sport;
			if (binat != NULL || rdr != NULL) {
				PF_ACPY(&s->gwy.addr, &baddr, af);
				s->gwy.port = bport;
			} else {
				PF_ACPY(&s->gwy.addr, &s->lan.addr, af);
				s->gwy.port = s->lan.port;
			}
		}
		s->src.seqlo  = 0;
		s->src.seqhi = 0;
		s->src.seqdiff = 0;
		s->src.max_win = 0;
		s->src.state = 1;
		s->dst.seqlo = 0;
		s->dst.seqhi = 0;
		s->dst.seqdiff = 0;
		s->dst.max_win = 0;
		s->dst.state = 0;
		s->creation = pftv.tv_sec;
		s->expire = pftv.tv_sec + pftm_udp_first_packet;
		s->packets = 1;
		s->bytes = pd->tot_len;
		pf_insert_state(s);
	}

	/* copy back packet headers if we performed NAT operations */
	if (rewrite)
		m_copyback(m, off, sizeof(*uh), (caddr_t)uh);

	return (PF_PASS);
}

int
pf_test_icmp(int direction, struct ifnet *ifp, struct mbuf *m,
    int ipoff, int off, void *h, struct pf_pdesc *pd)
{
	struct pf_nat *nat = NULL;
	struct pf_binat *binat = NULL;
	struct pf_addr *saddr = pd->src, *daddr = pd->dst, baddr;
	struct pf_rule *r, *rm = NULL;
	u_short reason;
	u_int16_t icmpid, af = pd->af;
	u_int8_t icmptype, icmpcode;

	switch (pd->proto) {
#ifdef INET
	case IPPROTO_ICMP:
		icmptype = pd->hdr.icmp->icmp_type;
		icmpcode = pd->hdr.icmp->icmp_code;
		icmpid = pd->hdr.icmp->icmp_id;
		break;
#endif /* INET */
#ifdef INET6
	case IPPROTO_ICMPV6:
		icmptype = pd->hdr.icmp6->icmp6_type;
		icmpcode = pd->hdr.icmp6->icmp6_code;
		icmpid = pd->hdr.icmp6->icmp6_id;
		break;
#endif /* INET6 */
	}

	if (direction == PF_OUT) {
		/* check outgoing packet for BINAT */
		if ((binat = pf_get_binat(PF_OUT, ifp, IPPROTO_ICMP,
		    saddr, daddr, af)) != NULL) {
			PF_ACPY(&baddr, saddr, af);
			switch (af) {
#ifdef INET
			case AF_INET:
				pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
				    binat->raddr.v4.s_addr, 0);
				break;
#endif /* INET */
#ifdef INET6
			case AF_INET6:
				pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
				    &binat->raddr, 0);
				break;
#endif /* INET6 */
			}
		}
		/* check outgoing packet for NAT */
		else if ((nat = pf_get_nat(ifp, pd->proto,
		    saddr, daddr, af)) != NULL) {
			PF_ACPY(&baddr, saddr, af);
			switch (af) {
#ifdef INET
			case AF_INET:
				pf_change_a(&saddr->v4.s_addr,
				    pd->ip_sum, nat->raddr.v4.s_addr, 0);
				break;
#endif /* INET */
#ifdef INET6
			case AF_INET6:
				pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
				    &nat->raddr, 0);
				break;
#endif /* INET6 */
			}
		}
	} else {
		/* check incoming packet for BINAT */
		if ((binat = pf_get_binat(PF_IN, ifp, IPPROTO_ICMP,
		    daddr, saddr, af)) != NULL) {
			PF_ACPY(&baddr, daddr, af);
			switch (af) {
#ifdef INET
			case AF_INET:
				pf_change_a(&daddr->v4.s_addr,
				    pd->ip_sum, binat->saddr.v4.s_addr, 0);
				break;
#endif /* INET */
#ifdef INET6
			case AF_INET6:
				pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
				    &binat->saddr, 0);
				break;
#endif /* INET6 */
			}
		}
	}

	r = TAILQ_FIRST(pf_rules_active);
	while (r != NULL) {
		if (r->action == PF_SCRUB) {
			r = TAILQ_NEXT(r, entries);
			continue;
		}
		r->evaluations++;
		if (r->ifp != NULL && r->ifp != ifp)
			r = r->skip[0];
		else if (r->af && r->af != af)
			r = r->skip[1];
		else if (r->proto && r->proto != pd->proto)
			r = r->skip[2];
		else if (!PF_AZERO(&r->src.mask, af) && !PF_MATCHA(r->src.not,
		    &r->src.addr, &r->src.mask, saddr, af))
			r = r->skip[3];
		else if (!PF_AZERO(&r->dst.mask, af) && !PF_MATCHA(r->dst.not,
		    &r->dst.addr, &r->dst.mask, daddr, af))
			r = r->skip[5];
		else if (r->direction != direction)
			r = TAILQ_NEXT(r, entries);
		else if (r->ifp != NULL && r->ifp != ifp)
			r = TAILQ_NEXT(r, entries);
		else if (r->type && r->type != icmptype + 1)
			r = TAILQ_NEXT(r, entries);
		else if (r->code && r->code != icmpcode + 1)
			r = TAILQ_NEXT(r, entries);
		else {
			rm = r;
			if (rm->quick)
				break;
			r = TAILQ_NEXT(r, entries);
		}
	}

	if (rm != NULL) {
		rm->packets++;
		rm->bytes +=  pd->tot_len;
		REASON_SET(&reason, PFRES_MATCH);

		/* XXX will log packet before rewrite */
		if (rm->log)
			PFLOG_PACKET(h, m, af, direction, reason, rm);

		if (rm->action != PF_PASS)
			return (PF_DROP);
	}

	if ((rm != NULL && rm->keep_state) || nat != NULL || binat != NULL) {
		/* create new state */
		u_int16_t len;
		struct pf_state *s;

		len = pd->tot_len - off - ICMP_MINLEN;
		s = pool_get(&pf_state_pl, PR_NOWAIT);
		if (s == NULL)
			return (PF_DROP);

		s->rule	 = rm;
		s->log	 = rm && (rm->log & 2);
		s->proto = pd->proto;
		s->direction = direction;
		s->af = af;
		if (direction == PF_OUT) {
			PF_ACPY(&s->gwy.addr, saddr, af);
			s->gwy.port = icmpid;
			PF_ACPY(&s->ext.addr, daddr, af);
			s->ext.port = icmpid;
			if (nat != NULL || binat != NULL) 
				PF_ACPY(&s->lan.addr, &baddr, af);
			else
				PF_ACPY(&s->lan.addr, &s->gwy.addr, af);
			s->lan.port = icmpid;
		} else {
			PF_ACPY(&s->lan.addr, daddr, af);
			s->lan.port = icmpid;
			PF_ACPY(&s->ext.addr, saddr, af);
			s->ext.port = icmpid;
			if (binat != NULL)
				PF_ACPY(&s->gwy.addr, &baddr, af);
			else
				PF_ACPY(&s->gwy.addr, &s->lan.addr, af);
			s->gwy.port = icmpid;
		}
		s->src.seqlo = 0;
		s->src.seqhi = 0;
		s->src.seqdiff = 0;
		s->src.max_win = 0;
		s->src.state = 0;
		s->dst.seqlo = 0;
		s->dst.seqhi = 0;
		s->dst.seqdiff = 0;
		s->dst.max_win = 0;
		s->dst.state = 0;
		s->creation = pftv.tv_sec;
		s->expire = pftv.tv_sec + pftm_icmp_first_packet;
		s->packets = 1;
		s->bytes = pd->tot_len;
		pf_insert_state(s);
	}

	return (PF_PASS);
}

int
pf_test_other(int direction, struct ifnet *ifp, struct mbuf *m,
    void *h, struct pf_pdesc *pd)
{
	struct pf_rule *r, *rm = NULL;
	struct pf_binat *binat = NULL;
	struct pf_addr *saddr = pd->src, *daddr = pd->dst;
	u_int8_t af = pd->af;

	if (direction == PF_OUT) {
		/* check outgoing packet for BINAT */
		if ((binat = pf_get_binat(PF_OUT, ifp, pd->proto,
		    saddr, daddr, af)) != NULL) {
			switch (af) {
#ifdef INET
			case AF_INET:
				pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
				    binat->raddr.v4.s_addr, 0);
				break;
#endif /* INET */
#ifdef INET6
			case AF_INET6:
				PF_ACPY(saddr, &binat->raddr, af);
				break;
#endif /* INET6 */
			}
		}
	} else {
		/* check incoming packet for BINAT */
		if ((binat = pf_get_binat(PF_IN, ifp, pd->proto,
		    daddr, saddr, af)) != NULL) {
			switch (af) {
#ifdef INET
			case AF_INET:
				pf_change_a(&daddr->v4.s_addr,
				    pd->ip_sum, binat->saddr.v4.s_addr, 0);
				break;
#endif /* INET */
#ifdef INET6
			case AF_INET6:
				PF_ACPY(daddr, &binat->saddr, af);
				break;
#endif /* INET6 */
			}
		}
	}

	r = TAILQ_FIRST(pf_rules_active);
	while (r != NULL) {
		if (r->action == PF_SCRUB) {
			r = TAILQ_NEXT(r, entries);
			continue;
		}
		r->evaluations++;
		if (r->ifp != NULL && r->ifp != ifp)
			r = r->skip[0];
		else if (r->af && r->af != af)
			r = r->skip[1];
		else if (r->proto && r->proto != pd->proto)
			r = r->skip[2];
		else if (!PF_AZERO(&r->src.mask, af) && !PF_MATCHA(r->src.not,
		    &r->src.addr, &r->src.mask, pd->src, af))
			r = r->skip[3];
		else if (!PF_AZERO(&r->dst.mask, af) && !PF_MATCHA(r->dst.not,
		    &r->dst.addr, &r->dst.mask, pd->dst, af))
			r = r->skip[5];
		else if (r->direction != direction)
			r = TAILQ_NEXT(r, entries);
		else {
			rm = r;
			if (rm->quick)
				break;
			r = TAILQ_NEXT(r, entries);
		}
	}

	if (rm != NULL) {
		u_short reason;

		rm->packets++;
		rm->bytes += pd->tot_len;
		REASON_SET(&reason, PFRES_MATCH);
		if (rm->log)
			PFLOG_PACKET(h, m, af, direction, reason, rm);

		if (rm->action != PF_PASS)
			return (PF_DROP);
	}
	return (PF_PASS);
}

int
pf_test_state_tcp(struct pf_state **state, int direction, struct ifnet *ifp,
    struct mbuf *m, int ipoff, int off, void *h, struct pf_pdesc *pd)
{
	struct pf_tree_key key;
	struct tcphdr *th = pd->hdr.tcp;
	u_int16_t win = ntohs(th->th_win);
	u_int32_t ack, end, seq;
	int ackskew;
	struct pf_state_peer *src, *dst;

	key.af	    = pd->af;
	key.proto   = IPPROTO_TCP;
	PF_ACPY(&key.addr[0], pd->src, key.af);
	PF_ACPY(&key.addr[1], pd->dst, key.af);
	key.port[0] = th->th_sport;
	key.port[1] = th->th_dport;

	if (direction == PF_IN)
		*state = pf_find_state(tree_ext_gwy, &key);
	else
		*state = pf_find_state(tree_lan_ext, &key);
	if (*state == NULL)
		return (PF_DROP);

	if (direction == (*state)->direction) {
		src = &(*state)->src;
		dst = &(*state)->dst;
	} else {
		src = &(*state)->dst;
		dst = &(*state)->src;
	}

	/*
	 * Sequence tracking algorithm from Guido van Rooij's paper:
	 *   http://www.madison-gurkha.com/publications/tcp_filtering/
	 *	tcp_filtering.ps
	 */

	seq = ntohl(th->th_seq);
	if (src->seqlo == 0) {
		/* First packet from this end.  Set its state */

		/* Deferred generation of sequence number modulator */
		if (dst->seqdiff) {
			while ((src->seqdiff = arc4random()) == 0)
				;
			ack = ntohl(th->th_ack) - dst->seqdiff;
			pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
			    src->seqdiff), 0);
			pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
		} else {
			ack = ntohl(th->th_ack);
		}

		end = seq + pd->p_len;
		if (th->th_flags & TH_SYN)
			end++;
		if (th->th_flags & TH_FIN)
			end++;

		src->seqlo = seq;
		if (src->state < TCPS_SYN_SENT)
			src->state = TCPS_SYN_SENT;

		/*
		 * May need to slide the window (seqhi may have been set by
		 * the crappy stack check or if we picked up the connection
		 * after establishment)
		 */
		if (SEQ_GEQ(end + MAX(1, dst->max_win), src->seqhi))
			src->seqhi = end + MAX(1, dst->max_win);
		if (win > src->max_win)
			src->max_win = win;

	} else {
		ack = ntohl(th->th_ack) - dst->seqdiff;
		if (src->seqdiff) {
			/* Modulate sequence numbers */
			pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
			    src->seqdiff), 0);
			pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
		}
		end = seq + pd->p_len;
		if (th->th_flags & TH_SYN)
			end++;
		if (th->th_flags & TH_FIN)
			end++;
	}

	if ((th->th_flags & TH_ACK) == 0) {
		/* Let it pass through the ack skew check */
		ack = dst->seqlo;
	} else if ((ack == 0 &&
	    (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
	    /* broken tcp stacks do not set ack */
	    (dst->state < TCPS_SYN_SENT)) {
	    /* Many stacks (ours included) will set the ACK number in an
	     * FIN|ACK if the SYN times out -- no sequence to ACK.
	     */
		ack = dst->seqlo;
	}

	if (seq == end) {
		/* Ease sequencing restrictions on no data packets */
		seq = src->seqlo;
		end = seq;
	}

	ackskew = dst->seqlo - ack;

#define MAXACKWINDOW (0xffff + 1500)	/* 1500 is an arbitrary fudge factor */
	if (SEQ_GEQ(src->seqhi, end) &&
	    /* Last octet inside other's window space */
	    SEQ_GEQ(seq, src->seqlo - dst->max_win) &&
	    /* Retrans: not more than one window back */
	    (ackskew >= -MAXACKWINDOW) &&
	    /* Acking not more than one window back */
	    (ackskew <= MAXACKWINDOW)) {
	    /* Acking not more than one window forward */

		(*state)->packets++;
		(*state)->bytes += pd->tot_len;

		/* update max window */
		if (src->max_win < win)
			src->max_win = win;
		/* syncronize sequencing */
		if (SEQ_GT(end, src->seqlo))
			src->seqlo = end;
		/* slide the window of what the other end can send */
		if (SEQ_GEQ(ack + win, dst->seqhi))
			dst->seqhi = ack + MAX(win, 1);


		/* update states */
		if (th->th_flags & TH_SYN)
			if (src->state < TCPS_SYN_SENT)
				src->state = TCPS_SYN_SENT;
		if (th->th_flags & TH_FIN)
			if (src->state < TCPS_CLOSING)
				src->state = TCPS_CLOSING;
		if (th->th_flags & TH_ACK) {
			if (dst->state == TCPS_SYN_SENT)
				dst->state = TCPS_ESTABLISHED;
			else if (dst->state == TCPS_CLOSING)
				dst->state = TCPS_FIN_WAIT_2;
		}
		if (th->th_flags & TH_RST)
			src->state = dst->state = TCPS_TIME_WAIT;

		/* update expire time */
		if (src->state >= TCPS_FIN_WAIT_2 &&
		    dst->state >= TCPS_FIN_WAIT_2)
			(*state)->expire = pftv.tv_sec + pftm_tcp_closed;
		else if (src->state >= TCPS_FIN_WAIT_2 ||
		    dst->state >= TCPS_FIN_WAIT_2)
			(*state)->expire = pftv.tv_sec + pftm_tcp_fin_wait;
		else if (src->state >= TCPS_CLOSING ||
		    dst->state >= TCPS_CLOSING)
			(*state)->expire = pftv.tv_sec + pftm_tcp_closing;
		else if (src->state < TCPS_ESTABLISHED ||
		    dst->state < TCPS_ESTABLISHED)
			(*state)->expire = pftv.tv_sec + pftm_tcp_opening;
		else
			(*state)->expire = pftv.tv_sec + pftm_tcp_established;

		/* Fall through to PASS packet */

	} else if ((dst->state < TCPS_SYN_SENT ||
		dst->state >= TCPS_FIN_WAIT_2 ||
		src->state >= TCPS_FIN_WAIT_2) &&
	    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
	    /* Within a window forward of the originating packet */
	    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
	    /* Within a window backward of the originating packet */

		/*
		 * This currently handles three situations:
		 *  1) Stupid stacks will shotgun SYNs before their peer
		 *     replies.
		 *  2) When PF catches an already established stream (the
		 *     firewall rebooted, the state table was flushed, routes
		 *     changed...)
		 *  3) Packets get funky immediately after the connection
		 *     closes (this should catch Solaris spurious ACK|FINs
		 *     that web servers like to spew after a close)
		 *
		 * This must be a little more careful than the above code
		 * since packet floods will also be caught here.  We don't
		 * update the TTL here to mitigate the damage of a packet
		 * flood and so the same code can handle awkward establishment
		 * and a loosened connection close.
		 * In the establishment case, a correct peer response will
		 * validate the connection, go through the normal state code
		 * and keep updating the state TTL.
		 */

		if (pf_status.debug >= PF_DEBUG_MISC) {
			printf("pf: loose state match: ");
			pf_print_state(*state);
			pf_print_flags(th->th_flags);
			printf(" seq=%lu ack=%lu len=%u ackskew=%d pkts=%d\n",
			    seq, ack, pd->p_len, ackskew, (*state)->packets);
		}

		(*state)->packets++;
		(*state)->bytes += pd->tot_len;

		/* update max window */
		if (src->max_win < win)
			src->max_win = win;
		/* syncronize sequencing */
		if (SEQ_GT(end, src->seqlo))
			src->seqlo = end;
		/* slide the window of what the other end can send */
		if (SEQ_GEQ(ack + win, dst->seqhi))
			dst->seqhi = ack + MAX(win, 1);

		/*
		 * Cannot set dst->seqhi here since this could be a shotgunned
		 * SYN and not an already established connection.
		 */

		if (th->th_flags & TH_FIN)
			if (src->state < TCPS_CLOSING)
				src->state = TCPS_CLOSING;
		if (th->th_flags & TH_RST)
			src->state = dst->state = TCPS_TIME_WAIT;

		/* Fall through to PASS packet */

	} else {
		if (pf_status.debug >= PF_DEBUG_MISC) {
			printf("pf: BAD state: ");
			pf_print_state(*state);
			pf_print_flags(th->th_flags);
			printf(" seq=%lu ack=%lu len=%u ackskew=%d pkts=%d "
			    "dir=%s,%s\n", seq, ack, pd->p_len, ackskew,
			    ++(*state)->packets,
			    direction == PF_IN ? "in" : "out",
			    direction == (*state)->direction ? "fwd" : "rev");
			printf("pf: State failure on: %c %c %c %c | %c %c\n",
			    SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
			    SEQ_GEQ(seq, src->seqlo - dst->max_win) ? ' ': '2',
			    (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
			    (ackskew <= MAXACKWINDOW) ? ' ' : '4',
			    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
			    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
		}
		return (PF_DROP);
	}

	/* Any packets which have gotten here are to be passed */

	/* translate source/destination address, if needed */
	if (STATE_TRANSLATE(*state)) {
		if (direction == PF_OUT)
			pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
			    &th->th_sum, &(*state)->gwy.addr,
		 	   (*state)->gwy.port, 0, pd->af);
		else
			pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
			    &th->th_sum, &(*state)->lan.addr,
			    (*state)->lan.port, 0, pd->af);
		m_copyback(m, off, sizeof(*th), (caddr_t)th);
	} else if (src->seqdiff) {
		/* Copyback sequence modulation */
		m_copyback(m, off, sizeof(*th), (caddr_t)th);
	}

	if ((*state)->rule != NULL) {
		(*state)->rule->packets++;
		(*state)->rule->bytes += pd->tot_len;
	}
	return (PF_PASS);
}

int
pf_test_state_udp(struct pf_state **state, int direction, struct ifnet *ifp,
    struct mbuf *m, int ipoff, int off, void *h, struct pf_pdesc *pd)
{
	struct pf_state_peer *src, *dst;
	struct pf_tree_key key;
	struct udphdr *uh = pd->hdr.udp;

	key.af	    = pd->af;
	key.proto   = IPPROTO_UDP;
	PF_ACPY(&key.addr[0], pd->src, key.af);
	PF_ACPY(&key.addr[1], pd->dst, key.af);
	key.port[0] = pd->hdr.udp->uh_sport;
	key.port[1] = pd->hdr.udp->uh_dport;

	if (direction == PF_IN)
		*state = pf_find_state(tree_ext_gwy, &key);
	else
		*state = pf_find_state(tree_lan_ext, &key);
	if (*state == NULL)
		return (PF_DROP);

	if (direction == (*state)->direction) {
		src = &(*state)->src;
		dst = &(*state)->dst;
	} else {
		src = &(*state)->dst;
		dst = &(*state)->src;
	}

	(*state)->packets++;
	(*state)->bytes += pd->tot_len;

	/* update states */
	if (src->state < 1)
		src->state = 1;
	if (dst->state == 1)
		dst->state = 2;

	/* update expire time */
	if (src->state == 2 && dst->state == 2)
		(*state)->expire = pftv.tv_sec + pftm_udp_multiple;
	else
		(*state)->expire = pftv.tv_sec + pftm_udp_single;

	/* translate source/destination address, if necessary */
	if (STATE_TRANSLATE(*state)) {
		if (direction == PF_OUT)
			pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
			    &uh->uh_sum, &(*state)->gwy.addr,
			    (*state)->gwy.port, 1, pd->af);
		else
			pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
			    &uh->uh_sum, &(*state)->lan.addr,
			    (*state)->lan.port, 1, pd->af);
		m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
	}

	if ((*state)->rule != NULL) {
		(*state)->rule->packets++;
		(*state)->rule->bytes += pd->tot_len;
	}
	return (PF_PASS);
}

int
pf_test_state_icmp(struct pf_state **state, int direction, struct ifnet *ifp,
    struct mbuf *m, int ipoff, int off, void *h, struct pf_pdesc *pd)
{
	struct pf_addr *saddr = pd->src, *daddr = pd->dst;
	u_int16_t icmpid, *icmpsum;
	u_int8_t icmptype;
	int state_icmp = 0;

	switch (pd->proto) {
#ifdef INET
	case IPPROTO_ICMP:
		icmptype = pd->hdr.icmp->icmp_type;
		icmpid = pd->hdr.icmp->icmp_id;
		icmpsum = &pd->hdr.icmp->icmp_cksum;

		if (icmptype == ICMP_UNREACH ||
		    icmptype == ICMP_SOURCEQUENCH ||
		    icmptype == ICMP_REDIRECT ||
		    icmptype == ICMP_TIMXCEED ||
		    icmptype == ICMP_PARAMPROB)
			state_icmp++;
		break;
#endif /* INET */
#ifdef INET6
	case IPPROTO_ICMPV6:
		icmptype = pd->hdr.icmp6->icmp6_type;
		icmpid = pd->hdr.icmp6->icmp6_id;
		icmpsum = &pd->hdr.icmp6->icmp6_cksum;

		if (icmptype == ICMP6_DST_UNREACH ||
		    icmptype == ICMP6_PACKET_TOO_BIG ||
		    icmptype == ICMP6_TIME_EXCEEDED ||
		    icmptype == ICMP6_PARAM_PROB)
			state_icmp++;
		break;
#endif /* INET6 */
	}

	if (!state_icmp) {

		/*
		 * ICMP query/reply message not related to a TCP/UDP packet.
		 * Search for an ICMP state.
		 */
		struct pf_tree_key key;

		key.af      = pd->af;
		key.proto   = pd->proto;
		PF_ACPY(&key.addr[0], saddr, key.af);
		PF_ACPY(&key.addr[1], daddr, key.af);
		key.port[0] = icmpid;
		key.port[1] = icmpid;

		if (direction == PF_IN)
			*state = pf_find_state(tree_ext_gwy, &key);
		else
			*state = pf_find_state(tree_lan_ext, &key);
		if (*state == NULL)
			return (PF_DROP);

		(*state)->packets++;
		(*state)->bytes += pd->tot_len;
		(*state)->expire = pftv.tv_sec + pftm_icmp_error_reply;

		/* translate source/destination address, if needed */
		if (PF_ANEQ(&(*state)->lan.addr, &(*state)->gwy.addr, pd->af)) {
			if (direction == PF_OUT) {
				switch (pd->af) {
#ifdef INET
				case AF_INET:
					pf_change_a(&saddr->v4.s_addr,
				    	    pd->ip_sum,
					    (*state)->gwy.addr.v4.s_addr, 0);
					break;
#endif /* INET */
#ifdef INET6
				case AF_INET6:
					pf_change_a6(saddr,
					    &pd->hdr.icmp6->icmp6_cksum,
					    &(*state)->gwy.addr, 0);
					break;
#endif /* INET6 */
				}
			} else {
				switch (pd->af) {
#ifdef INET
				case AF_INET:
					pf_change_a(&daddr->v4.s_addr,
					    pd->ip_sum,
					    (*state)->lan.addr.v4.s_addr, 0);
					break;
#endif /* INET */
#ifdef INET6
				case AF_INET6:
					pf_change_a6(daddr,
					    &pd->hdr.icmp6->icmp6_cksum,
					    &(*state)->lan.addr, 0);
					break;
#endif /* INET6 */
				}
			}
		}

		return (PF_PASS);

	} else {
		/*
		 * ICMP error message in response to a TCP/UDP packet.
		 * Extract the inner TCP/UDP header and search for that state.
		 */

		struct pf_pdesc pd2;
#ifdef INET
		struct ip h2;
#endif /* INET */
#ifdef INET6
		struct ip6_hdr h2_6;
		int terminal = 0;
#endif /* INET6 */
		int ipoff2;
		int off2;

		pd2.af = pd->af;
		switch (pd->af) {
#ifdef INET
		case AF_INET: 
			/* offset of h2 in mbuf chain */
			ipoff2 = off + ICMP_MINLEN;

			if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
			    NULL, NULL, pd2.af)) {
				DPFPRINTF(PF_DEBUG_MISC,
				    ("pf: ICMP error message too short (ip)\n"));
				return (PF_DROP);
			}
			/* ICMP error messages don't refer to non-first fragments */
			if (h2.ip_off & IP_OFFMASK)
				return (PF_DROP);

			/* offset of protocol header that follows h2 */
			off2 = ipoff2 + (h2.ip_hl << 2);

			pd2.src = (struct pf_addr *)&h2.ip_src;
			pd2.dst = (struct pf_addr *)&h2.ip_dst;
			pd2.ip_sum = &h2.ip_sum;
			break;
#endif /* INET */
#ifdef INET6
		case AF_INET6:
			ipoff2 = off + sizeof(struct icmp6_hdr); 

			if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
                            NULL, NULL, pd2.af)) {
				DPFPRINTF(PF_DEBUG_MISC,
				    ("pf: ICMP error message too short (ip6)\n"));
				return (PF_DROP);
			}
			pd2.proto = h2_6.ip6_nxt;
			pd2.src = (struct pf_addr *)&h2_6.ip6_src;
			pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
			pd2.ip_sum = NULL;
			do {			
				while (off >= m->m_len) {
					off -= m->m_len;
					m = m->m_next;
				}

				switch (pd2.proto) {
				case IPPROTO_FRAGMENT: 
					/* XXX we don't handle fagments yet */
					return (PF_DROP);
				case IPPROTO_AH:
				case IPPROTO_HOPOPTS:
				case IPPROTO_ROUTING:
				case IPPROTO_DSTOPTS: {
					/* get next header and header length */
					struct _opt6 *opt6;

					opt6 = (struct _opt6 *)(mtod(m, caddr_t) + off2);
					pd2.proto = opt6->opt6_nxt;
					off2 += (opt6->opt6_hlen + 1) * 8;
					/* goto the next header */
					break;
				}
				default:
					terminal++;
					break;
				}
			} while (!terminal);
			break;
#endif /* INET6 */
		}
			
		switch (pd2.proto) {
		case IPPROTO_TCP: {
			struct tcphdr th;
			u_int32_t seq;
			struct pf_tree_key key;
			struct pf_state_peer *src, *dst;

			/*
			 * Only the first 8 bytes of the TCP header can be
			 * expected. Don't access any TCP header fields after
			 * th_seq, an ackskew test is not possible.
			 */
			if (!pf_pull_hdr(m, off2, &th, 8, NULL, NULL, pd2.af)) {
				DPFPRINTF(PF_DEBUG_MISC,
				    ("pf: ICMP error message too short (tcp)\n"));
				return (PF_DROP);
			}

			key.af = pd2.af;
			key.proto   = IPPROTO_TCP;
			PF_ACPY(&key.addr[0], pd2.dst, pd2.af);
			key.port[0] = th.th_dport;
			PF_ACPY(&key.addr[1], pd2.src, pd2.af);
			key.port[1] = th.th_sport;

			if (direction == PF_IN)
				*state = pf_find_state(tree_ext_gwy, &key);
			else
				*state = pf_find_state(tree_lan_ext, &key);
			if (*state == NULL)
				return (PF_DROP);

			if (direction == (*state)->direction) {
				src = &(*state)->dst;
				dst = &(*state)->src;
			} else {
				src = &(*state)->src;
				dst = &(*state)->dst;
			}

			/* Demodulate sequence number */
			seq = ntohl(th.th_seq) - src->seqdiff;
			if (src->seqdiff)
				pf_change_a(&th.th_seq, &th.th_sum,
				    htonl(seq), 0);

			if (!SEQ_GEQ(src->seqhi, seq) ||
			    !SEQ_GEQ(seq, src->seqlo - dst->max_win)) {
				if (pf_status.debug >= PF_DEBUG_MISC) {
					printf("pf: BAD ICMP state: ");
					pf_print_state(*state);
					printf(" seq=%lu\n", seq);
				}
				return (PF_DROP);
			}

			if (STATE_TRANSLATE(*state)) {
				if (direction == PF_IN) {
					pf_change_icmp(pd2.src, &th.th_sport,
					    saddr, &(*state)->lan.addr,
					    (*state)->lan.port, NULL,
					    pd2.ip_sum, icmpsum,
					    pd->ip_sum, 0, pd2.af);
				} else {
					pf_change_icmp(pd2.dst, &th.th_dport,
					    saddr, &(*state)->gwy.addr,
					    (*state)->gwy.port, NULL,
					    pd2.ip_sum, icmpsum,
					    pd->ip_sum, 0, pd2.af);
				}
				switch (pd2.af) {
#ifdef INET
				case AF_INET:
					m_copyback(m, off, ICMP_MINLEN,
					    (caddr_t)pd->hdr.icmp);
					m_copyback(m, ipoff2, sizeof(h2),
					    (caddr_t)&h2);
					break;
#endif /* INET */
#ifdef INET6
				case AF_INET6:
					m_copyback(m, off, ICMP_MINLEN,
					    (caddr_t)pd->hdr.icmp6);
					m_copyback(m, ipoff2, sizeof(h2_6),
					    (caddr_t)&h2_6);
					break;
#endif /* INET6 */
				}
				m_copyback(m, off2, 8, (caddr_t)&th);
			} else if (src->seqdiff) {
				m_copyback(m, off2, 8, (caddr_t)&th);
			}

			return (PF_PASS);
			break;
		}
		case IPPROTO_UDP: {
			struct udphdr uh;
			struct pf_tree_key key;

			if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
			    NULL, NULL, pd2.af)) {
				DPFPRINTF(PF_DEBUG_MISC,
				    ("pf: ICMP error message too short (udp)\n"));
				return (PF_DROP);
			}

			key.af = pd2.af;
			key.proto   = IPPROTO_UDP;
			PF_ACPY(&key.addr[0], pd2.dst, pd2.af);
			key.port[0] = uh.uh_dport;
			PF_ACPY(&key.addr[1], pd2.src, pd2.af);
			key.port[1] = uh.uh_sport;

			if (direction == PF_IN)
				*state = pf_find_state(tree_ext_gwy, &key);
			else
				*state = pf_find_state(tree_lan_ext, &key);
			if (*state == NULL)
				return (PF_DROP);

			if (STATE_TRANSLATE(*state)) {
				if (direction == PF_IN) {
					pf_change_icmp(pd2.src, &uh.uh_sport,
					    daddr, &(*state)->lan.addr,
					    (*state)->lan.port, &uh.uh_sum,
					    pd2.ip_sum, icmpsum,
					    pd->ip_sum, 1, pd2.af);
				} else {
					pf_change_icmp(pd2.dst, &uh.uh_dport, 
					    saddr, &(*state)->gwy.addr,
					    (*state)->gwy.port, &uh.uh_sum,
					    pd2.ip_sum, icmpsum,
					    pd->ip_sum, 1, pd2.af);
				}
				switch (pd2.af) {
#ifdef INET
				case AF_INET:
					m_copyback(m, off, ICMP_MINLEN,
					    (caddr_t)pd->hdr.icmp);
					m_copyback(m, ipoff2, sizeof(h2),
					    (caddr_t)&h2);
					break;
#endif /* INET */
#ifdef INET6
				case AF_INET6:
					m_copyback(m, off, ICMP_MINLEN,
					    (caddr_t)pd->hdr.icmp6);
					m_copyback(m, ipoff2, sizeof(h2_6),
					    (caddr_t)&h2_6);
					break;
#endif /* INET6 */
				}
				m_copyback(m, off2, sizeof(uh),
				    (caddr_t)&uh);
			}

			return (PF_PASS);
			break;
		}
#ifdef INET
		case IPPROTO_ICMP: {
			struct icmp iih;
			struct pf_tree_key key;

			if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
			    NULL, NULL, pd2.af)) {
				DPFPRINTF(PF_DEBUG_MISC,
				    ("pf: ICMP error message too short (icmp)\n"));
				return (PF_DROP);
			}

			key.af = pd2.af;
			key.proto   = IPPROTO_ICMP;
			PF_ACPY(&key.addr[0], pd2.dst, pd2.af);
			key.port[0] = iih.icmp_id;
			PF_ACPY(&key.addr[1], pd2.src, pd2.af);
			key.port[1] = iih.icmp_id;

			if (direction == PF_IN)
				*state = pf_find_state(tree_ext_gwy, &key);
			else
				*state = pf_find_state(tree_lan_ext, &key);
			if (*state == NULL)
				return (PF_DROP);

			if (STATE_TRANSLATE(*state)) {
				if (direction == PF_IN) {
					pf_change_icmp(pd2.src, &iih.icmp_id,
					    daddr, &(*state)->lan.addr,
					    (*state)->lan.port, NULL,
					    pd2.ip_sum, icmpsum,
					    pd->ip_sum, 0, AF_INET);
				} else {
					pf_change_icmp(pd2.dst, &iih.icmp_id,
					    saddr, &(*state)->gwy.addr,
					    (*state)->gwy.port, NULL,
					    pd2.ip_sum, icmpsum,
					    pd->ip_sum, 0, AF_INET);
				}
				m_copyback(m, off, ICMP_MINLEN,
				    (caddr_t)pd->hdr.icmp);
				m_copyback(m, ipoff2, sizeof(h2),
				    (caddr_t)&h2);
				m_copyback(m, off2, ICMP_MINLEN,
				    (caddr_t)&iih);
			}

			return (PF_PASS);
			break;
		}
#endif /* INET */
#ifdef INET6
		case IPPROTO_ICMPV6: {
			struct icmp6_hdr iih;
			struct pf_tree_key key;

			if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
			    NULL, NULL, pd2.af)) {
				DPFPRINTF(PF_DEBUG_MISC,
				    ("pf: ICMP error message too short (icmp6)\n"));
				return (PF_DROP);
			}

			key.af = pd2.af;
			key.proto   = IPPROTO_ICMPV6;
			PF_ACPY(&key.addr[0], pd2.dst, pd2.af);
			key.port[0] = iih.icmp6_id;
			PF_ACPY(&key.addr[1], pd2.src, pd2.af);
			key.port[1] = iih.icmp6_id;

			if (direction == PF_IN)
				*state = pf_find_state(tree_ext_gwy, &key);
			else
				*state = pf_find_state(tree_lan_ext, &key);
			if (*state == NULL)
				return (PF_DROP);

			if (STATE_TRANSLATE(*state)) {
				if (direction == PF_IN) {
					pf_change_icmp(pd2.src, &iih.icmp6_id,
					    daddr, &(*state)->lan.addr,
					    (*state)->lan.port, NULL,
					    pd2.ip_sum, icmpsum,
					    pd->ip_sum, 0, AF_INET6);
				} else {
					pf_change_icmp(pd2.dst, &iih.icmp6_id,
					    saddr, &(*state)->gwy.addr,
					    (*state)->gwy.port, NULL,
					    pd2.ip_sum, icmpsum,
					    pd->ip_sum, 0, AF_INET6);
				}
				m_copyback(m, off, ICMP_MINLEN,
				    (caddr_t)pd->hdr.icmp6);
				m_copyback(m, ipoff2, sizeof(h2_6),
				    (caddr_t)&h2_6);
				m_copyback(m, off2, ICMP_MINLEN,
				    (caddr_t)&iih);
			}

			return (PF_PASS);
			break;
		}
#endif /* INET6 */
		default:
			DPFPRINTF(PF_DEBUG_MISC,
			    ("pf: ICMP error message for bad proto\n"));
			return (PF_DROP);
		}

	}
}

/*
 * ipoff and off are measured from the start of the mbuf chain.
 * h must be at "ipoff" on the mbuf chain.
 */
void *
pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
    u_short *actionp, u_short *reasonp, int af)
{
	switch (af) {
#ifdef INET
	case AF_INET: {
		struct ip *h = mtod(m, struct ip *);
		u_int16_t fragoff = (h->ip_off & IP_OFFMASK) << 3;

		if (fragoff) {
			if (fragoff >= len)
				ACTION_SET(actionp, PF_PASS);
			else {
				ACTION_SET(actionp, PF_DROP);
				REASON_SET(reasonp, PFRES_FRAG);
			}
			return (NULL);
		}
		if (m->m_pkthdr.len < off + len || h->ip_len < off + len) {
			ACTION_SET(actionp, PF_DROP);
			REASON_SET(reasonp, PFRES_SHORT);
			return (NULL);
		}
	}
#endif /* INET */
#ifdef INET6
	case AF_INET6: {
		struct ip6_hdr *h = mtod(m, struct ip6_hdr *);	
		if (m->m_pkthdr.len < off + len ||
		    (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) < off + len) {
                        ACTION_SET(actionp, PF_DROP);
                        REASON_SET(reasonp, PFRES_SHORT);
                        return (NULL);
                }
	}
#endif /* INET6 */
	}
	m_copydata(m, off, len, p);
	return (p);
}

#ifdef INET
int
pf_test(int dir, struct ifnet *ifp, struct mbuf **m0)
{
	u_short action, reason = 0, log = 0;
	struct mbuf *m = *m0;
	struct ip *h;
	struct pf_rule *r = NULL;
	struct pf_state *s = NULL;
	struct pf_pdesc pd;
	int off;

	if (!pf_status.running ||
	    (m_tag_find(m, PACKET_TAG_PF_GENERATED, NULL) != NULL))
		return (PF_PASS);

#ifdef DIAGNOSTIC
	if ((m->m_flags & M_PKTHDR) == 0)
		panic("non-M_PKTHDR is passed to pf_test");
#endif

	/* purge expire states */
	microtime(&pftv);
	if (pftv.tv_sec - pf_last_purge >= pftm_interval) {
		pf_purge_expired_states();
		pf_purge_expired_fragments();
		pf_last_purge = pftv.tv_sec;
	}

	if (m->m_pkthdr.len < sizeof(*h)) {
		action = PF_DROP;
		REASON_SET(&reason, PFRES_SHORT);
		log = 1;
		goto done;
	}

	/* We do IP header normalization and packet reassembly here */
	if (pf_normalize_ip(m0, dir, ifp, &reason) != PF_PASS) {
		ACTION_SET(&action, PF_DROP);
		goto done;
	}
	m = *m0;
	h = mtod(m, struct ip *);

	off = h->ip_hl << 2;
	if (off < sizeof(*h)) {
		action = PF_DROP;
		REASON_SET(&reason, PFRES_SHORT);
		log = 1;
		goto done;
	}

	pd.src = (struct pf_addr *)&h->ip_src;
	pd.dst = (struct pf_addr *)&h->ip_dst;
	pd.ip_sum = &h->ip_sum;
	pd.proto = h->ip_p;
	pd.af = AF_INET;
	pd.tot_len = h->ip_len;

	switch (h->ip_p) {

	case IPPROTO_TCP: {
		struct tcphdr th;
		pd.hdr.tcp = &th;

		if (!pf_pull_hdr(m, off, &th, sizeof(th),
		    &action, &reason, AF_INET)) {
			log = action != PF_PASS;
			goto done;
		}
		pd.p_len = pd.tot_len - off - (th.th_off << 2);
		action = pf_normalize_tcp(dir, ifp, m, 0, off, h, &pd);
		if (action == PF_DROP)
			break;
		action = pf_test_state_tcp(&s, dir, ifp, m, 0, off, h, &pd);
		if (action == PF_PASS) {
			r = s->rule;
			log = s->log;
		} else if (s == NULL)
			action = pf_test_tcp(dir, ifp, m, 0, off, h, &pd);
		break;
	}

	case IPPROTO_UDP: {
		struct udphdr uh;
		pd.hdr.udp = &uh;

		if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
		    &action, &reason, AF_INET)) {
			log = action != PF_PASS;
			goto done;
		}
		action = pf_test_state_udp(&s, dir, ifp, m, 0, off, h, &pd);
		if (action == PF_PASS) {
			r = s->rule;
			log = s->log;
		} else if (s == NULL)
			action = pf_test_udp(dir, ifp, m, 0, off, h, &pd);
		break;
	}

	case IPPROTO_ICMP: {
		struct icmp ih;
		pd.hdr.icmp = &ih;

		if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
		    &action, &reason, AF_INET)) {
			log = action != PF_PASS;
			goto done;
		}
		action = pf_test_state_icmp(&s, dir, ifp, m, 0, off, h, &pd);
		if (action == PF_PASS) {
			r = s->rule;
			if (r != NULL) {
				r->packets++;
				r->bytes += h->ip_len;
			}
			log = s->log;
		} else if (s == NULL)
			action = pf_test_icmp(dir, ifp, m, 0, off, h, &pd);
		break;
	}

	default:
		action = pf_test_other(dir, ifp, m, h, &pd);
		break;
	}

	if (ifp == status_ifp) {
		pf_status.bcounters[0][dir] += pd.tot_len;
		pf_status.pcounters[0][dir][action]++;
	}

done:
	if (log) {
		struct pf_rule r0;

		if (r == NULL) {
			r0.ifp = ifp;
			r0.action = action;
			r0.nr = -1;
			r = &r0;
		}
		PFLOG_PACKET(h, m, AF_INET, dir, reason, r);
	}
	return (action);
}
#endif /* INET */

#ifdef INET6
int
pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0)
{
	u_short action, reason = 0, log = 0;
	struct mbuf *m = *m0;
	struct ip6_hdr *h;
	struct pf_rule *r = NULL;
	struct pf_state *s = NULL;
	struct pf_pdesc pd;
	int off, terminal = 0;

	if (!pf_status.running ||
	    (m_tag_find(m, PACKET_TAG_PF_GENERATED, NULL) != NULL))
		return (PF_PASS);

#ifdef DIAGNOSTIC
	if ((m->m_flags & M_PKTHDR) == 0)
		panic("non-M_PKTHDR is passed to pf_test");
#endif

	/* purge expire states */
	microtime(&pftv);
	if (pftv.tv_sec - pf_last_purge >= pftm_interval) {
		pf_purge_expired_states();
		pf_purge_expired_fragments();
		pf_last_purge = pftv.tv_sec;
	}

	if (m->m_pkthdr.len < sizeof(*h)) {
		action = PF_DROP;
		REASON_SET(&reason, PFRES_SHORT);
		log = 1;
		goto done;
	}

	m = *m0;
	h = mtod(m, struct ip6_hdr *);

	pd.src = (struct pf_addr *)&h->ip6_src;
	pd.dst = (struct pf_addr *)&h->ip6_dst;
	pd.ip_sum = NULL;
	pd.af = AF_INET6;
	pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);

	off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
	pd.proto = h->ip6_nxt;
	do {			
		while (off >= m->m_len) {
			off -= m->m_len;
			m = m->m_next;
		}

		switch (pd.proto) {
		case IPPROTO_FRAGMENT: 
			/* XXX we don't handle fragments yet */
			action = PF_DROP;
			REASON_SET(&reason, PFRES_FRAG);
			goto done;
		case IPPROTO_AH:
		case IPPROTO_HOPOPTS:
		case IPPROTO_ROUTING:
		case IPPROTO_DSTOPTS: {
			/* get next header and header length */
			struct _opt6 *opt6;

			opt6 = (struct _opt6 *)(mtod(m, caddr_t) + off);
			pd.proto = opt6->opt6_nxt;
			off += (opt6->opt6_hlen + 1) * 8;
			/* goto the next header */
			break;
		}
		default:
			terminal++;
			break;
		}
	} while (!terminal);

	switch (pd.proto) {

	case IPPROTO_TCP: {
		struct tcphdr th;
		pd.hdr.tcp = &th;

		if (!pf_pull_hdr(m, off, &th, sizeof(th),
		    &action, &reason, AF_INET6)) {
			log = action != PF_PASS;
			goto done;
		}
		pd.p_len = pd.tot_len - off - (th.th_off << 2);
		action = pf_normalize_tcp(dir, ifp, m, 0, off, h, &pd);
                if (action == PF_DROP)
                        break;
		action = pf_test_state_tcp(&s, dir, ifp, m, 0, off, h, &pd);
		if (action == PF_PASS) {
			r = s->rule;
			log = s->log;
		} else if (s == NULL)
			action = pf_test_tcp(dir, ifp, m, 0, off, h, &pd);
		break;
	}

	case IPPROTO_UDP: {
		struct udphdr uh;
		pd.hdr.udp = &uh;

		if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
		    &action, &reason, AF_INET6)) {
			log = action != PF_PASS;
			goto done;
		}
		action = pf_test_state_udp(&s, dir, ifp, m, 0, off, h, &pd);
		if (action == PF_PASS) {
			r = s->rule;
			log = s->log;
		} else if (s == NULL)
			action = pf_test_udp(dir, ifp, m, 0, off, h, &pd);
		break;
	}

	case IPPROTO_ICMPV6: {
		struct icmp6_hdr ih;
		pd.hdr.icmp6 = &ih;

		if (!pf_pull_hdr(m, off, &ih, sizeof(&ih),
		    &action, &reason, AF_INET6)) {
			log = action != PF_PASS;
			goto done;
		}
		action = pf_test_state_icmp(&s, dir, ifp, m, 0, off, h, &pd);
		if (action == PF_PASS) {
			r = s->rule;
			if (r != NULL) {
				r->packets++;
				r->bytes += h->ip6_plen;
			}
			log = s->log;
		} else if (s == NULL)
			action = pf_test_icmp(dir, ifp, m, 0, off, h, &pd);
		break;
	}

	default:
		action = pf_test_other(dir, ifp, m, h, &pd);
		break;
	}

	if (ifp == status_ifp) {
		pf_status.bcounters[1][dir] += h->ip6_plen;
		pf_status.pcounters[1][dir][action]++;
	}

done:   
	if (log) {
		struct pf_rule r0;

		if (r == NULL) {
			r0.ifp = ifp;
			r0.action = action;
			r0.nr = -1;
			r = &r0;
		}
		PFLOG_PACKET(h, m, AF_INET6, dir, reason, r);
	}
	return (action);
}
#endif /* INET6 */