summaryrefslogtreecommitdiff
path: root/sys/net/pipex.c
blob: a0622ab6177a7cd48196642e060a257aab406b6e (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
/*	$OpenBSD: pipex.c,v 1.61 2014/10/28 09:45:37 yasuoka Exp $	*/

/*-
 * Copyright (c) 2009 Internet Initiative Japan Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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 AUTHOR 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 AUTHOR 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/socket.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/sysctl.h>
#include <sys/syslog.h>
#include <sys/conf.h>
#include <sys/time.h>
#include <sys/timeout.h>
#include <sys/kernel.h>
#include <sys/pool.h>

#include <net/if.h>
#include <net/if_types.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <net/if_dl.h>

#include <net/radix.h>
#include <net/route.h>
#include <net/netisr.h>
#include <net/ppp_defs.h>
#include <net/ppp-comp.h>

#include "pf.h"
#if NPF > 0
#include <net/pfvar.h>
#endif

#include "bpfilter.h"
#if NBPFILTER > 0
#include <sys/time.h>
#include <net/bpf.h>
#endif

#ifdef INET
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_var.h>
#ifdef INET6
#include <netinet/ip6.h>
#include <netinet6/ip6_var.h>
#endif
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/udp_var.h>
#endif
#include <crypto/arc4.h>

/* drop static for ddb debuggability */
#define	Static

#include <net/pipex.h>
#include "pipex_local.h"

struct pool pipex_session_pool;
struct pool mppe_key_pool;

/*
 * static/global variables
 */
int	pipex_enable = 0;
struct pipex_hash_head
    pipex_session_list,				/* master session list */
    pipex_close_wait_list,			/* expired session list */
    pipex_peer_addr_hashtable[PIPEX_HASH_SIZE],	/* peer's address hash */
    pipex_id_hashtable[PIPEX_HASH_SIZE]; 	/* peer id hash */

struct radix_node_head pipex_rd_head4;
struct radix_node_head pipex_rd_head6;
int pipex_rd_head4_initialized;
int pipex_rd_head6_initialized;
struct timeout pipex_timer_ch; 		/* callout timer context */
int pipex_prune = 1;			/* walk list every seconds */

/* pipex traffic queue */
struct ifqueue pipexinq;
struct ifqueue pipexoutq;
struct pipex_tag {
	struct pipex_session *session;
	int			proto;
};
void *pipex_softintr = NULL;
Static void pipex_softintr_handler(void *);

/* from udp_usrreq.c */
extern int udpcksum;

#ifdef PIPEX_DEBUG
int pipex_debug = 0;		/* systcl net.inet.ip.pipex_debug */
#endif

/* PPP compression == MPPE is assumed, so don't answer CCP Reset-Request. */
#define PIPEX_NO_CCP_RESETACK	1

/************************************************************************
 * Core functions
 ************************************************************************/
void
pipex_init(void)
{
	int		 i;
	extern int	 max_keylen;		/* for radix.c */

	if (pipex_softintr != NULL)
		return;

	pool_init(&pipex_session_pool, sizeof(struct pipex_session), 0, 0, 0,
	    "ppxsspl", NULL);
	pool_init(&mppe_key_pool, PIPEX_MPPE_KEYLEN * PIPEX_MPPE_NOLDKEY, 0, 0, 0,
	    "mppekeypl", NULL);

	LIST_INIT(&pipex_session_list);
	LIST_INIT(&pipex_close_wait_list);

	if (sizeof(struct sockaddr_in) > max_keylen)
		max_keylen = sizeof(struct sockaddr_in);
	for (i = 0; i < nitems(pipex_id_hashtable); i++)
		LIST_INIT(&pipex_id_hashtable[i]);
	for (i = 0; i < nitems(pipex_peer_addr_hashtable); i++)
		LIST_INIT(&pipex_peer_addr_hashtable[i]);
	/* queue and softintr init */
	IFQ_SET_MAXLEN(&pipexinq, IFQ_MAXLEN);
	IFQ_SET_MAXLEN(&pipexoutq, IFQ_MAXLEN);
	pipex_softintr =
	    softintr_establish(IPL_SOFTNET, pipex_softintr_handler, NULL);
}

void
pipex_iface_init(struct pipex_iface_context *pipex_iface, struct ifnet *ifp)
{
	int s;
	struct pipex_session *session;

	pipex_iface->pipexmode = 0;
	pipex_iface->ifnet_this = ifp;

	s = splnet();
	if (!pipex_rd_head4_initialized) {
		pipex_rd_head4_initialized++;
		if (!rn_inithead0(&pipex_rd_head4,
		    offsetof(struct sockaddr_in, sin_addr) * NBBY))
			panic("rn_inithead0() failed on pipex_init()");
	}
	if (!pipex_rd_head6_initialized) {
		pipex_rd_head6_initialized++;
		if (!rn_inithead0(&pipex_rd_head6,
		    offsetof(struct sockaddr_in6, sin6_addr) *NBBY))
			panic("rn_inithead0() failed on pipex_init()");
	}
	splx(s);

	/* virtual pipex_session entry for multicast */
	session = pool_get(&pipex_session_pool, PR_WAITOK | PR_ZERO);
	session->is_multicast = 1;
	session->pipex_iface = pipex_iface;
	pipex_iface->multicast_session = session;
}

Static void
pipex_iface_start(struct pipex_iface_context *pipex_iface)
{
	pipex_iface->pipexmode = 1;
}

Static void
pipex_iface_stop(struct pipex_iface_context *pipex_iface)
{
	struct pipex_session *session;
	struct pipex_session *session_next;

	pipex_iface->pipexmode = 0;
	/*
	 * traversal all pipex sessions.
	 * it will become heavy if the number of pppac devices bocomes large.
	 */
	for (session = LIST_FIRST(&pipex_session_list);
	    session; session = session_next) {
		session_next = LIST_NEXT(session, session_list);
		if (session->pipex_iface == pipex_iface)
			pipex_destroy_session(session);
	}
}

void
pipex_iface_fini(struct pipex_iface_context *pipex_iface)
{
	int	 s;

	s = splnet();

	pool_put(&pipex_session_pool, pipex_iface->multicast_session);
	pipex_iface_stop(pipex_iface);

	splx(s);
}

/* called from tunioctl() with splnet() */
int
pipex_ioctl(struct pipex_iface_context *pipex_iface, u_long cmd, caddr_t data)
{
	int pipexmode, ret;

	switch (cmd) {
	case PIPEXSMODE:
		pipexmode = *(int *)data;
		if (pipex_iface->pipexmode != pipexmode) {
			if (pipexmode)
				pipex_iface_start(pipex_iface);
			else
				pipex_iface_stop(pipex_iface);
		}
		break;

	case PIPEXGMODE:
		*(int *)data = pipex_iface->pipexmode;
		break;

	case PIPEXASESSION:
		ret = pipex_add_session((struct pipex_session_req *)data,
		    pipex_iface);
		return (ret);

	case PIPEXDSESSION:
		ret = pipex_close_session(
		    (struct pipex_session_close_req *)data);
		return (ret);

	case PIPEXCSESSION:
		ret = pipex_config_session(
		    (struct pipex_session_config_req *)data);
		return (ret);

	case PIPEXGSTAT:
		ret = pipex_get_stat((struct pipex_session_stat_req *)data);
		return (ret);

	case PIPEXGCLOSED:
		ret = pipex_get_closed((struct pipex_session_list_req *)data);
		return (ret);

	default:
		return (ENOTTY);

	}
	return (0);
}

/************************************************************************
 * Session management functions
 ************************************************************************/
Static int
pipex_add_session(struct pipex_session_req *req,
    struct pipex_iface_context *iface)
{
	struct pipex_session *session;
	struct pipex_hash_head *chain;
	struct radix_node *rn;
	int s;
#ifdef PIPEX_PPPOE
	struct ifnet *over_ifp = NULL;
#endif

	/* Checks requeted parameters.  */
	if (!iface->pipexmode)
		return (ENXIO);
	switch (req->pr_protocol) {
#ifdef PIPEX_PPPOE
	case PIPEX_PROTO_PPPOE:
		over_ifp = ifunit(req->pr_proto.pppoe.over_ifname);
		if (over_ifp == NULL)
			return (EINVAL);
		if (req->pr_peer_address.ss_family != AF_UNSPEC)
			return (EINVAL);
		break;
#endif
#if defined(PIPEX_L2TP) || defined(PIPEX_PPTP)
#ifdef PIPEX_PPTP
	case PIPEX_PROTO_PPTP:
#endif
#ifdef PIPEX_L2TP
	case PIPEX_PROTO_L2TP:
#endif
		switch (req->pr_peer_address.ss_family) {
		case AF_INET:
			if (req->pr_peer_address.ss_len !=
			    sizeof(struct sockaddr_in))
				return (EINVAL);
			break;
#ifdef INET6
		case AF_INET6:
			if (req->pr_peer_address.ss_len !=
			    sizeof(struct sockaddr_in6))
				return (EINVAL);
			break;
#endif
		default:
			return (EPROTONOSUPPORT);
		}
		if (req->pr_peer_address.ss_family !=
		    req->pr_local_address.ss_family ||
		    req->pr_peer_address.ss_len !=
		    req->pr_local_address.ss_len)
			return (EINVAL);
		break;
#endif
	default:
		return (EPROTONOSUPPORT);
	}

	/* prepare a new session */
	session = pool_get(&pipex_session_pool, PR_WAITOK | PR_ZERO);
	session->state = PIPEX_STATE_OPENED;
	session->protocol = req->pr_protocol;
	session->session_id = req->pr_session_id;
	session->peer_session_id = req->pr_peer_session_id;
	session->peer_mru = req->pr_peer_mru;
	session->timeout_sec = req->pr_timeout_sec;
	session->pipex_iface = iface;
	session->ppp_flags = req->pr_ppp_flags;
	session->ppp_id = req->pr_ppp_id;

	session->ip_forward = 1;

	session->ip_address.sin_family = AF_INET;
	session->ip_address.sin_len = sizeof(struct sockaddr_in);
	session->ip_address.sin_addr = req->pr_ip_address;

	session->ip_netmask.sin_family = AF_INET;
	session->ip_netmask.sin_len = sizeof(struct sockaddr_in);
	session->ip_netmask.sin_addr = req->pr_ip_netmask;

	if (session->ip_netmask.sin_addr.s_addr == 0L)
		session->ip_netmask.sin_addr.s_addr = 0xffffffffL;
	session->ip_address.sin_addr.s_addr &=
	    session->ip_netmask.sin_addr.s_addr;

	if (req->pr_peer_address.ss_len > 0)
		memcpy(&session->peer, &req->pr_peer_address,
		    MIN(req->pr_peer_address.ss_len, sizeof(session->peer)));
	if (req->pr_local_address.ss_len > 0)
		memcpy(&session->local, &req->pr_local_address,
		    MIN(req->pr_local_address.ss_len, sizeof(session->local)));
#ifdef PIPEX_PPPOE
	if (req->pr_protocol == PIPEX_PROTO_PPPOE)
		session->proto.pppoe.over_ifp = over_ifp;
#endif
#ifdef PIPEX_PPTP
	if (req->pr_protocol == PIPEX_PROTO_PPTP) {
		struct pipex_pptp_session *sess_pptp = &session->proto.pptp;

		sess_pptp->snd_gap = 0;
		sess_pptp->rcv_gap = 0;
		sess_pptp->snd_una = req->pr_proto.pptp.snd_una;
		sess_pptp->snd_nxt = req->pr_proto.pptp.snd_nxt;
		sess_pptp->rcv_nxt = req->pr_proto.pptp.rcv_nxt;
		sess_pptp->rcv_acked = req->pr_proto.pptp.rcv_acked;

		sess_pptp->winsz = req->pr_proto.pptp.winsz;
		sess_pptp->maxwinsz = req->pr_proto.pptp.maxwinsz;
		sess_pptp->peer_maxwinsz = req->pr_proto.pptp.peer_maxwinsz;
		/* last ack number */
		sess_pptp->ul_snd_una = sess_pptp->snd_una - 1;
	}
#endif
#ifdef PIPEX_L2TP
	if (req->pr_protocol == PIPEX_PROTO_L2TP) {
		struct pipex_l2tp_session *sess_l2tp = &session->proto.l2tp;

		/* session keys */
		sess_l2tp->tunnel_id = req->pr_proto.l2tp.tunnel_id;
		sess_l2tp->peer_tunnel_id = req->pr_proto.l2tp.peer_tunnel_id;

		/* protocol options */
		sess_l2tp->option_flags = req->pr_proto.l2tp.option_flags;

		/* initial state of dynamic context */
		sess_l2tp->ns_gap = sess_l2tp->nr_gap = 0;
		sess_l2tp->ns_nxt = req->pr_proto.l2tp.ns_nxt;
		sess_l2tp->nr_nxt = req->pr_proto.l2tp.nr_nxt;
		sess_l2tp->ns_una = req->pr_proto.l2tp.ns_una;
		sess_l2tp->nr_acked = req->pr_proto.l2tp.nr_acked;
		/* last ack number */
		sess_l2tp->ul_ns_una = sess_l2tp->ns_una - 1;
		sess_l2tp->ipsecflowinfo = req->pr_proto.l2tp.ipsecflowinfo;
	}
#endif
#ifdef PIPEX_MPPE
	if ((req->pr_ppp_flags & PIPEX_PPP_MPPE_ACCEPTED) != 0) {
		if (req->pr_mppe_recv.keylenbits <= 0) {
			pool_put(&pipex_session_pool, session);
			return (EINVAL);
		}
		pipex_session_init_mppe_recv(session,
		    req->pr_mppe_recv.stateless, req->pr_mppe_recv.keylenbits,
		    req->pr_mppe_recv.master_key);
	}
	if ((req->pr_ppp_flags & PIPEX_PPP_MPPE_ENABLED) != 0) {
		if (req->pr_mppe_send.keylenbits <= 0) {
			pool_put(&pipex_session_pool, session);
			return (EINVAL);
		}
		pipex_session_init_mppe_send(session,
		    req->pr_mppe_send.stateless, req->pr_mppe_send.keylenbits,
		    req->pr_mppe_send.master_key);
	}

	if (pipex_session_is_mppe_required(session)) {
		if (!pipex_session_is_mppe_enabled(session) ||
		    !pipex_session_is_mppe_accepted(session)) {
			pool_put(&pipex_session_pool, session);
			return (EINVAL);
		}
	}
#endif

	/* commit the session */
	s = splnet();
	if (!in_nullhost(session->ip_address.sin_addr)) {
		if (pipex_lookup_by_ip_address(session->ip_address.sin_addr)
		    != NULL) {
			splx(s);
			pool_put(&pipex_session_pool, session);
			return (EADDRINUSE);
		}

		rn = pipex_rd_head4.rnh_addaddr(&session->ip_address,
		    &session->ip_netmask, &pipex_rd_head4, session->ps4_rn, RTP_STATIC);
		if (rn == NULL) {
			splx(s);
			pool_put(&pipex_session_pool, session);
			return (ENOMEM);
		}
	}
	if (0) { /* NOT YET */
		rn = pipex_rd_head6.rnh_addaddr(&session->ip6_address,
		    &session->ip6_prefixlen, &pipex_rd_head6, session->ps6_rn,
		    RTP_STATIC);
		if (rn == NULL) {
			splx(s);
			pool_put(&pipex_session_pool, session);
			return (ENOMEM);
		}
	}

	chain = PIPEX_ID_HASHTABLE(session->session_id);
	LIST_INSERT_HEAD(chain, session, id_chain);
	LIST_INSERT_HEAD(&pipex_session_list, session, session_list);
	switch (req->pr_protocol) {
	case PIPEX_PROTO_PPTP:
	case PIPEX_PROTO_L2TP:
		chain = PIPEX_PEER_ADDR_HASHTABLE(
		    pipex_sockaddr_hash_key((struct sockaddr *)&session->peer));
		LIST_INSERT_HEAD(chain, session, peer_addr_chain);
	}

	/* if first session is added, start timer */
	if (LIST_NEXT(session, session_list) == NULL)
		pipex_timer_start();

	splx(s);

	pipex_session_log(session, LOG_INFO, "PIPEX is ready.");

	return (0);
}

int
pipex_notify_close_session(struct pipex_session *session)
{
	int s;

	s = splnet();
	session->state = PIPEX_STATE_CLOSE_WAIT;
	session->stat.idle_time = 0;
	LIST_INSERT_HEAD(&pipex_close_wait_list, session, state_list);
	splx(s);

	return (0);
}

int
pipex_notify_close_session_all(void)
{
	struct pipex_session *session;
	int s;

	s = splnet();
	LIST_FOREACH(session, &pipex_session_list, session_list)
		if (session->state == PIPEX_STATE_OPENED)
			pipex_notify_close_session(session);
	splx(s);

	return (0);
}

Static int
pipex_close_session(struct pipex_session_close_req *req)
{
	struct pipex_session *session;
	int s;

	s = splnet();
	session = pipex_lookup_by_session_id(req->pcr_protocol,
	    req->pcr_session_id);
	if (session == NULL) {
		splx(s);
		return (EINVAL);
	}

	/* remove from close_wait list */
	if (session->state == PIPEX_STATE_CLOSE_WAIT)
		LIST_REMOVE(session, state_list);

	/* get statistics before destroy the session */
	req->pcr_stat = session->stat;
	session->state = PIPEX_STATE_CLOSED;
	splx(s);

	return (0);
}

Static int
pipex_config_session(struct pipex_session_config_req *req)
{
	struct pipex_session *session;
	int s;

	s = splnet();
	session = pipex_lookup_by_session_id(req->pcr_protocol,
	    req->pcr_session_id);
	if (session == NULL) {
		splx(s);
		return (EINVAL);
	}
	session->ip_forward = req->pcr_ip_forward;
	splx(s);

	return (0);
}

Static int
pipex_get_stat(struct pipex_session_stat_req *req)
{
	struct pipex_session *session;
	int s;

	s = splnet();
	session = pipex_lookup_by_session_id(req->psr_protocol,
	    req->psr_session_id);
	if (session == NULL) {
		splx(s);
		return (EINVAL);
	}
	req->psr_stat = session->stat;
	splx(s);

	return (0);
}

Static int
pipex_get_closed(struct pipex_session_list_req *req)
{
	struct pipex_session *session;
	int s;

	s = splnet();
	bzero(req, sizeof(*req));
	while (!LIST_EMPTY(&pipex_close_wait_list)) {
		session = LIST_FIRST(&pipex_close_wait_list);
		req->plr_ppp_id[req->plr_ppp_id_count++] = session->ppp_id;
		LIST_REMOVE(session, state_list);
		session->state = PIPEX_STATE_CLOSE_WAIT2;
		if (req->plr_ppp_id_count >= PIPEX_MAX_LISTREQ) {
			if (!LIST_EMPTY(&pipex_close_wait_list))
				req->plr_flags |= PIPEX_LISTREQ_MORE;
			break;
		}
	}
	splx(s);

	return (0);
}

Static int
pipex_destroy_session(struct pipex_session *session)
{
	struct radix_node *rn;
	int s;

	/* remove from radix tree and hash chain */
	s = splnet();

	if (!in_nullhost(session->ip_address.sin_addr)) {
		rn = pipex_rd_head4.rnh_deladdr(&session->ip_address,
		    &session->ip_netmask, &pipex_rd_head4,
		    (struct radix_node *)session);
		KASSERT(rn != NULL);
	}

	LIST_REMOVE(session, id_chain);
	LIST_REMOVE(session, session_list);
#ifdef PIPEX_PPTP
	if (session->protocol == PIPEX_PROTO_PPTP) {
		LIST_REMOVE(session, peer_addr_chain);
	}
#endif
#ifdef PIPEX_L2TP
	if (session->protocol == PIPEX_PROTO_L2TP) {
		LIST_REMOVE(session, peer_addr_chain);
	}
#endif
	/* if final session is destroyed, stop timer */
	if (LIST_EMPTY(&pipex_session_list))
		pipex_timer_stop();

	splx(s);

	if (session->mppe_recv.old_session_keys)
		pool_put(&mppe_key_pool, session->mppe_recv.old_session_keys);
	pool_put(&pipex_session_pool, session);

	return (0);
}

Static struct pipex_session *
pipex_lookup_by_ip_address(struct in_addr addr)
{
	struct pipex_session *session;
	struct sockaddr_in pipex_in4, pipex_in4mask;

	bzero(&pipex_in4, sizeof(pipex_in4));
	pipex_in4.sin_addr = addr;
	pipex_in4.sin_family = AF_INET;
	pipex_in4.sin_len = sizeof(pipex_in4);

	bzero(&pipex_in4mask, sizeof(pipex_in4mask));
	pipex_in4mask.sin_addr.s_addr = htonl(0xFFFFFFFFL);
	pipex_in4mask.sin_family = AF_INET;
	pipex_in4mask.sin_len = sizeof(pipex_in4mask);

	session = (struct pipex_session *)pipex_rd_head4.rnh_lookup(
	    &pipex_in4, &pipex_in4mask, &pipex_rd_head4);

#ifdef PIPEX_DEBUG
	if (session == NULL) {
		char buf[INET_ADDRSTRLEN];

		PIPEX_DBG((NULL, LOG_DEBUG, "<%s> session not found (addr=%s)",
		    __func__, inet_ntop(AF_INET, &addr, buf, sizeof(buf))));
	}
#endif

	return (session);
}

Static struct pipex_session *
pipex_lookup_by_session_id(int protocol, int session_id)
{
	struct pipex_hash_head *list;
	struct pipex_session *session;

	list = PIPEX_ID_HASHTABLE(session_id);
	LIST_FOREACH(session, list, id_chain) {
		if (session->protocol == protocol &&
		    session->session_id == session_id)
			break;
	}

#ifdef PIPEX_DEBUG
	if (session == NULL)
		PIPEX_DBG((NULL, LOG_DEBUG,
		    "<%s> session not found (session_id=%d)", __func__,
		    session_id));
#endif

	return (session);
}

/***********************************************************************
 * Queue and Software Interrupt Handler
 ***********************************************************************/
Static void
pipex_softintr_handler(void *dummy)
{
	/* called at splsoftnet() */
	pipex_ppp_dequeue();
}

Static void
pipex_ppp_dequeue(void)
{
	struct mbuf *m;
	struct m_tag *mtag;
	struct pipex_tag *tag;
	int c, s;

	/* ppp output */
	for (c = 0; c < PIPEX_DEQUEUE_LIMIT; c++) {
		s = splnet();
		IF_DEQUEUE(&pipexoutq, m);
		if (m == NULL) {
			splx(s);
			break;
		}
		splx(s);

		mtag = m_tag_find(m, PACKET_TAG_PIPEX, NULL);
		if (mtag == NULL) {
			m_freem(m);
			continue;
		}
		tag = (struct pipex_tag *)(mtag + 1);
		if (tag->session->is_multicast != 0) {
			struct pipex_session *session;
			struct mbuf *m0;

			LIST_FOREACH(session, &pipex_session_list,
			    session_list) {
				if (session->pipex_iface !=
				    tag->session->pipex_iface)
					continue;
				if (session->ip_forward == 0 &&
				    session->ip6_forward == 0)
					continue;
				m0 = m_copym(m, 0, M_COPYALL, M_NOWAIT);
				if (m0 == NULL) {
					session->stat.oerrors++;
					continue;
				}
				pipex_ppp_output(m0, session, tag->proto);
			}
			m_freem(m);
		} else
			pipex_ppp_output(m, tag->session, tag->proto);
	}

	/* ppp input */
	for (c = 0; c < PIPEX_DEQUEUE_LIMIT; c++) {
		s = splnet();
		IF_DEQUEUE(&pipexinq, m);
		if (m == NULL) {
			splx(s);
			break;
		}
		splx(s);

		mtag = m_tag_find(m, PACKET_TAG_PIPEX, NULL);
		if (mtag == NULL) {
			m_freem(m);
			continue;
		}
		tag = (struct pipex_tag *)(mtag + 1);
		pipex_ppp_input(m, tag->session, 0);
	}

	/*
	 * When packet remains in queue, it is necessary
	 * to re-schedule software interrupt.
	 */
	s = splnet();
	if (!IF_IS_EMPTY(&pipexinq) || !IF_IS_EMPTY(&pipexoutq))
		softintr_schedule(pipex_softintr);
	splx(s);
}

Static int
pipex_ppp_enqueue(struct mbuf *m0, struct pipex_session *session,
    struct ifqueue *queue)
{
	struct pipex_tag *tag;
	struct m_tag *mtag;
	int s;

	s = splnet();
	if (IF_QFULL(queue)) {
		IF_DROP(queue);
		splx(s);
		goto fail;
	}
	mtag = m_tag_get(PACKET_TAG_PIPEX, sizeof(struct pipex_tag), M_NOWAIT);
	if (mtag == NULL) {
		splx(s);
		goto fail;
	}
	m_tag_prepend(m0, mtag);
	tag = (struct pipex_tag *)(mtag + 1);
	tag->session = session;
	tag->proto = PPP_IP;	/* XXX need to support other protocols */

	IF_ENQUEUE(queue, m0);
	splx(s);

	softintr_schedule(pipex_softintr);
	return (0);

fail:
	/* caller is responsible for freeing m0 */
	return (1);
}

/***********************************************************************
 * Timer functions
 ***********************************************************************/
Static void
pipex_timer_start(void)
{
	timeout_set(&pipex_timer_ch, pipex_timer, NULL);
	timeout_add_sec(&pipex_timer_ch, pipex_prune);
}

Static void
pipex_timer_stop(void)
{
	timeout_del(&pipex_timer_ch);
}

Static void
pipex_timer(void *ignored_arg)
{
	int s;
	struct pipex_session *session;
	struct pipex_session *session_next;

	s = splnet();
	timeout_add_sec(&pipex_timer_ch, pipex_prune);

	/* walk through */
	for (session = LIST_FIRST(&pipex_session_list); session;
	    session = session_next) {
		session_next = LIST_NEXT(session, session_list);
		switch (session->state) {
		case PIPEX_STATE_OPENED:
			if (session->timeout_sec == 0)
				continue;

			session->stat.idle_time++;
			if (session->stat.idle_time < session->timeout_sec)
				continue;

			pipex_notify_close_session(session);
			break;

		case PIPEX_STATE_CLOSE_WAIT:
		case PIPEX_STATE_CLOSE_WAIT2:
			/* Wait PIPEXDSESSION from userland */
			session->stat.idle_time++;
			if (session->stat.idle_time < PIPEX_CLOSE_TIMEOUT)
				continue;

			if (session->state == PIPEX_STATE_CLOSE_WAIT)
				LIST_REMOVE(session, state_list);
			session->state = PIPEX_STATE_CLOSED;
			/* FALLTHROUGH */

		case PIPEX_STATE_CLOSED:
			/*
			 * mbuf queued in pipexinq or pipexoutq may have a
			 * refererce to this session.
			 */
			if (!IF_IS_EMPTY(&pipexinq) || !IF_IS_EMPTY(&pipexoutq))
				continue;

			pipex_destroy_session(session);
			break;

		default:
			break;
		}
	}

	splx(s);
}

/***********************************************************************
 * Common network I/O functions.  (tunnel protocol independent)
 ***********************************************************************/
struct mbuf *
pipex_output(struct mbuf *m0, int af, int off,
    struct pipex_iface_context *pipex_iface)
{
	struct pipex_session *session;
	struct ip ip;
	struct pipex_tag *tag;
	struct m_tag *mtag;
	struct mbuf *mret;

	session = NULL;
	mret = NULL;
	switch (af) {
	case AF_INET:
		if (m0->m_pkthdr.len >= sizeof(struct ip) + off) {
			m_copydata(m0, off, sizeof(struct ip), (caddr_t)&ip);
			if (IN_MULTICAST(ip.ip_dst.s_addr))
				session = pipex_iface->multicast_session;
			else
				session = pipex_lookup_by_ip_address(ip.ip_dst);
		}
		if (session != NULL) {
			for (mtag = m_tag_find(m0, PACKET_TAG_PIPEX, NULL);
			    mtag != NULL;
			    mtag = m_tag_find(m0, PACKET_TAG_PIPEX, mtag)) {
				tag = (struct pipex_tag *)(mtag + 1);
				if (tag->session == session) {
					/*
					 * Don't encapsulate encapsulated
					 * packets.
					 */
					m_freem(m0);
					return (NULL);
				}
			}

			if (session == pipex_iface->multicast_session) {
				mret = m0;
				m0 = m_copym(m0, 0, M_COPYALL, M_NOWAIT);
				if (m0 == NULL) {
					m0 = mret;
					mret = NULL;
					goto drop;
				}
			}

			if (off > 0)
				m_adj(m0, off);

			pipex_ip_output(m0, session);
			return (mret);
		}
		break;
	}

	return (m0);

drop:
	if (m0 != NULL)
		m_freem(m0);
	if (session != NULL)
		session->stat.oerrors++;
	return(NULL);
}

Static void
pipex_ip_output(struct mbuf *m0, struct pipex_session *session)
{
	int is_idle;
	struct ifnet *ifp;

	/* output succeed here as a interface */
	ifp = session->pipex_iface->ifnet_this;
	ifp->if_opackets++;
	ifp->if_obytes+=m0->m_pkthdr.len;

	if (session->is_multicast == 0) {
		/*
		 * Multicast packet is a idle packet and it's not TCP.
		 */
		if (session->ip_forward == 0 && session->ip6_forward == 0)
			goto drop;
		/* reset idle timer */
		if (session->timeout_sec != 0) {
			is_idle = 0;
			m0 = ip_is_idle_packet(m0, &is_idle);
			if (m0 == NULL)
				goto drop;
			if (is_idle == 0)
				/* update expire time */
				session->stat.idle_time = 0;
		}

		/* adjust tcpmss */
		if ((session->ppp_flags & PIPEX_PPP_ADJUST_TCPMSS) != 0) {
			m0 = adjust_tcp_mss(m0, session->peer_mru);
			if (m0 == NULL)
				goto drop;
		}
	} else
		m0->m_flags &= ~(M_BCAST|M_MCAST);

	/* output ip packets to the session tunnel */
	if (pipex_ppp_enqueue(m0, session, &pipexoutq))
		goto drop;

	return;
drop:
	if (m0 != NULL)
		m_freem(m0);
	session->stat.oerrors++;
}

Static void
pipex_ppp_output(struct mbuf *m0, struct pipex_session *session, int proto)
{
	u_char *cp, hdr[16];

#ifdef PIPEX_MPPE
	if (pipex_session_is_mppe_enabled(session)) {
		if (proto == PPP_IP) {
			pipex_mppe_output(m0, session, PPP_IP);
			return;
		}
	}
#endif /* PIPEX_MPPE */
	cp = hdr;
	if (session->protocol != PIPEX_PROTO_PPPOE) {
		/* PPPoE has not address and control field */
		PUTCHAR(PPP_ALLSTATIONS, cp);
		PUTCHAR(PPP_UI, cp);
	}
	PUTSHORT(proto, cp);

	M_PREPEND(m0, cp - hdr, M_NOWAIT);
	if (m0 == NULL)
		goto drop;
	memcpy(mtod(m0, u_char *), hdr, cp - hdr);

	switch (session->protocol) {
#ifdef	PIPEX_PPPOE
	case PIPEX_PROTO_PPPOE:
		pipex_pppoe_output(m0, session);
		break;
#endif
#ifdef PIPEX_PPTP
	case PIPEX_PROTO_PPTP:
		pipex_pptp_output(m0, session, 1, 1);
		break;
#endif
#ifdef	PIPEX_L2TP
	case PIPEX_PROTO_L2TP:
		pipex_l2tp_output(m0, session);
		break;
#endif
	default:
		goto drop;
	}

	return;
drop:
	if (m0 != NULL)
		m_freem(m0);
	session->stat.oerrors++;
}

Static void
pipex_ppp_input(struct mbuf *m0, struct pipex_session *session, int decrypted)
{
	int proto, hlen = 0;
	struct m_tag *mtag;
	struct pipex_tag *tag;

	proto = pipex_ppp_proto(m0, session, 0, &hlen);
#ifdef PIPEX_MPPE
	if (proto == PPP_COMP) {
		if (decrypted)
			goto drop;

		/* checked this on ppp_common_input() already. */
		KASSERT(pipex_session_is_mppe_accepted(session));

		m_adj(m0, hlen);
		pipex_mppe_input(m0, session);
		return;
	}
	if (proto == PPP_CCP) {
		if (decrypted)
			goto drop;

#if NBPFILTER > 0
	    {
		struct ifnet *ifp = session->pipex_iface->ifnet_this;
		if (ifp->if_bpf && ifp->if_type == IFT_PPP)
			bpf_mtap(ifp->if_bpf, m0, BPF_DIRECTION_IN);
	    }
#endif
		m_adj(m0, hlen);
		pipex_ccp_input(m0, session);
		return;
	}
#endif
	/* delete mtag from decapsulated packet */
	for (mtag = m_tag_find(m0, PACKET_TAG_PIPEX, NULL); mtag;
	    mtag = m_tag_find(m0, PACKET_TAG_PIPEX, mtag)) {
		tag = (struct pipex_tag *)(mtag + 1);
		if (tag->session == session) {
			m_tag_delete(m0, mtag);
			break;
		}
	}

	switch (proto) {
	case PPP_IP:
		if (session->ip_forward == 0)
			goto drop;
		if (!decrypted && pipex_session_is_mppe_required(session))
			/*
			 * if ip packet received when mppe
			 * is required, discard it.
			 */
			goto drop;
		m_adj(m0, hlen);
		pipex_ip_input(m0, session);
		return;
#ifdef INET6
	case PPP_IPV6:
		if (session->ip6_forward == 0)
			goto drop;
		if (!decrypted && pipex_session_is_mppe_required(session))
			/*
			 * if ip packet received when mppe
			 * is required, discard it.
			 */
			goto drop;
		m_adj(m0, hlen);
		pipex_ip6_input(m0, session);
		return;
#endif
	default:
		if (decrypted)
			goto drop;
		/* protocol must be checked on pipex_common_input() already */
		KASSERT(0);
		goto drop;
	}

	return;
drop:
	if (m0 != NULL)
		m_freem(m0);
	session->stat.ierrors++;
}

Static void
pipex_ip_input(struct mbuf *m0, struct pipex_session *session)
{
	struct ifnet *ifp;
	struct ip *ip;
	int s, len;
	int is_idle;

	/* change recvif */
	m0->m_pkthdr.rcvif = session->pipex_iface->ifnet_this;
	ifp = m0->m_pkthdr.rcvif;

	PIPEX_PULLUP(m0, sizeof(struct ip));
	if (m0 == NULL)
		goto drop;

#if 0
	/*
	 * XXX: hsuenaga
	 * we need to know openbsd manners to adjust alignment
	 */
	if (!ALIGNED_POINTER(mtod(m0, caddr_t), struct ip *)) {
		/* ip_output() assumes ip packet is aligned.  */
		if ((m0 = m_copyup(m0, sizeof(struct ip),
		    ((max_linkhdr + 3) & ~3))) == NULL)
			goto drop;
	}
#endif
	if (ISSET(session->ppp_flags, PIPEX_PPP_INGRESS_FILTER)) {
		/* ingress filter */
		ip = mtod(m0, struct ip *);
		if ((ip->ip_src.s_addr & session->ip_netmask.sin_addr.s_addr) !=
		    session->ip_address.sin_addr.s_addr) {
			char src[INET_ADDRSTRLEN];

			pipex_session_log(session, LOG_DEBUG,
			    "ip packet discarded by ingress filter (src %s)",
			    inet_ntop(AF_INET, &ip->ip_src, src, sizeof(src)));
			goto drop;
		}
	}

	/* idle timer */
	if (session->timeout_sec != 0) {
		is_idle = 0;
		m0 = ip_is_idle_packet(m0, &is_idle);
		if (m0 == NULL)
			goto drop;
		if (is_idle == 0)
			/* update expire time */
			session->stat.idle_time = 0;
	}

	/* adjust tcpmss */
	if (session->ppp_flags & PIPEX_PPP_ADJUST_TCPMSS) {
		m0 = adjust_tcp_mss(m0, session->peer_mru);
		if (m0 == NULL)
			goto drop;
	}

	len = m0->m_pkthdr.len;

#if NBPFILTER > 0
	if (ifp->if_bpf)
		bpf_mtap_af(ifp->if_bpf, AF_INET, m0, BPF_DIRECTION_IN);
#endif

	s = splnet();
	if (IF_QFULL(&ipintrq)) {
		IF_DROP(&ipintrq);
		ifp->if_collisions++;
		if (!ipintrq.ifq_congestion)
			if_congestion(&ipintrq);
		splx(s);
		goto drop;
	}
	IF_ENQUEUE(&ipintrq, m0);
	schednetisr(NETISR_IP);

	ifp->if_ipackets++;
	ifp->if_ibytes += len;
	session->stat.ipackets++;
	session->stat.ibytes += len;

	splx(s);

	return;
drop:
	if (m0 != NULL)
		m_freem(m0);
	session->stat.ierrors++;
}

#ifdef INET6
Static void
pipex_ip6_input(struct mbuf *m0, struct pipex_session *session)
{
	struct ifnet *ifp;
	struct ip6_hdr *ip6;
	int s, len;

	/* change recvif */
	m0->m_pkthdr.rcvif = session->pipex_iface->ifnet_this;
	ifp = m0->m_pkthdr.rcvif;

#if 0 /* XXX: alignment */
	PIPEX_PULLUP(m0, sizeof(struct ip6_hdr));
	if (m0 == NULL)
		goto drop;

	if (!ALIGNED_POINTER(mtod(m0, caddr_t), struct ip6_hdr *)) {
		/* ip6_output() assumes ip packet is aligned.  */
		if ((m0 = m_copyup(m0, sizeof(struct ip6_hdr),
		    ((max_linkhdr + 3) & ~3))) == NULL)
			goto drop;
	}
#endif
	ip6 = mtod(m0, struct ip6_hdr *);

	/*
	 * XXX: what is reasonable ingress filter ???
	 *      only one address is enough ??
	 */

	/* XXX: we must define idle packet for IPv6(ICMPv6). */

	/*
	 * XXX: tcpmss adjustment for IPv6 is required???
	 *      We may use PMTUD in IPv6....
	 */

#if NPF > 0
	pf_pkt_addr_changed(m0);
#endif

	len = m0->m_pkthdr.len;

#if NBPFILTER > 0
	if (ifp->if_bpf)
		bpf_mtap_af(ifp->if_bpf, AF_INET6, m0, BPF_DIRECTION_IN);
#endif

	s = splnet();
	if (IF_QFULL(&ip6intrq)) {
		IF_DROP(&ip6intrq);
		ifp->if_collisions++;
		if (!ip6intrq.ifq_congestion)
			if_congestion(&ip6intrq);
		splx(s);
		goto drop;
	}
	IF_ENQUEUE(&ip6intrq, m0);
	schednetisr(NETISR_IPV6);

	ifp->if_ipackets++;
	ifp->if_ibytes += len;
	session->stat.ipackets++;
	session->stat.ibytes += len;

	splx(s);

	return;
drop:
	if (m0 != NULL)
		m_freem(m0);
	session->stat.ierrors++;
}
#endif

Static struct mbuf *
pipex_common_input(struct pipex_session *session, struct mbuf *m0, int hlen,
    int plen)
{
	int proto, ppphlen;
	u_char code;

	if (m0->m_pkthdr.len < hlen + PIPEX_PPPMINLEN)
		goto drop;

	proto = pipex_ppp_proto(m0, session, hlen, &ppphlen);
	switch (proto) {
#ifdef PIPEX_MPPE
	case PPP_CCP:
		code = 0;
		KASSERT(m0->m_pkthdr.len >= hlen + ppphlen + 1);
		m_copydata(m0, hlen + ppphlen, 1, (caddr_t)&code);
		if (code != CCP_RESETREQ && code != CCP_RESETACK)
			goto not_ours;
		break;

	case PPP_COMP:
		if (pipex_session_is_mppe_accepted(session))
			break;
		goto not_ours;
#endif
	case PPP_IP:
#ifdef INET6
	case PPP_IPV6:
#endif
		break;
	default:
		goto not_ours;
	}

	/* ok,  The packet is for PIPEX */
	m_adj(m0, hlen);/* cut off the tunnle protocol header */

	/* ensure the mbuf length equals the PPP frame length */
	if (m0->m_pkthdr.len < plen)
		goto drop;
	if (m0->m_pkthdr.len > plen) {
		if (m0->m_len == m0->m_pkthdr.len) {
			m0->m_len = plen;
			m0->m_pkthdr.len = plen;
		} else
			m_adj(m0, plen - m0->m_pkthdr.len);
	}

	/* input ppp packets to kernel session */
	if (pipex_ppp_enqueue(m0, session, &pipexinq) == 0)
		return (NULL);
drop:
	m_freem(m0);
	session->stat.ierrors++;
	return (NULL);

not_ours:
	return (m0);	/* Not to be handled by PIPEX */
}

/*
 * pipex_ppp_proto
 */
Static int
pipex_ppp_proto(struct mbuf *m0, struct pipex_session *session, int off,
    int *hlenp)
{
	int proto;
	u_char *cp, pktbuf[4];

	m_copydata(m0, off, sizeof(pktbuf), pktbuf);
	cp = pktbuf;

	if (pipex_session_has_acf(session)) {
		if (cp[0] == PPP_ALLSTATIONS && cp[1] == PPP_UI)
			cp += 2;
#ifdef PIPEX_DEBUG
		else if (!pipex_session_is_acfc_accepted(session))
			PIPEX_DBG((session, LOG_DEBUG,
			    "no acf but acfc is not accepted by the peer."));
#endif
	}
	if ((*cp & 0x01) != 0) {
		if (!pipex_session_is_pfc_accepted(session)) {
			PIPEX_DBG((session, LOG_DEBUG, "Received a broken ppp "
			    "frame.  No protocol field. %02x-%02x",
			    cp[0], cp[1]));
			return (-1);
		}
		GETCHAR(proto, cp);
	} else
		GETSHORT(proto, cp);

	if (hlenp != NULL)
		*hlenp = cp - pktbuf;

	return (proto);
}

#ifdef PIPEX_PPPOE
/***********************************************************************
 * PPPoE
 ***********************************************************************/
Static u_char	pipex_pppoe_padding[ETHERMIN];
/*
 * pipex_pppoe_lookup_session
 */
struct pipex_session *
pipex_pppoe_lookup_session(struct mbuf *m0)
{
	struct pipex_session *session;
	struct pipex_pppoe_header pppoe;

	/* short packet */
	if (m0->m_pkthdr.len < (sizeof(struct ether_header) + sizeof(pppoe)))
		return (NULL);

	m_copydata(m0, sizeof(struct ether_header),
	    sizeof(struct pipex_pppoe_header), (caddr_t)&pppoe);
	NTOHS(pppoe.session_id);
	session = pipex_lookup_by_session_id(PIPEX_PROTO_PPPOE,
	    pppoe.session_id);
#ifdef PIPEX_DEBUG
	if (session == NULL)
		PIPEX_DBG((NULL, LOG_DEBUG, "<%s> session not found (id=%d)",
		    __func__, pppoe.session_id));
#endif

	return (session);
}

struct mbuf *
pipex_pppoe_input(struct mbuf *m0, struct pipex_session *session)
{
	int hlen;
	struct pipex_pppoe_header pppoe;

	/* already checked at pipex_pppoe_lookup_session */
	KASSERT(m0->m_pkthdr.len >= (sizeof(struct ether_header) +
	    sizeof(pppoe)));

	m_copydata(m0, sizeof(struct ether_header),
	    sizeof(struct pipex_pppoe_header), (caddr_t)&pppoe);

	hlen = sizeof(struct ether_header) + sizeof(struct pipex_pppoe_header);
	if ((m0 = pipex_common_input(session, m0, hlen, ntohs(pppoe.length)))
	    == NULL)
		return (NULL);
	m_freem(m0);
	session->stat.ierrors++;
	return (NULL);
}

/*
 * pipex_ppope_output
 */
Static void
pipex_pppoe_output(struct mbuf *m0, struct pipex_session *session)
{
	struct pipex_pppoe_header *pppoe;
	struct ifnet *ifp, *over_ifp;
	int len, padlen;

	/* save length for pppoe header */
	len = m0->m_pkthdr.len;

	ifp = session->pipex_iface->ifnet_this;
	over_ifp = session->proto.pppoe.over_ifp;

	/* prepend protocol header */
	M_PREPEND(m0, sizeof(struct pipex_pppoe_header), M_NOWAIT);
	if (m0 == NULL) {
		PIPEX_DBG((NULL, LOG_ERR,
		    "<%s> cannot prepend header.", __func__));
		session->stat.oerrors++;
		return;
	}
	padlen = ETHERMIN - m0->m_pkthdr.len;
	if (padlen > 0)
		m_copyback(m0, m0->m_pkthdr.len, padlen, pipex_pppoe_padding,
		    M_NOWAIT);

	/* setup pppoe header information */
	pppoe = mtod(m0, struct pipex_pppoe_header *);
	pppoe->vertype = PIPEX_PPPOE_VERTYPE;
	pppoe->code = PIPEX_PPPOE_CODE_SESSION;
	pppoe->session_id = htons(session->session_id);
	pppoe->length = htons(len);

	m0->m_pkthdr.rcvif = ifp; 
	m0->m_flags &= ~(M_BCAST|M_MCAST);

	session->stat.opackets++;
	session->stat.obytes += len;

	over_ifp->if_output(over_ifp, m0, (struct sockaddr *)&session->peer,
	    NULL);
}
#endif /* PIPEX_PPPOE */

#ifdef PIPEX_PPTP
/***********************************************************************
 * PPTP
 ***********************************************************************/
Static void
pipex_pptp_output(struct mbuf *m0, struct pipex_session *session,
    int has_seq, int has_ack)
{
	int len, reqlen;
	struct pipex_gre_header *gre = NULL;
	struct ip *ip;
	u_char *cp;

	reqlen = PIPEX_IPGRE_HDRLEN + (has_seq + has_ack) * 4;

	len = 0;
	if (m0 != NULL) {
		/* save length for gre header */
		len = m0->m_pkthdr.len;
		/* prepend protocol header */
		M_PREPEND(m0, reqlen, M_NOWAIT);
		if (m0 == NULL)
			goto drop;
	} else {
		MGETHDR(m0, M_DONTWAIT, MT_DATA);
		if (m0 && reqlen > MHLEN) {
			MCLGET(m0, M_DONTWAIT);
			if ((m0->m_flags & M_EXT) == 0) {
				m_freem(m0);
				m0 = NULL;
			}
		}
		if (m0 == NULL)
			goto drop;
		m0->m_pkthdr.len = m0->m_len = reqlen;
	}

	/* setup ip header information */
	ip = mtod(m0, struct ip *);

	ip->ip_len = htons(m0->m_pkthdr.len);
	ip->ip_off = 0;
	ip->ip_ttl = MAXTTL;
	ip->ip_p = IPPROTO_GRE;
	ip->ip_tos = 0;

	ip->ip_src = session->local.sin4.sin_addr;
	ip->ip_dst = session->peer.sin4.sin_addr;
#if NPF > 0
	pf_pkt_addr_changed(m0);
#endif

	/* setup gre(ver1) header information */
	gre = PIPEX_SEEK_NEXTHDR(ip, sizeof(struct ip),
	    struct pipex_gre_header *);
	gre->type = htons(PIPEX_GRE_PROTO_PPP);
	gre->call_id = htons(session->peer_session_id);
	gre->flags = PIPEX_GRE_KFLAG | PIPEX_GRE_VER;	/* do htons later */
	gre->len = htons(len);

	cp = PIPEX_SEEK_NEXTHDR(gre, sizeof(struct pipex_gre_header),u_char *);
	if (has_seq) {
		gre->flags |= PIPEX_GRE_SFLAG;
		PUTLONG(session->proto.pptp.snd_nxt, cp);
		session->proto.pptp.snd_nxt++;
		session->proto.pptp.snd_gap++;
	}
	if (has_ack) {
		gre->flags |= PIPEX_GRE_AFLAG;
		session->proto.pptp.rcv_acked = session->proto.pptp.rcv_nxt - 1;
		PUTLONG(session->proto.pptp.rcv_acked, cp);
	}
	gre->flags = htons(gre->flags);

	m0->m_pkthdr.rcvif = session->pipex_iface->ifnet_this;
	if (ip_output(m0, NULL, NULL, 0, NULL, NULL, 0) != 0) {
		PIPEX_DBG((session, LOG_DEBUG, "ip_output failed."));
		goto drop;
	}
	if (len > 0) {	/* network layer only */
		/* countup statistics */
		session->stat.opackets++;
		session->stat.obytes += len;
	}

	return;
drop:
	session->stat.oerrors++;
}

struct pipex_session *
pipex_pptp_lookup_session(struct mbuf *m0)
{
	struct pipex_session *session;
	struct pipex_gre_header gre;
	struct ip ip;
	uint16_t flags;
	uint16_t id;
	int hlen;

	if (m0->m_pkthdr.len < PIPEX_IPGRE_HDRLEN) {
		PIPEX_DBG((NULL, LOG_DEBUG,
		    "<%s> packet length is too short", __func__));
		goto not_ours;
	}

	/* get ip header info */
	m_copydata(m0, 0, sizeof(struct ip), (caddr_t)&ip);
	hlen = ip.ip_hl << 2;

	/*
	 * m0 has already passed ip_input(), so there is
	 * no necessity for ip packet inspection.
	 */

	/* get gre flags */
	m_copydata(m0, hlen, sizeof(gre), (caddr_t)&gre);
	flags = ntohs(gre.flags);

	/* gre version must be '1' */
	if ((flags & PIPEX_GRE_VERMASK) != PIPEX_GRE_VER) {
		PIPEX_DBG((NULL, LOG_DEBUG,
		    "<%s> gre header wrong version.", __func__));
		goto not_ours;
	}

	/* gre keys must be present */
	if ((flags & PIPEX_GRE_KFLAG) == 0) {
		PIPEX_DBG((NULL, LOG_DEBUG,
		    "<%s> gre header has no keys.", __func__));
		goto not_ours;
	}

	/* lookup pipex session table */
	id = ntohs(gre.call_id);
	session = pipex_lookup_by_session_id(PIPEX_PROTO_PPTP, id);
#ifdef PIPEX_DEBUG
	if (session == NULL) {
		PIPEX_DBG((NULL, LOG_DEBUG,
		    "<%s> session not found (id=%d)", __func__, id));
		goto not_ours;
	}
#endif

	return (session);

not_ours:
	return (NULL);
}

struct mbuf *
pipex_pptp_input(struct mbuf *m0, struct pipex_session *session)
{
	int hlen, has_seq, has_ack, nseq;
	const char *reason = "";
	u_char *cp, *seqp = NULL, *ackp = NULL;
	uint32_t flags, seq = 0, ack = 0;
	struct ip *ip;
	struct pipex_gre_header *gre;
	struct pipex_pptp_session *pptp_session;
	int rewind = 0;

	KASSERT(m0->m_pkthdr.len >= PIPEX_IPGRE_HDRLEN);
	pptp_session = &session->proto.pptp;

	/* get ip header */
	ip = mtod(m0, struct ip *);
	hlen = ip->ip_hl << 2;

	/* seek gre header */
	gre = PIPEX_SEEK_NEXTHDR(ip, hlen, struct pipex_gre_header *);
	flags = ntohs(gre->flags);

	/* pullup for seek sequences in header */
	has_seq = (flags & PIPEX_GRE_SFLAG) ? 1 : 0;
	has_ack = (flags & PIPEX_GRE_AFLAG) ? 1 : 0;
	hlen = PIPEX_IPGRE_HDRLEN + 4 * (has_seq + has_ack);
	if (m0->m_len < hlen) {
		m0 = m_pullup(m0, hlen);
		if (m0 == NULL) {
			PIPEX_DBG((session, LOG_DEBUG, "pullup failed."));
			goto drop;
		}
	}

	/* check sequence */
	cp = PIPEX_SEEK_NEXTHDR(gre, sizeof(struct pipex_gre_header),u_char *);
	if (has_seq) {
		seqp = cp;
		GETLONG(seq, cp);
	}
	if (has_ack) {
		ackp = cp;
		GETLONG(ack, cp);
		if (ack + 1 == pptp_session->snd_una) {
			/* ack has not changed before */
		} else if (SEQ32_LT(ack, pptp_session->snd_una)) {
			/* OoO ack packets should not be dropped. */
			rewind = 1;
		} else if (SEQ32_GT(ack, pptp_session->snd_nxt)) {
			reason = "ack for unknown sequence";
			goto out_seq;
		} else
			pptp_session->snd_una = ack + 1;
	}
	if (!has_seq) {
		/* ack only packet */
		goto not_ours;
	}
	if (SEQ32_LT(seq, pptp_session->rcv_nxt)) {
		rewind = 1;
		if (SEQ32_LT(seq,
		    pptp_session->rcv_nxt - PIPEX_REWIND_LIMIT)) {
			reason = "out of sequence";
			goto out_seq;
		}
	} else if (SEQ32_GE(seq, pptp_session->rcv_nxt +
	    pptp_session->maxwinsz)) {
		pipex_session_log(session, LOG_DEBUG,
		    "received packet caused window overflow. seq=%u(%u-%u)"
		    "may lost %d packets.", seq, pptp_session->rcv_nxt,
		    pptp_session->rcv_nxt + pptp_session->maxwinsz,
		    (int)SEQ32_SUB(seq, pptp_session->rcv_nxt));
	}

	seq++;
	nseq = SEQ32_SUB(seq, pptp_session->rcv_nxt);
	if (!rewind) {
		pptp_session->rcv_nxt = seq;
		if (SEQ32_SUB(seq, pptp_session->rcv_acked) >
		    roundup(pptp_session->winsz, 2) / 2) /* Send ack only packet. */
			pipex_pptp_output(NULL, session, 0, 1);
	}

	if ((m0 = pipex_common_input(session, m0, hlen, (int)ntohs(gre->len)))
	    == NULL) {
		/* ok,  The packet is for PIPEX */
		if (!rewind)
			session->proto.pptp.rcv_gap += nseq;
		return (NULL);
	}

	if (rewind)
		goto out_seq;

not_ours:
	seq--;	/* revert original seq value */

	/*
	 * overwrite sequence numbers to adjust a gap between pipex and
	 * userland.
	 */
	if (seqp != NULL) {
		seq -= pptp_session->rcv_gap;
		PUTLONG(seq, seqp);
	}
	if (ackp != NULL) {
		if (pptp_session->snd_nxt == pptp_session->snd_una) {
			ack -= session->proto.pptp.snd_gap;
			pptp_session->ul_snd_una = ack;
		} else {
			/*
			 * There are sending packets they are not acked.
			 * In this situation, (ack - snd_gap) may points
			 * before sending window of userland.  So we don't
			 * update the ack number.
			 */
			ack = pptp_session->ul_snd_una;
		}
		PUTLONG(ack, ackp);
	}

	return (m0);
out_seq:
	pipex_session_log(session, LOG_DEBUG,
	    "Received bad data packet: %s: seq=%u(%u-%u) ack=%u(%u-%u)",
	    reason, seq, pptp_session->rcv_nxt,
	    pptp_session->rcv_nxt + pptp_session->maxwinsz,
	    ack, pptp_session->snd_una,
	    pptp_session->snd_nxt);

	/* FALLTHROUGH */
drop:
	if (m0 != NULL)
		m_freem(m0);
	session->stat.ierrors++;

	return (NULL);
}

struct pipex_session *
pipex_pptp_userland_lookup_session_ipv4(struct mbuf *m0, struct in_addr dst)
{
	struct sockaddr_in sin4;

	sin4.sin_family = AF_INET;
	sin4.sin_addr = dst;

	return pipex_pptp_userland_lookup_session(m0, (struct sockaddr *)&sin4);
}

#ifdef INET6
struct pipex_session *
pipex_pptp_userland_lookup_session_ipv6(struct mbuf *m0, struct in6_addr dst)
{
	struct sockaddr_in6 sin6;

	sin6.sin6_family = AF_INET6;
	in6_recoverscope(&sin6, &dst, NULL);

	return pipex_pptp_userland_lookup_session(m0, (struct sockaddr *)&sin6);
}
#endif

Static struct pipex_session *
pipex_pptp_userland_lookup_session(struct mbuf *m0, struct sockaddr *sa)
{
	struct pipex_gre_header gre;
	struct pipex_hash_head *list;
	struct pipex_session *session;
	uint16_t id, flags;

	/* pullup */
	if (m0->m_pkthdr.len < sizeof(gre)) {
		PIPEX_DBG((NULL, LOG_DEBUG,
		    "<%s> packet length is too short", __func__));
		return (NULL);
	}

	/* get flags */
	m_copydata(m0, 0, sizeof(struct pipex_gre_header), (caddr_t)&gre);
	flags = ntohs(gre.flags);

	/* gre version must be '1' */
	if ((flags & PIPEX_GRE_VERMASK) != PIPEX_GRE_VER) {
		PIPEX_DBG((NULL, LOG_DEBUG,
		    "<%s> gre header wrong version.", __func__));
		return (NULL);
	}

	/* gre keys must be present */
	if ((flags & PIPEX_GRE_KFLAG) == 0) {
		PIPEX_DBG((NULL, LOG_DEBUG,
		    "<%s> gre header has no keys.", __func__));
		return (NULL);
	}

	/* lookup pipex session table */
	id = ntohs(gre.call_id);

	list = PIPEX_PEER_ADDR_HASHTABLE(pipex_sockaddr_hash_key(sa));
	LIST_FOREACH(session, list, peer_addr_chain) {
		if (pipex_sockaddr_compar_addr(
		    (struct sockaddr *)&session->peer, sa) != 0)
			continue;
		if (session->peer_session_id == id)
			break;
	}
#ifdef PIPEX_DEBUG
	if (session == NULL) {
		PIPEX_DBG((NULL, LOG_DEBUG,
		    "<%s> session not found (,call_id=%d)",
		    __func__, (int)gre.call_id));
	}
#endif
	return (session);
}

/*
 * pipex_pptp_userland_output
 */
struct mbuf *
pipex_pptp_userland_output(struct mbuf *m0, struct pipex_session *session)
{
	int len;
	struct pipex_gre_header *gre, gre0;
	uint16_t flags;
	u_char *cp, *cp0;
	uint32_t val32;

	len = sizeof(struct pipex_gre_header);
	m_copydata(m0, 0, len, (caddr_t)&gre0);
	gre = &gre0;
	flags = ntohs(gre->flags);
	if ((flags & PIPEX_GRE_SFLAG) != 0)
		len += 4;
	if ((flags & PIPEX_GRE_AFLAG) != 0)
		len += 4;

	/* check length */
	PIPEX_PULLUP(m0, len);
	if (m0 == NULL) {
		PIPEX_DBG((session, LOG_DEBUG, "gre header is too short."));
		return (NULL);
	}

	gre = mtod(m0, struct pipex_gre_header *);
	cp = PIPEX_SEEK_NEXTHDR(gre, sizeof(struct pipex_gre_header), u_char *);

	/*
	 * overwrite sequence numbers to adjust a gap between pipex and
	 * userland.
	 */
	if ((flags & PIPEX_GRE_SFLAG) != 0) {
		cp0 = cp;
		GETLONG(val32, cp);
		val32 += session->proto.pptp.snd_gap;
		PUTLONG(val32, cp0);
		session->proto.pptp.snd_nxt++;
	}
	if ((flags & PIPEX_GRE_AFLAG) != 0) {
		cp0 = cp;
		GETLONG(val32, cp);
		val32 += session->proto.pptp.rcv_gap;
		PUTLONG(val32, cp0);
		if (SEQ32_GT(val32, session->proto.pptp.rcv_acked))
			session->proto.pptp.rcv_acked = val32;
	}

	return (m0);
}
#endif /* PIPEX_PPTP */

#ifdef PIPEX_L2TP
/***********************************************************************
 * L2TP support
 ***********************************************************************/
Static void
pipex_l2tp_output(struct mbuf *m0, struct pipex_session *session)
{
	int hlen, plen, datalen;
	struct pipex_l2tp_header *l2tp = NULL;
	struct pipex_l2tp_seq_header *seq = NULL;
	struct udphdr *udp;
	struct ip *ip;
#ifdef INET6
	struct ip6_hdr *ip6;
#endif

	hlen = sizeof(struct pipex_l2tp_header) +
	    ((pipex_session_is_l2tp_data_sequencing_on(session))
		    ? sizeof(struct pipex_l2tp_seq_header) : 0) +
	    sizeof(struct udphdr) +
#ifdef INET6
	    ((session->peer.sin6.sin6_family == AF_INET6)
		    ? sizeof(struct ip6_hdr) : sizeof(struct ip));
#else
	    sizeof(struct ip);
#endif

	datalen = 0;
	if (m0 != NULL) {
		datalen = m0->m_pkthdr.len;
		M_PREPEND(m0, hlen, M_NOWAIT);
		if (m0 == NULL)
			goto drop;
	} else {
		MGETHDR(m0, M_DONTWAIT, MT_DATA);
		if (m0 == NULL)
			goto drop;
		KASSERT(hlen <= MHLEN);
		m0->m_pkthdr.len = m0->m_len = hlen;
	}

#ifdef INET6
	hlen = (session->peer.sin6.sin6_family == AF_INET6)
	    ? sizeof(struct ip6_hdr) : sizeof(struct ip);
#else
	hlen = sizeof(struct ip);
#endif
	plen = datalen + sizeof(struct pipex_l2tp_header) +
	    ((pipex_session_is_l2tp_data_sequencing_on(session))
		    ? sizeof(struct pipex_l2tp_seq_header) : 0);

	l2tp = (struct pipex_l2tp_header *)
	    (mtod(m0, caddr_t) + hlen + sizeof(struct udphdr));
	l2tp->flagsver = PIPEX_L2TP_VER | PIPEX_L2TP_FLAG_LENGTH;
	l2tp->length = htons(plen);
	l2tp->tunnel_id = htons(session->proto.l2tp.peer_tunnel_id);
	l2tp->session_id = htons(session->peer_session_id);
	if (pipex_session_is_l2tp_data_sequencing_on(session)) {
		seq = (struct pipex_l2tp_seq_header *)(l2tp + 1);
		l2tp->flagsver |= PIPEX_L2TP_FLAG_SEQUENCE;
		seq->ns = htons(session->proto.l2tp.ns_nxt);
		session->proto.l2tp.ns_nxt++;
		session->proto.l2tp.ns_gap++;
		session->proto.l2tp.nr_acked = session->proto.l2tp.nr_nxt - 1;
		seq->nr = htons(session->proto.l2tp.nr_acked);
	}
	HTONS(l2tp->flagsver);

	plen += sizeof(struct udphdr);
	udp = (struct udphdr *)(mtod(m0, caddr_t) + hlen);
	udp->uh_sport = session->local.sin6.sin6_port;
	udp->uh_dport = session->peer.sin6.sin6_port;
	udp->uh_ulen = htons(plen);
	udp->uh_sum = 0;

	m0->m_pkthdr.csum_flags |= M_UDP_CSUM_OUT;
	m0->m_pkthdr.rcvif = session->pipex_iface->ifnet_this;
#if NPF > 0
	pf_pkt_addr_changed(m0);
#endif
	switch (session->peer.sin6.sin6_family) {
	case AF_INET:
		ip = mtod(m0, struct ip *);
		ip->ip_p = IPPROTO_UDP;
		ip->ip_src = session->local.sin4.sin_addr;
		ip->ip_dst = session->peer.sin4.sin_addr;
		ip->ip_len = htons(hlen + plen);
		ip->ip_ttl = MAXTTL;
		ip->ip_tos = 0;
		ip->ip_off = 0;

		if (ip_output(m0, NULL, NULL, 0, NULL, NULL,
		    session->proto.l2tp.ipsecflowinfo) != 0) {
			PIPEX_DBG((session, LOG_DEBUG, "ip_output failed."));
			goto drop;
		}
		break;
#ifdef INET6
	case AF_INET6:
		ip6 = mtod(m0, struct ip6_hdr *);

		ip6->ip6_flow = 0;
		ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
		ip6->ip6_vfc |= IPV6_VERSION;
		ip6->ip6_nxt = IPPROTO_UDP;
		ip6->ip6_src = session->local.sin6.sin6_addr;
		(void)in6_embedscope(&ip6->ip6_dst,
		    &session->peer.sin6, NULL, NULL);
		/* ip6->ip6_plen will be filled in ip6_output. */

		if (ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL) != 0) {
			PIPEX_DBG((session, LOG_DEBUG, "ip6_output failed."));
			goto drop;
		}
		break;
#endif
	}
	udpstat.udps_opackets++;

	if (datalen > 0) {	/* network layer only */
		/* countup statistics */
		session->stat.opackets++;
		session->stat.obytes += datalen;
	}

	return;
drop:
	session->stat.oerrors++;
}

struct pipex_session *
pipex_l2tp_lookup_session(struct mbuf *m0, int off)
{
	struct pipex_session *session;
	uint16_t flags, session_id, ver;
	u_char *cp, buf[PIPEX_L2TP_MINLEN];

	if (m0->m_pkthdr.len < off + PIPEX_L2TP_MINLEN) {
		PIPEX_DBG((NULL, LOG_DEBUG,
		    "<%s> packet length is too short", __func__));
		goto not_ours;
	}

	/* get first 16bits of L2TP */
	m_copydata(m0, off, sizeof(buf), buf);
	cp = buf;
	GETSHORT(flags, cp);
	ver = flags & PIPEX_L2TP_VER_MASK;

	/* l2tp version must be '2' */
	if (ver != PIPEX_L2TP_VER) {
		PIPEX_DBG((NULL, LOG_DEBUG,
		    "<%s> l2tp header wrong version %u.", __func__, ver));
		goto not_ours;
	}
	if ((flags & PIPEX_L2TP_FLAG_TYPE) != 0)
		goto not_ours;

	if (flags & PIPEX_L2TP_FLAG_LENGTH)
		cp += 2;			/* skip length field */
	cp += 2;				/* skip tunnel-id field */
	GETSHORT(session_id, cp);		/* get session-id field */

	/* lookup pipex session table */
	session = pipex_lookup_by_session_id(PIPEX_PROTO_L2TP, session_id);
#ifdef PIPEX_DEBUG
	if (session == NULL) {
		PIPEX_DBG((NULL, LOG_DEBUG,
		    "<%s> session not found (id=%d)", __func__, session_id));
		goto not_ours;
	}
#endif

	return (session);

not_ours:
	return (NULL);
}

struct mbuf *
pipex_l2tp_input(struct mbuf *m0, int off0, struct pipex_session *session,
    uint32_t ipsecflowinfo)
{
	struct pipex_l2tp_session *l2tp_session;
	int length, offset, hlen, nseq;
	u_char *cp, *nsp, *nrp;
	uint16_t flags, ns = 0, nr = 0;
	int rewind = 0;

	length = offset = ns = nr = 0;
	l2tp_session = &session->proto.l2tp;
	l2tp_session->ipsecflowinfo = ipsecflowinfo;
	nsp = nrp = NULL;

	m_copydata(m0, off0, sizeof(flags), (caddr_t)&flags);

	flags = ntohs(flags) & PIPEX_L2TP_FLAG_MASK;
	KASSERT((flags & PIPEX_L2TP_FLAG_TYPE) == 0);

	hlen = 2;				/* flags and version fields */
	if (flags & PIPEX_L2TP_FLAG_LENGTH)	/* length */
		hlen += 2;
	hlen += 4;				/* tunnel-id and session-id */
	if (flags & PIPEX_L2TP_FLAG_SEQUENCE)	/* ns and nr */
		hlen += 4;
	if (flags & PIPEX_L2TP_FLAG_OFFSET)	/* offset */
		hlen += 2;

	PIPEX_PULLUP(m0, off0 + hlen);
	if (m0  == NULL)
		goto drop;

	cp = mtod(m0, u_char *) + off0;
	cp += 2;	/* flags and version */
	if (flags & PIPEX_L2TP_FLAG_LENGTH)
		GETSHORT(length, cp);
	else
		length = m0->m_pkthdr.len - off0;
	cp += 4;	/* skip tunnel-id and session-id field */

	/* pullup for seek sequences in header */
	nseq = 0;
	if (flags & PIPEX_L2TP_FLAG_SEQUENCE) {
		nsp = cp;
		GETSHORT(ns, cp);
		nrp = cp;
		GETSHORT(nr, cp);

		nr++;
		if (SEQ16_GT(nr, l2tp_session->ns_una) &&
		    SEQ16_LE(nr, l2tp_session->ns_nxt))
			/* update 'ns_una' only if the ns is in valid range */
			l2tp_session->ns_una = nr;
		if (SEQ16_LT(ns, l2tp_session->nr_nxt)) {
			rewind = 1;
			if (SEQ16_LT(ns,
			    l2tp_session->nr_nxt - PIPEX_REWIND_LIMIT))
				goto out_seq;
		}

		ns++;
		nseq = SEQ16_SUB(ns, l2tp_session->nr_nxt);
		if (!rewind)
			l2tp_session->nr_nxt = ns;
	}
	if (flags & PIPEX_L2TP_FLAG_OFFSET)
		GETSHORT(offset, cp);

	length -= hlen + offset;
	hlen += off0 + offset;
	if ((m0 = pipex_common_input(session, m0, hlen, length)) == NULL) {
		/* ok,  The packet is for PIPEX */
		if (!rewind)
			session->proto.l2tp.nr_gap += nseq;
		return (NULL);
	}

	if (rewind)
		goto out_seq;

	/*
	 * overwrite sequence numbers to adjust a gap between pipex and
	 * userland.
	 */
	if (flags & PIPEX_L2TP_FLAG_SEQUENCE) {
		--ns; --nr;	/* revert original values */
		ns -= l2tp_session->nr_gap;
		PUTSHORT(ns, nsp);

		if (l2tp_session->ns_nxt == l2tp_session->ns_una) {
			nr -= l2tp_session->ns_gap;
			l2tp_session->ul_ns_una = nr;
		} else {
			/*
			 * There are sending packets they are not acked.
			 * In this situation, (ack - snd_gap) may points
			 * before sending window of userland.  So we don't
			 * update the ack number.
			 */
			nr = l2tp_session->ul_ns_una;
		}
		PUTSHORT(nr, nrp);
	}

	return (m0);
out_seq:
	pipex_session_log(session, LOG_DEBUG,
	    "Received bad data packet: out of sequence: seq=%u(%u-) "
	    "ack=%u(%u-%u)", ns, l2tp_session->nr_nxt, nr, l2tp_session->ns_una,
	    l2tp_session->ns_nxt);

	/* FALLTHROUGH */
drop:
	if (m0 != NULL)
		m_freem(m0);
	session->stat.ierrors++;

	return (NULL);
}

struct pipex_session *
pipex_l2tp_userland_lookup_session_ipv4(struct mbuf *m0, struct in_addr dst)
{
	struct sockaddr_in sin4;

	sin4.sin_family = AF_INET;
	sin4.sin_addr = dst;

	return pipex_l2tp_userland_lookup_session(m0, (struct sockaddr *)&sin4);
}

#ifdef INET6
struct pipex_session *
pipex_l2tp_userland_lookup_session_ipv6(struct mbuf *m0, struct in6_addr dst)
{
	struct sockaddr_in6 sin6;

	sin6.sin6_family = AF_INET6;
	in6_recoverscope(&sin6, &dst, NULL);

	return pipex_l2tp_userland_lookup_session(m0, (struct sockaddr *)&sin6);
}
#endif

struct pipex_session *
pipex_l2tp_userland_lookup_session(struct mbuf *m0, struct sockaddr *sa)
{
	struct pipex_l2tp_header l2tp;
	struct pipex_hash_head *list;
	struct pipex_session *session;
	uint16_t session_id, tunnel_id, flags;

	if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
		return (NULL);

	/* pullup */
	if (m0->m_pkthdr.len < sizeof(l2tp)) {
		PIPEX_DBG((NULL, LOG_DEBUG,
		    "<%s> packet length is too short", __func__));
		return (NULL);
	}

	/* get flags */
	m_copydata(m0, 0, sizeof(l2tp), (caddr_t)&l2tp);
	flags = ntohs(l2tp.flagsver);

	/* l2tp version must be '2' */
	if ((flags & PIPEX_L2TP_VER_MASK) != PIPEX_L2TP_VER) {
		PIPEX_DBG((NULL, LOG_DEBUG,
		    "<%s> l2tp header wrong version.", __func__));
		return (NULL);
	}
	/* We need L2TP data messages only */
	if ((flags & PIPEX_L2TP_FLAG_TYPE) != 0)
		return (NULL);
	/* No need to hook packets that don't have the sequence field */
	if ((flags & PIPEX_L2TP_FLAG_SEQUENCE) == 0)
		return (NULL);

	session_id = ntohs(l2tp.session_id);
	tunnel_id = ntohs(l2tp.tunnel_id);

	list = PIPEX_PEER_ADDR_HASHTABLE(pipex_sockaddr_hash_key(sa));
	LIST_FOREACH(session, list, peer_addr_chain) {
		if (pipex_sockaddr_compar_addr(
		    (struct sockaddr *)&session->peer, sa) != 0)
			continue;
		if (session->proto.l2tp.peer_tunnel_id != tunnel_id)
			continue;
		if (session->peer_session_id == session_id)
			break;
	}
#ifdef PIPEX_DEBUG
	if (session == NULL) {
		PIPEX_DBG((NULL, LOG_DEBUG, "<%s> session not found "
		    "(tunnel_id=%d, session_id=%d)", __func__,
		    tunnel_id, session_id));
	}
#endif

	return (session);
}

struct mbuf *
pipex_l2tp_userland_output(struct mbuf *m0, struct pipex_session *session)
{
	struct pipex_l2tp_header *l2tp;
	struct pipex_l2tp_seq_header *seq;
	uint16_t ns, nr;

	/* check length */
	PIPEX_PULLUP(m0, sizeof(struct pipex_l2tp_header) +
	    sizeof(struct pipex_l2tp_seq_header));
	if (m0 == NULL)
		return (NULL);

	l2tp = mtod(m0, struct pipex_l2tp_header *);
	KASSERT(ntohs(l2tp->flagsver) & PIPEX_L2TP_FLAG_SEQUENCE);

	/*
	 * overwrite sequence numbers to adjust a gap between pipex and
	 * userland.
	 */
		seq = (struct pipex_l2tp_seq_header *)(l2tp + 1);
		ns = ntohs(seq->ns);
		nr = ntohs(seq->nr);

		ns += session->proto.l2tp.ns_gap;
		seq->ns = htons(ns);
		session->proto.l2tp.ns_nxt++;

		nr += session->proto.l2tp.nr_gap;
		seq->nr = htons(nr);
		if (SEQ16_GT(nr, session->proto.l2tp.nr_acked))
			session->proto.l2tp.nr_acked = nr;

	return (m0);
}
#endif /* PIPEX_L2TP */

#ifdef PIPEX_MPPE
/**********************************************************************
 * MPPE
 ***********************************************************************/
#define	PIPEX_COHERENCY_CNT_MASK		0x0fff
Static void
pipex_mppe_init(struct pipex_mppe *mppe, int stateless, int keylenbits,
    u_char *master_key, int has_oldkey)
{
	memset(mppe, 0, sizeof(struct pipex_mppe));
	if (stateless)
		mppe->stateless = 1;
	if (has_oldkey)
		mppe->old_session_keys =
		    pool_get(&mppe_key_pool, PR_WAITOK);
	else
		mppe->old_session_keys = NULL;
	memcpy(mppe->master_key, master_key, sizeof(mppe->master_key));

	mppe->keylenbits = keylenbits;
	switch (keylenbits) {
	case 40:
	case 56:
		mppe->keylen = 8;
		break;
	case 128:
		mppe->keylen = 16;
		break;
	}

	GetNewKeyFromSHA(mppe->master_key, mppe->master_key, mppe->keylen,
	    mppe->session_key);
	pipex_mppe_reduce_key(mppe);
	pipex_mppe_setkey(mppe);
}

void
pipex_session_init_mppe_recv(struct pipex_session *session, int stateless,
    int keylenbits, u_char *master_key)
{
	pipex_mppe_init(&session->mppe_recv, stateless, keylenbits,
	    master_key, stateless);
	session->ppp_flags |= PIPEX_PPP_MPPE_ACCEPTED;
}

void
pipex_session_init_mppe_send(struct pipex_session *session, int stateless,
    int keylenbits, u_char *master_key)
{
	pipex_mppe_init(&session->mppe_send, stateless, keylenbits,
	    master_key, 0);
	session->ppp_flags |= PIPEX_PPP_MPPE_ENABLED;
}

#include <crypto/sha1.h>

static u_char SHAPad1[] = {
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
}, SHAPad2[] = {
	0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2,
	0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2,
	0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2,
	0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2,
	0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2,
};

Static void
GetNewKeyFromSHA(u_char *StartKey, u_char *SessionKey, int SessionKeyLength,
    u_char *InterimKey)
{
	u_char Digest[20];
	SHA1_CTX Context;

	SHA1Init(&Context);
	SHA1Update(&Context, StartKey, SessionKeyLength);
	SHA1Update(&Context, SHAPad1, 40);
	SHA1Update(&Context, SessionKey, SessionKeyLength);
	SHA1Update(&Context, SHAPad2, 40);
	SHA1Final(Digest, &Context);

	memcpy(InterimKey, Digest, SessionKeyLength);
}

Static void
pipex_mppe_reduce_key(struct pipex_mppe *mppe)
{
	switch (mppe->keylenbits) {
	case 40:
		mppe->session_key[1] = 0x26;
		mppe->session_key[2] = 0x9e;
	case 56:
		mppe->session_key[0] = 0xd1;
	}
}

Static void
mppe_key_change(struct pipex_mppe *mppe)
{
	u_char interim[16];
	struct rc4_ctx keychg;

	memset(&keychg, 0, sizeof(keychg));

	GetNewKeyFromSHA(mppe->master_key, mppe->session_key, mppe->keylen,
	    interim);

	rc4_keysetup(&keychg, interim, mppe->keylen);
	rc4_crypt(&keychg, interim, mppe->session_key, mppe->keylen);

	pipex_mppe_reduce_key(mppe);

	if (mppe->old_session_keys) {
		int idx = mppe->coher_cnt & PIPEX_MPPE_OLDKEYMASK;
		memcpy(mppe->old_session_keys[idx],
		    mppe->session_key, PIPEX_MPPE_KEYLEN);
	}
}

Static void
pipex_mppe_input(struct mbuf *m0, struct pipex_session *session)
{
	int pktloss, encrypt, flushed, m, n, len;
	struct pipex_mppe *mppe;
	uint16_t coher_cnt;
	struct mbuf *m1;
	u_char *cp;
	int rewind = 0;

	/* pullup */
	PIPEX_PULLUP(m0, sizeof(coher_cnt));
	if (m0 == NULL)
		goto drop;

	mppe = &session->mppe_recv;
	/* get header information */
	cp = mtod(m0, u_char *);
	GETSHORT(coher_cnt, cp);
	flushed = ((coher_cnt & 0x8000) != 0) ? 1 : 0;
	encrypt = ((coher_cnt & 0x1000) != 0) ? 1 : 0;
	coher_cnt &= PIPEX_COHERENCY_CNT_MASK;
	pktloss = 0;

	PIPEX_MPPE_DBG((session, LOG_DEBUG, "in coher_cnt=%03x %s%s",
	    mppe->coher_cnt, (flushed) ? "[flushed]" : "",
	    (encrypt) ? "[encrypt]" : ""));

	if (encrypt == 0) {
		pipex_session_log(session, LOG_DEBUG,
		    "Received unexpected MPPE packet.(no ecrypt)");
		goto drop;
	}

	/* adjust mbuf */
	m_adj(m0, sizeof(coher_cnt));

	/*
	 * L2TP data session may be used without sequencing, PPP frames may
	 * arrive in disorder.  The 'coherency counter' of MPPE detects such
	 * situations, but we cannot distinguish between 'disorder' and
	 * 'packet loss' exactly.
	 *
	 * When 'coherency counter' detects lost packets greater than
	 * (4096 - 256), we treat as 'disorder' otherwise treat as
	 * 'packet loss'.
	 */
    {
	int coher_cnt0;

	coher_cnt0 = coher_cnt;
	if (coher_cnt < mppe->coher_cnt)
		coher_cnt0 += 0x1000;
	if (coher_cnt0 - mppe->coher_cnt > 0x0f00) {
		if (!mppe->stateless ||
		    coher_cnt0 - mppe->coher_cnt
		    <= 0x1000 - PIPEX_MPPE_NOLDKEY) {
			pipex_session_log(session, LOG_DEBUG,
			    "Workaround the out-of-sequence PPP framing problem: "
			    "%d => %d", mppe->coher_cnt, coher_cnt);
			goto drop;
		}
		rewind = 1;
	}
    }

	if (mppe->stateless != 0) {
		if (!rewind) {
			mppe_key_change(mppe);
			while (mppe->coher_cnt != coher_cnt) {
				mppe->coher_cnt++;
				mppe->coher_cnt &= PIPEX_COHERENCY_CNT_MASK;
				mppe_key_change(mppe);
				pktloss++;
			}
		}
		pipex_mppe_setoldkey(mppe, coher_cnt);
	} else {
		if (flushed) {
			if (coher_cnt < mppe->coher_cnt) {
				coher_cnt += 0x1000;
			}
			pktloss += coher_cnt - mppe->coher_cnt;
			m = mppe->coher_cnt / 256;
			n = coher_cnt / 256;
			while (m++ < n)
				mppe_key_change(mppe);

			coher_cnt &= PIPEX_COHERENCY_CNT_MASK;
			mppe->coher_cnt = coher_cnt;
		} else if (mppe->coher_cnt != coher_cnt) {
			/* Send CCP ResetReq */
			PIPEX_DBG((session, LOG_DEBUG, "CCP SendResetReq"));
			pipex_ccp_output(session, CCP_RESETREQ,
			    session->ccp_id++);
			goto drop;
		}
		if ((coher_cnt & 0xff) == 0xff) {
			mppe_key_change(mppe);
			flushed = 1;
		}
		if (flushed)
			pipex_mppe_setkey(mppe);
	}

	if (pktloss > 1000) {
		pipex_session_log(session, LOG_DEBUG,
		    "%d packets loss.", pktloss);
	}

	/* decrypt ppp payload */
	for (m1 = m0; m1; m1 = m1->m_next) {
		cp = mtod(m1, u_char *);
		len = m1->m_len;
		pipex_mppe_crypt(mppe, len, cp, cp);
	}

	if (!rewind) {
		/* update coher_cnt */
		mppe->coher_cnt++;
		mppe->coher_cnt &= PIPEX_COHERENCY_CNT_MASK;
	}

	pipex_ppp_input(m0, session, 1);

	return;
drop:
	if (m0 != NULL)
		m_freem(m0);
	session->stat.ierrors++;
}

Static void
pipex_mppe_output(struct mbuf *m0, struct pipex_session *session,
    uint16_t protocol)
{
	int encrypt, flushed, len;
	struct mppe_header {
		uint16_t coher_cnt;
		uint16_t protocol;
	} __packed *hdr;
	u_char *cp;
	struct pipex_mppe *mppe;
	struct mbuf *m;

	mppe = &session->mppe_send;

	/*
	 * create a deep-copy if the mbuf has a shared mbuf cluster.
	 * this is required to handle cases of tcp retransmition.
	 */
	for (m = m0; m != NULL; m = m->m_next) {
		if (M_READONLY(m)) {
			m = m_copym2(m0, 0, M_COPYALL, M_NOWAIT);
			if (m == NULL)
				goto drop;
			m_freem(m0);
			m0 = m;
			break;
		}
	}
	/* prepend mppe header */
	M_PREPEND(m0, sizeof(struct mppe_header), M_NOWAIT);
	if (m0 == NULL)
		goto drop;
	hdr = mtod(m0, struct mppe_header *);
	hdr->protocol = protocol;

	/* check coherency counter */
	flushed = 0;
	encrypt = 1;

	if (mppe->stateless != 0) {
		flushed = 1;
		mppe_key_change(mppe);
	} else {
		if ((mppe->coher_cnt % 0x100) == 0xff) {
			flushed = 1;
			mppe_key_change(mppe);
		} else if (mppe->resetreq != 0) {
			flushed = 1;
			mppe->resetreq = 0;
		}
	}

	if (flushed)
		pipex_mppe_setkey(mppe);

	PIPEX_MPPE_DBG((session, LOG_DEBUG, "out coher_cnt=%03x %s%s",
	    mppe->coher_cnt, (flushed) ? "[flushed]" : "",
	    (encrypt) ? "[encrypt]" : ""));

	/* setup header information */
	hdr->coher_cnt = (mppe->coher_cnt++) & PIPEX_COHERENCY_CNT_MASK;
	hdr->coher_cnt &= PIPEX_COHERENCY_CNT_MASK;
	if (flushed)
		hdr->coher_cnt |= 0x8000;
	if (encrypt)
		hdr->coher_cnt |= 0x1000;

	HTONS(hdr->protocol);
	HTONS(hdr->coher_cnt);

	/* encrypt chain */
	for (m = m0; m; m = m->m_next) {
		cp = mtod(m, u_char *);
		len = m->m_len;
		if (m == m0 && len > offsetof(struct mppe_header, protocol)) {
			len -= offsetof(struct mppe_header, protocol);
			cp += offsetof(struct mppe_header, protocol);
		}
		pipex_mppe_crypt(mppe, len, cp, cp);
	}

	pipex_ppp_output(m0, session, PPP_COMP);

	return;
drop:
	session->stat.oerrors++;
}

Static void
pipex_ccp_input(struct mbuf *m0, struct pipex_session *session)
{
	u_char *cp;
	int code, id, len;

	if (m0->m_pkthdr.len < PPP_HDRLEN)
		goto drop;
	if ((m0 = m_pullup(m0, PPP_HDRLEN)) == NULL)
		goto drop;

	cp = mtod(m0, u_char *);
	GETCHAR(code, cp);
	GETCHAR(id, cp);
	GETSHORT(len, cp);

	switch (code) {
	case CCP_RESETREQ:
		PIPEX_DBG((session, LOG_DEBUG, "CCP RecvResetReq"));
		session->mppe_send.resetreq = 1;
#ifndef PIPEX_NO_CCP_RESETACK
		PIPEX_DBG((session, LOG_DEBUG, "CCP SendResetAck"));
		pipex_ccp_output(session, CCP_RESETACK, id);
#endif
		/* ignore error */
		break;
	case CCP_RESETACK:
		PIPEX_DBG((session, LOG_DEBUG, "CCP RecvResetAck"));
		break;
	default:
		PIPEX_DBG((session, LOG_DEBUG, "CCP Recv code=%d", code));
		goto drop;
	}
	m_freem(m0);

	return;
drop:
	if (m0 != NULL)
		m_freem(m0);
	session->stat.ierrors++;
}

Static int
pipex_ccp_output(struct pipex_session *session, int code, int id)
{
	u_char *cp;
	struct mbuf *m;

	MGETHDR(m, M_DONTWAIT, MT_DATA);
	if (m == NULL) {
		session->stat.oerrors++;
		return (1);
	}
	m->m_pkthdr.len = m->m_len = 4;
	cp = mtod(m, u_char *);
	PUTCHAR(code, cp);
	PUTCHAR(id, cp);
	PUTSHORT(4, cp);

	pipex_ppp_output(m, session, PPP_CCP);

	return (0);
}
#endif
/***********************************************************************
 * Miscellaneous fuctions
 ***********************************************************************/
/* adapted from FreeBSD:src/usr.sbin/ppp/tcpmss.c */
/*
 * Copyright (c) 2000 Ruslan Ermilov and Brian Somers <brian@Awfulhak.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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 AUTHOR 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 AUTHOR 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.
 *
 * $FreeBSD: src/usr.sbin/ppp/tcpmss.c,v 1.1.4.3 2001/07/19 11:39:54 brian Exp $
 */
#define TCP_OPTLEN_IN_SEGMENT	12	/* timestamp option and padding */
#define MAXMSS(mtu) (mtu - sizeof(struct ip) - sizeof(struct tcphdr) - \
    TCP_OPTLEN_IN_SEGMENT)
/*
 * The following macro is used to update an internet checksum.  "acc" is a
 * 32-bit accumulation of all the changes to the checksum (adding in old
 * 16-bit words and subtracting out new words), and "cksum" is the checksum
 * value to be updated.
 */
#define ADJUST_CHECKSUM(acc, cksum) {			\
	acc += cksum;					\
	if (acc < 0) {					\
		acc = -acc;				\
		acc = (acc >> 16) + (acc & 0xffff);	\
		acc += acc >> 16;			\
		cksum = (u_short) ~acc;			\
	} else {					\
		acc = (acc >> 16) + (acc & 0xffff);	\
		acc += acc >> 16;			\
		cksum = (u_short) acc;			\
	}						\
}

/*
 * Rewrite max-segment-size TCP option to avoid PMTU blackhole issues.
 * The mtu parameter should be the MTU bottleneck (as far as we know)
 * on the link between the source and the destination.
 */
Static struct mbuf *
adjust_tcp_mss(struct mbuf *m0, int mtu)
{
	int opt, optlen, acc, mss, maxmss, lpktp;
	struct ip *pip;
	struct tcphdr *th;
	u_char *pktp, *mssp;
	u_int16_t ip_off;

	lpktp = sizeof(struct ip) + sizeof(struct tcphdr) + PIPEX_TCP_OPTLEN;
	lpktp = MIN(lpktp, m0->m_pkthdr.len);

	PIPEX_PULLUP(m0, lpktp);
	if (m0 == NULL)
		goto drop;

	pktp = mtod(m0, char *);
	pip = (struct ip *)pktp;
	ip_off = ntohs(pip->ip_off);

	/* Non TCP or fragmented packet must not have a MSS option */
	if (pip->ip_p != IPPROTO_TCP ||
	    (ip_off & IP_MF) != 0 || (ip_off & IP_OFFMASK) != 0)
		goto handled;

	pktp += pip->ip_hl << 2;
	lpktp -= pip->ip_hl << 2;

	/* packet is broken */
	if (sizeof(struct tcphdr) > lpktp)
		goto drop;
	th = (struct tcphdr *)pktp;

	/*
	 * As RFC 973, a MSS field must only be sent in the initial
	 * connection request(it must be with SYN).
	 */
	if ((th->th_flags & TH_SYN) == 0)
		goto handled;

	lpktp = MIN(th->th_off << 4, lpktp);

	pktp += sizeof(struct tcphdr);
	lpktp -= sizeof(struct tcphdr);
	while (lpktp >= TCPOLEN_MAXSEG) {
		GETCHAR(opt, pktp);
		switch (opt) {
		case TCPOPT_MAXSEG:
			GETCHAR(optlen, pktp);
			mssp = pktp;		/* mss place holder */
			GETSHORT(mss, pktp);
			maxmss = MAXMSS(mtu);
			if (mss > maxmss) {
				PIPEX_DBG((NULL, LOG_DEBUG,
				    "change tcp-mss %d => %d", mss, maxmss));
				PUTSHORT(maxmss, mssp);
				acc = htons(mss);
				acc -= htons(maxmss);
				ADJUST_CHECKSUM(acc, th->th_sum);
			}
			goto handled;
			/* NOTREACHED */
		case TCPOPT_EOL:
			goto handled;
			/* NOTREACHED */
		case TCPOPT_NOP:
			lpktp--;
			break;
		default:
			GETCHAR(optlen, pktp);
			if (optlen < 2)	/* packet is broken */
				goto drop;
			pktp += optlen - 2;
			lpktp -= optlen;
			break;
		}
	}

handled:
	return (m0);

drop:
	if (m0)
		m_freem(m0);
	return (NULL);
}

/*
 *  Check whether a packet should reset idle timer
 *  Returns 1 to don't reset timer (i.e. the packet is "idle" packet)
 */
Static struct mbuf *
ip_is_idle_packet(struct mbuf *m0, int *ris_idle)
{
	u_int16_t ip_off;
	const struct udphdr *uh;
	struct ip *pip;
	int len;

	/* pullup ip header */
	len = sizeof(struct ip);
	PIPEX_PULLUP(m0, len);
	if (m0 == NULL)
		goto error;
	pip = mtod(m0, struct ip *);

	/*
	 * the packet which fragmentations was not the idle packet.
	 */
	ip_off = ntohs(pip->ip_off);
	if ((ip_off & IP_MF) || ((ip_off & IP_OFFMASK) != 0))
		goto is_active;

	switch (pip->ip_p) {
	case IPPROTO_IGMP:
		goto is_active;
	case IPPROTO_ICMP:
		len = pip->ip_hl * 4 + 8;
		PIPEX_PULLUP(m0, len);
		if (m0 == NULL)
			goto error;

		switch (((unsigned char *) pip)[pip->ip_hl * 4]) {
		case 0:	/* Echo Reply */
		case 8:	/* Echo Request */
			goto is_active;
		default:
			goto is_idle;
		}

	case IPPROTO_UDP:
	case IPPROTO_TCP:
		len = pip->ip_hl * 4 + sizeof(struct udphdr);
		PIPEX_PULLUP(m0, len);
		if (m0 == NULL)
			goto error;
		uh = mtod(m0, struct udphdr *);

		switch (ntohs(uh->uh_sport)) {
		case 53:	/* DOMAIN */
		case 67:	/* BOOTPS */
		case 68:	/* BOOTPC */
		case 123:	/* NTP */
		case 137:	/* NETBIOS-NS */
		case 520:	/* RIP */
			goto is_idle;
		}
		switch (ntohs(uh->uh_dport)) {
		case 53:	/* DOMAIN */
		case 67:	/* BOOTPS */
		case 68:	/* BOOTPC */
		case 123:	/* NTP */
		case 137:	/* NETBIOS-NS */
		case 520:	/* RIP */
			goto is_idle;
		}
		goto is_active;
	default:
		goto is_active;
	}

is_active:
	*ris_idle = 0;
	return (m0);

is_idle:
	*ris_idle = 1;
	return (m0);

error:
	return (NULL);
}

Static void
pipex_session_log(struct pipex_session *session, int prio, const char *fmt, ...)
{
	char logbuf[1024];
	va_list ap;

	logpri(prio);
	if (session != NULL) {
		addlog("pipex: ppp=%d iface=%s protocol=%s id=%d ",
		    session->ppp_id, session->pipex_iface->ifnet_this->if_xname,
		    (session->protocol == PIPEX_PROTO_PPPOE)? "PPPoE" :
		    (session->protocol == PIPEX_PROTO_PPTP)? "PPTP" :
		    (session->protocol == PIPEX_PROTO_L2TP) ? "L2TP" :
		    "Unknown", session->session_id);
	} else
		addlog("pipex: ");

	va_start(ap, fmt);
	vsnprintf(logbuf, sizeof(logbuf), fmt, ap);
	va_end(ap);
	addlog("%s\n", logbuf);
}

Static uint32_t
pipex_sockaddr_hash_key(struct sockaddr *sa)
{
	switch (sa->sa_family) {
	case AF_INET:
		return ntohl(((struct sockaddr_in *)sa)->sin_addr.s_addr);
	case AF_INET6:
		return ntohl(((struct sockaddr_in6 *)sa)->sin6_addr
		    .s6_addr32[3]);
	}
	panic("pipex_sockaddr_hash_key: unknown address family");
	return (0);
}

/*
 * Compare struct sockaddr_in{,6} with the address only.
 * The port number is not covered.
 */
Static int
pipex_sockaddr_compar_addr(struct sockaddr *a, struct sockaddr *b)
{
	int cmp;

	cmp = b->sa_family - a->sa_family;
	if (cmp != 0)
		return cmp;
	switch (a->sa_family) {
	case AF_INET:
		return ((struct sockaddr_in *)b)->sin_addr.s_addr -
		    ((struct sockaddr_in *)a)->sin_addr.s_addr;
	case AF_INET6:
		cmp = ((struct sockaddr_in6 *)b)->sin6_scope_id -
		    ((struct sockaddr_in6 *)a)->sin6_scope_id;
		if (cmp != 0)
			return cmp;
		return memcmp(&((struct sockaddr_in6 *)a)->sin6_addr,
		    &((struct sockaddr_in6 *)b)->sin6_addr,
		    sizeof(struct in6_addr));
	}
	panic("pipex_sockaddr_compar_addr: unknown address family");

	return (-1);
}

Static inline int
pipex_mppe_setkey(struct pipex_mppe *mppe)
{
	rc4_keysetup(&mppe->rc4ctx, mppe->session_key, mppe->keylen);

	return (0);
}

Static inline int
pipex_mppe_setoldkey(struct pipex_mppe *mppe, uint16_t coher_cnt)
{
	KASSERT(mppe->old_session_keys != NULL);

	rc4_keysetup(&mppe->rc4ctx,
	    mppe->old_session_keys[coher_cnt & PIPEX_MPPE_OLDKEYMASK],
	    mppe->keylen);

	return (0);
}

Static inline void
pipex_mppe_crypt(struct pipex_mppe *mppe, int len, u_char *indata,
    u_char *outdata)
{
	rc4_crypt(&mppe->rc4ctx, indata, outdata, len);
}

int
pipex_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
    size_t newlen)
{
	switch (name[0]) {
	case PIPEXCTL_ENABLE:
		if (namelen != 1)
			return (ENOTDIR);
		return (sysctl_int(oldp, oldlenp, newp, newlen,
		    &pipex_enable));
	case PIPEXCTL_INQ:
	        return (sysctl_ifq(name + 1, namelen - 1,
		    oldp, oldlenp, newp, newlen, &pipexinq));
	case PIPEXCTL_OUTQ:
	        return (sysctl_ifq(name + 1, namelen - 1,
		    oldp, oldlenp, newp, newlen, &pipexoutq));
	default:
		return (ENOPROTOOPT);
	}
	/* NOTREACHED */
}