summaryrefslogtreecommitdiffstats
path: root/sys/netkey/key.c
blob: f00792d00d5048026c196619051fce409d8affbc (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
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
/*
 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
 * 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.
 * 3. Neither the name of the project nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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$
 */

/* KAME $Id: key.c,v 1.1.6.5.2.19 1999/07/22 14:09:24 itojun Exp $ */

/*
 * This code is referd to RFC 2367
 */

#include "opt_inet.h"
#include "opt_inet6.h"
#include "opt_ipsec.h"

#include <sys/types.h>
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/mbuf.h>
#include <sys/domain.h>
#include <sys/protosw.h>
#include <sys/malloc.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/sysctl.h>
#include <sys/errno.h>
#include <sys/proc.h>
#include <sys/queue.h>

#include <net/if.h>
#include <net/route.h>
#include <net/raw_cb.h>

#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/in_var.h>
#include <netinet/in_pcb.h>

#ifdef INET6
#include <netinet6/ip6.h>
#include <netinet6/in6_var.h>
#include <netinet6/in6_pcb.h>
#endif /* INET6 */

#include <net/pfkeyv2.h>
#include <netkey/key_var.h>
#include <netkey/keydb.h>
#include <netkey/key.h>
#include <netkey/keysock.h>
#ifdef IPSEC_DEBUG
#include <netkey/key_debug.h>
#else
#define	KEYDEBUG(lev,arg)
#endif

#include <netinet6/ipsec.h>
#include <netinet6/ah.h>
#ifdef INET6
#include <netinet6/ipsec6.h>
#include <netinet6/ah6.h>
#endif
#ifdef IPSEC_ESP
#include <netinet6/esp.h>
#ifdef INET6
#include <netinet6/esp6.h>
#endif
#endif

MALLOC_DEFINE(M_SECA, "key mgmt", "security associations, key management");

#if defined(IPSEC_DEBUG)
u_int32_t key_debug_level = 0;
#endif /* defined(IPSEC_DEBUG) */
static u_int key_spi_trycnt = 1000;
static u_int32_t key_spi_minval = 0x100;
static u_int32_t key_spi_maxval = 0x0fffffff;	/* XXX */
static u_int key_int_random = 60;	/*interval to initialize randseed,1(m)*/
static u_int key_larval_lifetime = 30;	/* interval to expire acquiring, 30(s)*/
static int key_blockacq_count = 10;	/* counter for blocking SADB_ACQUIRE.*/
static int key_blockacq_lifetime = 20;	/* lifetime for blocking SADB_ACQUIRE.*/

static u_int32_t acq_seq = 0;
static int key_tick_init_random = 0;

static LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX];	/* SPD */
static LIST_HEAD(_sahtree, secashead) sahtree;			/* SAD */
static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
							/* registed list */
#ifndef IPSEC_NONBLOCK_ACQUIRE
static LIST_HEAD(_acqtree, secacq) acqtree;		/* acquiring list */
#endif

struct key_cb key_cb;

/* search order for SAs */
static u_int saorder_state_valid[] = {
	SADB_SASTATE_MATURE, SADB_SASTATE_DYING
};
static u_int saorder_state_alive[] = {
	/* except DEAD */
	SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
};
static u_int saorder_state_any[] = {
	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
	SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
};

#if defined(IPSEC_DEBUG)
SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL,	debug,	CTLFLAG_RW, \
	&key_debug_level,	0,	"");
#endif /* defined(IPSEC_DEBUG) */

/* max count of trial for the decision of spi value */
SYSCTL_INT(_net_key, KEYCTL_SPI_TRY,		spi_trycnt,	CTLFLAG_RW, \
	&key_spi_trycnt,	0,	"");

/* minimum spi value to allocate automatically. */
SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE,	spi_minval,	CTLFLAG_RW, \
	&key_spi_minval,	0,	"");

/* maximun spi value to allocate automatically. */
SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE,	spi_maxval,	CTLFLAG_RW, \
	&key_spi_maxval,	0,	"");

/* interval to initialize randseed */
SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT,	int_random,	CTLFLAG_RW, \
	&key_int_random,	0,	"");

/* lifetime for larval SA */
SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME,	larval_lifetime,	CTLFLAG_RW, \
	&key_larval_lifetime,	0,	"");

/* counter for blocking to send SADB_ACQUIRE to IKEd */
SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,	blockacq_count,	CTLFLAG_RW, \
	&key_blockacq_count,	0,	"");

/* lifetime for blocking to send SADB_ACQUIRE to IKEd */
SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,	blockacq_lifetime,	CTLFLAG_RW, \
	&key_blockacq_lifetime,	0,	"");

#define	__LIST_FOREACH(elm, head, field)                                     \
	for (elm = LIST_FIRST(head); elm; elm = LIST_NEXT(elm, field))
#define	__LIST_CHAINED(elm) \
	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))

#define	KEY_CHKSASTATE(head, sav, name) {                                    \
	if ((head) != (sav)) {                                               \
		printf("%s: state mismatched (TREE=%d SA=%d)\n",             \
			(name), (head), (sav));                              \
		continue;                                                    \
	}                                                                    \
}

#define	KEY_CHKSPDIR(head, sp, name) {                                       \
	if ((head) != (sp)) {                                                \
		printf("%s: direction mismatched (TREE=%d SP=%d), "          \
			"anyway continue.\n",                                \
			(name), (head), (sp));                               \
	}                                                                    \
}

#define	KMALLOC(p, t, n)                                                     \
	((p) = (t) malloc((unsigned long)(n), M_SECA, M_NOWAIT))
#define	KFREE(p)                                                             \
	free((caddr_t)(p), M_SECA);

#define	KEY_NEWBUF(dst, t, src, len)                                         \
	((dst) = (t)key_newbuf((src), (len)))

/*
 * set parameters into secpolicyindex buffer.
 * Must allocate secpolicyindex buffer passed to this function.
 */
#define	KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) do {                   \
	bzero((idx), sizeof(struct secpolicyindex));                             \
	(idx)->dir = (_dir);                                                 \
	(idx)->prefs = (ps);                                                 \
	(idx)->prefd = (pd);                                                 \
	(idx)->ul_proto = (ulp);                                             \
	bcopy((s), &(idx)->src, ((struct sockaddr *)(s))->sa_len);           \
	bcopy((d), &(idx)->dst, ((struct sockaddr *)(d))->sa_len);           \
} while (0)

/*
 * set parameters into secasindex buffer.
 * Must allocate secasindex buffer before calling this function.
 */
#define	KEY_SETSECASIDX(p, m, s, d, idx) do {                                \
	bzero((idx), sizeof(struct secasindex));                             \
	(idx)->proto = (p);                                                  \
	(idx)->mode = (m);                                                   \
	bcopy((s), &(idx)->src, ((struct sockaddr *)(s))->sa_len);           \
	bcopy((d), &(idx)->dst, ((struct sockaddr *)(d))->sa_len);           \
} while (0)

/* key statistics */
struct _keystat {
	u_long getspi_count; /* the avarage of count to try to get new SPI */
} keystat;

static struct secasvar *key_allocsa_policy __P((struct ipsecrequest *isr));
static void key_freesp_so __P((struct secpolicy **sp));
static struct secasvar *key_do_allocsa_policy __P((struct secashead *sah,
						u_int state));
static void key_delsp __P((struct secpolicy *sp));
static struct secpolicy *key_getsp __P((struct secpolicyindex *spidx));
static struct sadb_msg *key_spdadd __P((caddr_t *mhp));
static struct sadb_msg *key_spddelete __P((caddr_t *mhp));
static struct sadb_msg *key_spdflush __P((caddr_t *mhp));
static int key_spddump __P((caddr_t *mhp, struct socket *so, int target));
static u_int key_setdumpsp __P((struct sadb_msg *newmsg, struct secpolicy *sp,
				u_int8_t type, u_int32_t seq, u_int32_t pid));
static u_int key_getspmsglen __P((struct secpolicy *sp));
static u_int key_getspreqmsglen __P((struct secpolicy *sp));
static struct secashead *key_newsah __P((struct secasindex *saidx));
static void key_delsah __P((struct secashead *sah));
static struct secasvar *key_newsav __P((caddr_t *mhp, struct secashead *sah));
static void key_delsav __P((struct secasvar *sav));
static struct secashead *key_getsah __P((struct secasindex *saidx));
static struct secasvar *key_checkspidup __P((struct secasindex *saidx,
						u_int32_t spi));
static struct secasvar *key_getsavbyspi __P((struct secashead *sah,
						u_int32_t spi));
static int key_setsaval __P((struct secasvar *sav, caddr_t *mhp));
static u_int key_getmsglen __P((struct secasvar *sav));
static int key_mature __P((struct secasvar *sav));
static u_int key_setdumpsa __P((struct sadb_msg *newmsg, struct secasvar *sav,
				u_int8_t type, u_int8_t satype,
				u_int32_t seq, u_int32_t pid));
static caddr_t key_setsadbmsg __P((caddr_t buf, u_int8_t type, int tlen,
				u_int8_t satype, u_int32_t seq, pid_t pid,
				u_int8_t reserved1, u_int8_t reserved2));
static caddr_t key_setsadbsa __P((caddr_t buf, struct secasvar *sav));
static caddr_t key_setsadbaddr __P((caddr_t buf, u_int16_t exttype,
	struct sockaddr *saddr, u_int8_t prefixlen, u_int16_t ul_proto));
static caddr_t key_setsadbident
	__P((caddr_t buf, u_int16_t exttype, u_int16_t idtype,
		caddr_t string, int stringlen, u_int64_t id));
static caddr_t key_setsadbext __P((caddr_t p, caddr_t ext));
static void *key_newbuf __P((void *src, u_int len));
#ifdef INET6
static int key_ismyaddr6 __P((caddr_t addr));
#endif
static int key_cmpsaidx_exactly
	__P((struct secasindex *saidx0, struct secasindex *saidx1));
static int key_cmpsaidx_withmode
	__P((struct secasindex *saidx0, struct secasindex *saidx1));
static int key_cmpspidx_exactly
	__P((struct secpolicyindex *spidx0, struct secpolicyindex *spidx1));
static int key_cmpspidx_withmask
	__P((struct secpolicyindex *spidx0, struct secpolicyindex *spidx1));
static int key_bbcmp __P((caddr_t p1, caddr_t p2, u_int bits));
static u_int16_t key_satype2proto __P((u_int8_t satype));
static u_int8_t key_proto2satype __P((u_int16_t proto));

static struct sadb_msg *key_getspi __P((caddr_t *mhp));
static u_int32_t key_do_getnewspi __P((struct sadb_spirange *spirange,
					struct secasindex *saidx));
static struct sadb_msg *key_update __P((caddr_t *mhp));
static struct secasvar *key_getsavbyseq __P((struct secashead *sah,
						u_int32_t seq));
static struct sadb_msg *key_add __P((caddr_t *mhp));
static struct sadb_msg *key_getmsgbuf_x1 __P((caddr_t *mhp));
static struct sadb_msg *key_delete __P((caddr_t *mhp));
static struct sadb_msg *key_get __P((caddr_t *mhp));
static int key_acquire __P((struct secasindex *saidx,
				struct secpolicyindex *spidx));
static struct secacq *key_newacq __P((struct secasindex *saidx));
static struct secacq *key_getacq __P((struct secasindex *saidx));
static struct secacq *key_getacqbyseq __P((u_int32_t seq));
static struct sadb_msg *key_acquire2 __P((caddr_t *mhp));
static struct sadb_msg *key_register __P((caddr_t *mhp, struct socket *so));
static int key_expire __P((struct secasvar *sav));
static struct sadb_msg *key_flush __P((caddr_t *mhp));
static int key_dump __P((caddr_t *mhp, struct socket *so, int target));
static void key_promisc __P((caddr_t *mhp, struct socket *so));
static int key_sendall __P((struct sadb_msg *msg, u_int len));
static int key_align __P((struct sadb_msg *msg, caddr_t *mhp));
static void key_sa_chgstate __P((struct secasvar *sav, u_int8_t state));
/* %%% IPsec policy management */
/*
 * allocating a SP for OUTBOUND or INBOUND packet.
 * Must call key_freesp() later.
 * OUT:	NULL:	not found
 *	others:	found and return the pointer.
 */
struct secpolicy *
key_allocsp(spidx, dir)
	struct secpolicyindex *spidx;
	u_int dir;
{
	struct secpolicy *sp;
	int s;

	/* sanity check */
	if (spidx == NULL)
		panic("key_allocsp: NULL pointer is passed.\n");

	/* check direction */
	switch (dir) {
	case IPSEC_DIR_INBOUND:
	case IPSEC_DIR_OUTBOUND:
		break;
	default:
		panic("key_allocsp: Invalid direction is passed.\n");
	}

	/* get a SP entry */
	s = splnet();	/*called from softclock()*/
	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
		printf("*** objects\n");
		kdebug_secpolicyindex(spidx));

	__LIST_FOREACH(sp, &sptree[dir], chain) {
		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
			printf("*** in SPD\n");
			kdebug_secpolicyindex(&sp->spidx));

		if (sp->state == IPSEC_SPSTATE_DEAD)
			continue;
		if (key_cmpspidx_withmask(&sp->spidx, spidx))
			goto found;
	}

	splx(s);
	return NULL;

found:
	/* sanity check */
	KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp");

	/* found a SPD entry */
	sp->refcnt++;
	splx(s);
	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
		printf("DP key_allocsp cause refcnt++:%d SP:%p\n",
			sp->refcnt, sp));

	return sp;
}

/*
 * checking each request entries in SP, and acquire SA if need.
 * OUT:	0: there are valid requests.
 *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
 */
int
key_checkrequest(isr)
	struct ipsecrequest *isr;
{
	u_int level;
	int error;

	/* sanity check */
	if (isr == NULL)
		panic("key_checkrequest: NULL pointer is passed.\n");

	/* check mode */
	switch (isr->saidx.mode) {
	case IPSEC_MODE_TRANSPORT:
	case IPSEC_MODE_TUNNEL:
		break;
	case IPSEC_MODE_ANY:
	default:
		panic("key_checkrequest: Invalid policy defined.\n");
	}

	/* get current level */
	level = ipsec_get_reqlevel(isr);

	/*
	 * We don't allocate new SA if the state of SA in the holder is
	 * SADB_SASTATE_MATURE, and if this is newer one.
	 */
	if (isr->sav != NULL) {
		/*
		 * XXX While SA is hanging on policy request(isr), its refcnt
		 * can not be zero.  So isr->sav->sah is valid pointer if
		 * isr->sav != NULL.  But that may not be true in fact.
		 * There may be missunderstanding by myself.  Anyway I set
		 * zero to isr->sav->sah when isr->sav is flushed.
		 * I must check to have conviction this issue.
		 */
		if (isr->sav->sah != NULL
		 && isr->sav != (struct secasvar *)LIST_FIRST(
			    &isr->sav->sah->savtree[SADB_SASTATE_MATURE])) {
			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
				printf("DP checkrequest calls free SA:%p\n",
					isr->sav));
			key_freesav(isr->sav);
		}
		isr->sav = NULL;
	}

	/* new SA allocation if no SA found. */
	if (isr->sav == NULL)
		isr->sav = key_allocsa_policy(isr);

	/* When there is SA. */
	if (isr->sav != NULL)
		return 0;

	/* there is no SA */
	if ((error = key_acquire(&isr->saidx, &isr->sp->spidx)) != 0) {
		/* XXX What I do ? */
		printf("key_checkrequest: error %d returned "
			"from key_acquire.\n", error);
		return error;
	}

	return level == IPSEC_LEVEL_REQUIRE ? ENOENT : 0;
}

/*
 * allocating a SA for policy entry from SAD.
 * NOTE: searching SAD of aliving state.
 * OUT:	NULL:	not found.
 *	others:	found and return the pointer.
 */
static struct secasvar *
key_allocsa_policy(isr)
	struct ipsecrequest *isr;
{
	struct secashead *sah;
	struct secasvar *sav;
	u_int stateidx, state;

	__LIST_FOREACH(sah, &sahtree, chain) {
		if (sah->state == SADB_SASTATE_DEAD)
			continue;
		if (key_cmpsaidx_withmode(&sah->saidx, &isr->saidx))
			goto found;
	}

	return NULL;

    found:

	/* search valid state */
	for (stateidx = 0;
	     stateidx < _ARRAYLEN(saorder_state_valid);
	     stateidx++) {

		state = saorder_state_valid[stateidx];

		sav = key_do_allocsa_policy(sah, state);
		if (sav != NULL)
			return sav;
	}

	return NULL;
}

/*
 * searching SAD with direction, protocol, mode and state.
 * called by key_allocsa_policy().
 * OUT:
 *	NULL	: not found
 *	others	: found, pointer to a SA.
 */
static struct secasvar *
key_do_allocsa_policy(sah, state)
	struct secashead *sah;
	u_int state;
{
	struct secasvar *sav, *candidate;

	/* initilize */
	candidate = NULL;

	__LIST_FOREACH(sav, &sah->savtree[state], chain) {

		/* sanity check */
		KEY_CHKSASTATE(sav->state, state, "key_do_allocsa_policy");

		/* initialize */
		if (candidate == NULL) {
			candidate = sav;
			continue;
		}

		/* Which SA is the better ? */

		/* sanity check 2 */
		if (candidate->lft_c == NULL || sav->lft_c == NULL) {
			/*XXX do panic ? */
			printf("key_do_allocsa_policy: "
				"lifetime_current is NULL.\n");
			continue;
		}

		/* XXX What the best method is to compare ? */
		if (candidate->lft_c->sadb_lifetime_addtime <
				sav->lft_c->sadb_lifetime_addtime) {
			candidate = sav;
			continue;
		}
	}

	if (candidate) {
		candidate->refcnt++;
		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
			printf("DP allocsa_policy cause "
				"refcnt++:%d SA:%p\n",
				candidate->refcnt, candidate));
	}
	return candidate;
}

/*
 * allocating a SA entry for a *INBOUND* packet.
 * Must call key_freesav() later.
 * OUT: positive:	pointer to a sav.
 *	NULL:		not found, or error occured.
 */
struct secasvar *
key_allocsa(family, src, dst, proto, spi)
	u_int family, proto;
	caddr_t src, dst;
	u_int32_t spi;
{
	struct secashead *sah;
	struct secasvar *sav;
	u_int stateidx, state;
	int s;

	/* sanity check */
	if (src == NULL || dst == NULL)
		panic("key_allocsa: NULL pointer is passed.\n");

	/*
	 * searching SAD.
	 * XXX: to be checked internal IP header somewhere.  Also when
	 * IPsec tunnel packet is received.  But ESP tunnel mode is
	 * encrypted so we can't check internal IP header.
	 */
	s = splnet();	/*called from softclock()*/
	__LIST_FOREACH(sah, &sahtree, chain) {

		/* search valid state */
		for (stateidx = 0;
		     stateidx < _ARRAYLEN(saorder_state_valid);
		     stateidx++) {

			state = saorder_state_valid[stateidx];
			__LIST_FOREACH(sav, &sah->savtree[state], chain) {

				/* sanity check */
				KEY_CHKSASTATE(sav->state, state, "key_allocsav");
				if (proto != sav->sah->saidx.proto)
					continue;
				if (spi != sav->spi)
					continue;

				if (key_bbcmp(src,
				     _INADDRBYSA(&sav->sah->saidx.src),
				     _INALENBYAF(sav->sah->saidx.src.ss_family) << 3)
				 && key_bbcmp(dst,
				     _INADDRBYSA(&sav->sah->saidx.dst),
				     _INALENBYAF(sav->sah->saidx.dst.ss_family) << 3))
					goto found;
			}
		}
	}

	/* not found */
	splx(s);
	return NULL;

found:
	sav->refcnt++;
	splx(s);
	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
		printf("DP allocsa cause refcnt++:%d SA:%p\n",
			sav->refcnt, sav));
	return sav;
}

/*
 * Must be called after calling key_allocsp().
 * For both the packet without socket and key_freeso().
 */
void
key_freesp(sp)
	struct secpolicy *sp;
{
	/* sanity check */
	if (sp == NULL)
		panic("key_freesp: NULL pointer is passed.\n");

	sp->refcnt--;
	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
		printf("DP freesp cause refcnt--:%d SP:%p\n",
			sp->refcnt, sp));

	if (sp->refcnt == 0)
		key_delsp(sp);

	return;
}

/*
 * Must be called after calling key_allocsp().
 * For the packet with socket.
 */
void
key_freeso(so)
	struct socket *so;
{
	/* sanity check */
	if (so == NULL)
		panic("key_freeso: NULL pointer is passed.\n");

	switch (so->so_proto->pr_domain->dom_family) {
#ifdef INET
	case PF_INET:
	    {
		struct inpcb *pcb = sotoinpcb(so);

		/* Does it have a PCB ? */
		if (pcb == NULL)
			return;
		key_freesp_so(&pcb->inp_sp->sp_in);
		key_freesp_so(&pcb->inp_sp->sp_out);
	    }
		break;
#endif
#ifdef INET6
	case PF_INET6:
	    {
		struct in6pcb *pcb  = sotoin6pcb(so);

		/* Does it have a PCB ? */
		if (pcb == NULL)
			return;
		key_freesp_so(&pcb->in6p_sp->sp_in);
		key_freesp_so(&pcb->in6p_sp->sp_out);
	    }
		break;
#endif /* INET6 */
	default:
		printf("key_freeso: unknown address family=%d.\n",
			so->so_proto->pr_domain->dom_family);
		return;
	}

	return;
}

static void
key_freesp_so(sp)
	struct secpolicy **sp;
{
	/* sanity check */
	if (sp == NULL || *sp == NULL)
		panic("key_freesp_so: sp == NULL\n");

	switch ((*sp)->policy) {
	case IPSEC_POLICY_IPSEC:
		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
			printf("DP freeso calls free SP:%p\n", *sp));
		key_freesp(*sp);
		*sp = NULL;
		break;
	case IPSEC_POLICY_ENTRUST:
	case IPSEC_POLICY_BYPASS:
		return;
	default:
		panic("key_freesp_so: Invalid policy found %d", (*sp)->policy);
	}

	return;
}

/*
 * Must be called after calling key_allocsa().
 * This function is called by key_freesp() to free some SA allocated
 * for a policy.
 */
void
key_freesav(sav)
	struct secasvar *sav;
{
	/* sanity check */
	if (sav == NULL)
		panic("key_freesav: NULL pointer is passed.\n");

	sav->refcnt--;
	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
		printf("DP freesav cause refcnt--:%d SA:%p SPI %d\n",
			sav->refcnt, sav, (u_int32_t)ntohl(sav->spi)));

	if (sav->refcnt == 0)
		key_delsav(sav);

	return;
}

/* %%% SPD management */
/*
 * free security policy entry.
 */
static void
key_delsp(sp)
	struct secpolicy *sp;
{
	int s;

	/* sanity check */
	if (sp == NULL)
		panic("key_delsp: NULL pointer is passed.\n");

	sp->state = IPSEC_SPSTATE_DEAD;

	if (sp->refcnt > 0)
		return; /* can't free */

	s = splnet();	/*called from softclock()*/
	/* remove from SP index */
	if (__LIST_CHAINED(sp))
		LIST_REMOVE(sp, chain);

    {
	struct ipsecrequest *isr = sp->req, *nextisr;

	while (isr != NULL) {
		if (isr->sav != NULL) {
			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
				printf("DP delsp calls free SA:%p\n",
					isr->sav));
			key_freesav(isr->sav);
			isr->sav = NULL;
		}

		nextisr = isr->next;
		KFREE(isr);
		isr = nextisr;
	}
    }

	KFREE(sp);

	splx(s);

	return;
}

/*
 * search SPD
 * OUT:	NULL	: not found
 *	others	: found, pointer to a SP.
 */
static struct secpolicy *
key_getsp(spidx)
	struct secpolicyindex *spidx;
{
	struct secpolicy *sp;

	/* sanity check */
	if (spidx == NULL)
		panic("key_getsp: NULL pointer is passed.\n");

	__LIST_FOREACH(sp, &sptree[spidx->dir], chain) {
		if (sp->state == IPSEC_SPSTATE_DEAD)
			continue;
		if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
			sp->refcnt++;
			return sp;
		}
	}

	return NULL;
}

struct secpolicy *
key_newsp()
{
	struct secpolicy *newsp = NULL;

	KMALLOC(newsp, struct secpolicy *, sizeof(*newsp));
	if (newsp == NULL) {
		printf("key_newsp: No more memory.\n");
		return NULL;
	}
	bzero(newsp, sizeof(*newsp));

	newsp->refcnt = 1;
	newsp->req = NULL;

	return newsp;
}

/*
 * create secpolicy structure from sadb_x_policy structure.
 * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
 * so must be set properly later.
 */
struct secpolicy *
key_msg2sp(xpl0)
	struct sadb_x_policy *xpl0;
{
	struct secpolicy *newsp;

	/* sanity check */
	if (xpl0 == NULL)
		panic("key_msg2sp: NULL pointer was passed.\n");

	if ((newsp = key_newsp()) == NULL)
		return NULL;

	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
	newsp->policy = xpl0->sadb_x_policy_type;

	/* check policy */
	switch (xpl0->sadb_x_policy_type) {
	case IPSEC_POLICY_DISCARD:
	case IPSEC_POLICY_NONE:
	case IPSEC_POLICY_ENTRUST:
	case IPSEC_POLICY_BYPASS:
		newsp->req = NULL;
		break;

	case IPSEC_POLICY_IPSEC:
	    {
		int tlen;
		struct sadb_x_ipsecrequest *xisr;
		struct ipsecrequest **p_isr = &newsp->req;

		/* validity check */
		if (PFKEY_EXTLEN(xpl0) <= sizeof(*xpl0)) {
			printf("key_msg2sp: Invalid msg length.\n");
			key_freesp(newsp);
			return NULL;
		}

		tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
		xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);

		while (tlen > 0) {

			/* length check */
			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
				printf("key_msg2sp: "
					"invalid ipsecrequest length.\n");
				key_freesp(newsp);
				return NULL;
			}

			/* allocate request buffer */
			KMALLOC(*p_isr, struct ipsecrequest *, sizeof(**p_isr));
			if ((*p_isr) == NULL) {
				printf("key_msg2sp: No more memory.\n");
				key_freesp(newsp);
				return NULL;
			}
			bzero(*p_isr, sizeof(**p_isr));

			/* set values */
			(*p_isr)->next = NULL;

			switch (xisr->sadb_x_ipsecrequest_proto) {
			case IPPROTO_ESP:
			case IPPROTO_AH:
				break;
			default:
				printf("key_msg2sp: invalid proto type=%u\n",
					xisr->sadb_x_ipsecrequest_proto);
				key_freesp(newsp);
				return NULL;
			}
			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;

			switch (xisr->sadb_x_ipsecrequest_mode) {
			case IPSEC_MODE_TRANSPORT:
			case IPSEC_MODE_TUNNEL:
				break;
			case IPSEC_MODE_ANY:
			default:
				printf("key_msg2sp: invalid mode=%u\n",
					xisr->sadb_x_ipsecrequest_mode);
				key_freesp(newsp);
				return NULL;
			}
			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;

			switch (xisr->sadb_x_ipsecrequest_level) {
			case IPSEC_LEVEL_DEFAULT:
			case IPSEC_LEVEL_USE:
			case IPSEC_LEVEL_REQUIRE:
				break;
			default:
				printf("key_msg2sp: invalid level=%u\n",
					xisr->sadb_x_ipsecrequest_level);
				key_freesp(newsp);
				return NULL;
			}
			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;

			/* set IP addresses if there */
			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
				struct sockaddr *paddr;

				paddr = (struct sockaddr *)(xisr + 1);

				/* validity check */
				if (paddr->sa_len
				    > sizeof((*p_isr)->saidx.src)) {
					printf("key_msg2sp: invalid request "
						"address length.\n");
					key_freesp(newsp);
					return NULL;
				}
				bcopy(paddr, &(*p_isr)->saidx.src,
					paddr->sa_len);

				paddr = (struct sockaddr *)((caddr_t)paddr
							+ paddr->sa_len);

				/* validity check */
				if (paddr->sa_len
				    > sizeof((*p_isr)->saidx.dst)) {
					printf("key_msg2sp: invalid request "
						"address length.\n");
					key_freesp(newsp);
					return NULL;
				}
				bcopy(paddr, &(*p_isr)->saidx.dst,
					paddr->sa_len);
			}

			(*p_isr)->sav = NULL;
			(*p_isr)->sp = newsp;

			/* initialization for the next. */
			p_isr = &(*p_isr)->next;
			tlen -= xisr->sadb_x_ipsecrequest_len;

			/* validity check */
			if (tlen < 0) {
				printf("key_msg2sp: becoming tlen < 0.\n");
				key_freesp(newsp);
				return NULL;
			}

			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
			                 + xisr->sadb_x_ipsecrequest_len);
		}
	    }
		break;
	default:
		printf("key_msg2sp: invalid policy type.\n");
		key_freesp(newsp);
		return NULL;
	}

	return newsp;
}

/*
 * copy secpolicy struct to sadb_x_policy structure indicated.
 */
struct sadb_x_policy *
key_sp2msg(sp)
	struct secpolicy *sp;
{
	struct sadb_x_policy *xpl;
	int tlen;
	caddr_t p;

	/* sanity check. */
	if (sp == NULL)
		panic("key_sp2msg: NULL pointer was passed.\n");

	tlen = key_getspreqmsglen(sp);

	KMALLOC(xpl, struct sadb_x_policy *, tlen);
	if (xpl == NULL) {
		printf("key_sp2msg: No more memory.\n");
		return NULL;
	}
	bzero(xpl, tlen);

	xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
	xpl->sadb_x_policy_type = sp->policy;
	xpl->sadb_x_policy_dir = sp->spidx.dir;
	p = (caddr_t)xpl + sizeof(*xpl);

	/* if is the policy for ipsec ? */
	if (sp->policy == IPSEC_POLICY_IPSEC) {
		struct sadb_x_ipsecrequest *xisr;
		struct ipsecrequest *isr;

		for (isr = sp->req; isr != NULL; isr = isr->next) {

			xisr = (struct sadb_x_ipsecrequest *)p;

			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
			xisr->sadb_x_ipsecrequest_level = isr->level;

			p += sizeof(*xisr);
			bcopy(&isr->saidx.src, p, isr->saidx.src.ss_len);
			p += isr->saidx.src.ss_len;
			bcopy(&isr->saidx.dst, p, isr->saidx.dst.ss_len);
			p += isr->saidx.src.ss_len;

			xisr->sadb_x_ipsecrequest_len =
				PFKEY_ALIGN8(sizeof(*xisr)
					+ isr->saidx.src.ss_len
					+ isr->saidx.dst.ss_len);
		}
	}

	return xpl;
}

/*
 * SADB_SPDADD processing
 * add a entry to SP database, when received
 *   <base, address(SD), policy>
 * from the user(?).
 * Adding to SP database,
 * and send
 *   <base, address(SD), policy>
 * to the socket which was send.
 *
 * IN:	mhp: pointer to the pointer to each header.
 * OUT:	NULL if fail.
 *	other if success, return pointer to the message to send.
 *
 */
static struct sadb_msg *
key_spdadd(mhp)
	caddr_t *mhp;
{
	struct sadb_msg *msg0;
	struct sadb_address *src0, *dst0;
	struct sadb_x_policy *xpl0;
	struct secpolicyindex spidx;
	struct secpolicy *newsp;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL)
		panic("key_spdadd: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	if (mhp[SADB_EXT_ADDRESS_SRC] == NULL
	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
	 || mhp[SADB_X_EXT_POLICY] == NULL) {
		printf("key_spdadd: invalid message is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	src0 = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
	dst0 = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
	xpl0 = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];

	/* make secindex */
	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
	                src0 + 1,
	                dst0 + 1,
	                src0->sadb_address_prefixlen,
	                dst0->sadb_address_prefixlen,
	                src0->sadb_address_proto,
	                &spidx);

	/* checking the direciton. */
	switch (xpl0->sadb_x_policy_dir) {
	case IPSEC_DIR_INBOUND:
	case IPSEC_DIR_OUTBOUND:
		break;
	default:
		printf("key_spdadd: Invalid SP direction.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	/* Is there SP in SPD ? */
	newsp = key_getsp(&spidx);
	if (newsp != NULL) {
		key_freesp(newsp);
		printf("key_spdadd: a SP entry exists already.\n");
		msg0->sadb_msg_errno = EEXIST;
		return NULL;
	}

	/* check policy */
	/* key_spdadd() accepts DISCARD, NONE and IPSEC. */
	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
	 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
		printf("key_spdadd: Invalid policy type.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	/* allocation new SP entry */
	if ((newsp = key_msg2sp(xpl0)) == NULL) {
		msg0->sadb_msg_errno = ENOBUFS;
		return NULL;
	}

	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
	                src0 + 1,
	                dst0 + 1,
	                src0->sadb_address_prefixlen,
	                dst0->sadb_address_prefixlen,
	                src0->sadb_address_proto,
	                &newsp->spidx);

	newsp->refcnt = 1;	/* do not reclaim until I say I do */
	newsp->state = IPSEC_SPSTATE_ALIVE;
	LIST_INSERT_HEAD(&sptree[newsp->spidx.dir], newsp, chain);

    {
	struct sadb_msg *newmsg;
	u_int len;
	caddr_t p;

	/* create new sadb_msg to reply. */
	len = sizeof(struct sadb_msg)
	    + PFKEY_EXTLEN(mhp[SADB_X_EXT_POLICY])
	    + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_SRC])
	    + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_DST]);

	KMALLOC(newmsg, struct sadb_msg *, len);
	if (newmsg == NULL) {
		printf("key_spdadd: No more memory.\n");
		msg0->sadb_msg_errno = ENOBUFS;
		return NULL;
	}
	bzero((caddr_t)newmsg, len);

	bcopy((caddr_t)msg0, (caddr_t)newmsg, sizeof(*msg0));
	newmsg->sadb_msg_errno = 0;
	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
	p = (caddr_t)newmsg + sizeof(*msg0);

	p = key_setsadbext(p, mhp[SADB_X_EXT_POLICY]);
	p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_SRC]);
	p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_DST]);

	return newmsg;
    }
}

/*
 * SADB_SPDDELETE processing
 * receive
 *   <base, address(SD), policy(*)>
 * from the user(?), and set SADB_SASTATE_DEAD,
 * and send,
 *   <base, address(SD), policy(*)>
 * to the ikmpd.
 * policy(*) including direction of policy.
 *
 * IN:	mhp: pointer to the pointer to each header.
 * OUT:	other if success, return pointer to the message to send.
 *	0 if fail.
 */
static struct sadb_msg *
key_spddelete(mhp)
	caddr_t *mhp;
{
	struct sadb_msg *msg0;
	struct sadb_address *src0, *dst0;
	struct sadb_x_policy *xpl0;
	struct secpolicyindex spidx;
	struct secpolicy *sp;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL)
		panic("key_spddelete: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	if (mhp[SADB_EXT_ADDRESS_SRC] == NULL
	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
	 || mhp[SADB_X_EXT_POLICY] == NULL) {
		printf("key_spddelete: invalid message is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
	dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);
	xpl0 = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];

	/* make secindex */
	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
	                src0 + 1,
	                dst0 + 1,
	                src0->sadb_address_prefixlen,
	                dst0->sadb_address_prefixlen,
	                src0->sadb_address_proto,
	                &spidx);

	/* checking the direciton. */
	switch (xpl0->sadb_x_policy_dir) {
	case IPSEC_DIR_INBOUND:
	case IPSEC_DIR_OUTBOUND:
		break;
	default:
		printf("key_spddelete: Invalid SP direction.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	/* Is there SP in SPD ? */
	if ((sp = key_getsp(&spidx)) == NULL) {
		printf("key_spddelete: no SP found.\n");
		msg0->sadb_msg_errno = ENOENT;
		return NULL;
	}

	sp->state = IPSEC_SPSTATE_DEAD;
	key_freesp(sp);

    {
	struct sadb_msg *newmsg;
	u_int len;
	caddr_t p;

	/* create new sadb_msg to reply. */
	len = sizeof(struct sadb_msg)
	    + PFKEY_EXTLEN(mhp[SADB_X_EXT_POLICY])
	    + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_SRC])
	    + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_DST]);

	KMALLOC(newmsg, struct sadb_msg *, len);
	if (newmsg == NULL) {
		printf("key_spddelete: No more memory.\n");
		msg0->sadb_msg_errno = ENOBUFS;
		return NULL;
	}
	bzero((caddr_t)newmsg, len);

	bcopy((caddr_t)mhp[0], (caddr_t)newmsg, sizeof(*msg0));
	newmsg->sadb_msg_errno = 0;
	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
	p = (caddr_t)newmsg + sizeof(*msg0);

	p = key_setsadbext(p, mhp[SADB_X_EXT_POLICY]);
	p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_SRC]);
	p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_DST]);

	return newmsg;
    }
}

/*
 * SADB_SPDFLUSH processing
 * receive
 *   <base>
 * from the user, and free all entries in secpctree.
 * and send,
 *   <base>
 * to the user.
 * NOTE: what to do is only marking SADB_SASTATE_DEAD.
 *
 * IN:	mhp: pointer to the pointer to each header.
 * OUT:	other if success, return pointer to the message to send.
 *	0 if fail.
 */
static struct sadb_msg *
key_spdflush(mhp)
	caddr_t *mhp;
{
	struct sadb_msg *msg0;
	struct secpolicy *sp;
	u_int dir;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL)
		panic("key_spdflush: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
		__LIST_FOREACH(sp, &sptree[dir], chain) {
			sp->state = IPSEC_SPSTATE_DEAD;
		}
	}

    {
	struct sadb_msg *newmsg;
	u_int len;

	/* create new sadb_msg to reply. */
	len = sizeof(struct sadb_msg);

	KMALLOC(newmsg, struct sadb_msg *, len);
	if (newmsg == NULL) {
		printf("key_spdflush: No more memory.\n");
		msg0->sadb_msg_errno = ENOBUFS;
		return NULL;
	}
	bzero((caddr_t)newmsg, len);

	bcopy((caddr_t)mhp[0], (caddr_t)newmsg, sizeof(*msg0));
	newmsg->sadb_msg_errno = 0;
	newmsg->sadb_msg_len = PFKEY_UNIT64(len);

	return(newmsg);
    }
}

/*
 * SADB_SPDDUMP processing
 * receive
 *   <base>
 * from the user, and dump all SP leaves
 * and send,
 *   <base> .....
 * to the ikmpd.
 *
 * IN:	mhp: pointer to the pointer to each header.
 * OUT:	other if success, return pointer to the message to send.
 *	0 if fail.
 */
static int
key_spddump(mhp, so, target)
	caddr_t *mhp;
	struct socket *so;
	int target;
{
	struct sadb_msg *msg0;
	struct secpolicy *sp;
	int len, cnt, cnt_sanity;
	struct sadb_msg *newmsg;
	u_int dir;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL)
		panic("key_spddump: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	/* search SPD entry and get buffer size. */
	cnt = cnt_sanity = 0;
	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
		__LIST_FOREACH(sp, &sptree[dir], chain) {
			cnt++;
		}
	}

	if (cnt == 0)
		return ENOENT;

	newmsg = NULL;
	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
		__LIST_FOREACH(sp, &sptree[dir], chain) {
			len = key_getspmsglen(sp);

			/* making buffer */
			KMALLOC(newmsg, struct sadb_msg *, len);
			if (newmsg == NULL) {
				printf("key_spddump: No more memory.\n");
				return ENOBUFS;
			}
			bzero((caddr_t)newmsg, len);

			--cnt;
			(void)key_setdumpsp(newmsg, sp, SADB_X_SPDDUMP,
			                    cnt, msg0->sadb_msg_pid);

			key_sendup(so, newmsg, len, target);
			KFREE(newmsg);
			newmsg = NULL;
		}
	}

	return 0;
}

static u_int
key_setdumpsp(newmsg, sp, type, seq, pid)
	struct sadb_msg *newmsg;
	struct secpolicy *sp;
	u_int8_t type;
	u_int32_t seq, pid;
{
	u_int tlen;
	caddr_t p;

	tlen = key_getspmsglen(sp);

	p = key_setsadbmsg((caddr_t)newmsg, type, tlen,
	                   SADB_SATYPE_UNSPEC, seq, pid,
	                   IPSEC_MODE_ANY, sp->refcnt);

	p = key_setsadbaddr(p,
	                    SADB_EXT_ADDRESS_SRC,
	                    (struct sockaddr *)&sp->spidx.src,
	                    sp->spidx.prefs,
	                    sp->spidx.ul_proto);
	p = key_setsadbaddr(p,
	                    SADB_EXT_ADDRESS_DST,
	                    (struct sockaddr *)&sp->spidx.dst,
	                    sp->spidx.prefd,
	                    sp->spidx.ul_proto);

    {
	struct sadb_x_policy *tmp;

	if ((tmp = key_sp2msg(sp)) == NULL) {
		printf("key_setdumpsp: No more memory.\n");
		return ENOBUFS;
	}

	/* validity check */
	if (key_getspreqmsglen(sp) != PFKEY_UNUNIT64(tmp->sadb_x_policy_len))
		panic("key_setdumpsp: length mismatch."
		      "sp:%d msg:%d\n",
			key_getspreqmsglen(sp),
			PFKEY_UNUNIT64(tmp->sadb_x_policy_len));

	bcopy(tmp, p, PFKEY_UNUNIT64(tmp->sadb_x_policy_len));
	KFREE(tmp);
    }

	return tlen;
}

/* get sadb message length for a SP. */
static u_int
key_getspmsglen(sp)
	struct secpolicy *sp;
{
	u_int tlen;

	/* sanity check */
	if (sp == NULL)
		panic("key_getspmsglen: NULL pointer is passed.\n");

	tlen = (sizeof(struct sadb_msg)
		+ sizeof(struct sadb_address)
		+ PFKEY_ALIGN8(_SALENBYAF(sp->spidx.src.ss_family))
		+ sizeof(struct sadb_address)
		+ PFKEY_ALIGN8(_SALENBYAF(sp->spidx.dst.ss_family)));

	tlen += key_getspreqmsglen(sp);

	return tlen;
}

/*
 * get PFKEY message length for security policy and request.
 */
static u_int
key_getspreqmsglen(sp)
	struct secpolicy *sp;
{
	u_int tlen;

	tlen = sizeof(struct sadb_x_policy);

	/* if is the policy for ipsec ? */
	if (sp->policy != IPSEC_POLICY_IPSEC)
		return tlen;

	/* get length of ipsec requests */
    {
	struct ipsecrequest *isr;
	int len;

	for (isr = sp->req; isr != NULL; isr = isr->next) {
		len = sizeof(struct sadb_x_ipsecrequest)
			+ isr->saidx.src.ss_len
			+ isr->saidx.dst.ss_len;

		tlen += PFKEY_ALIGN8(len);
	}
    }

	return tlen;
}

/* %%% SAD management */
/*
 * allocating a memory for new SA head, and copy from the values of mhp.
 * OUT:	NULL	: failure due to the lack of memory.
 *	others	: pointer to new SA head.
 */
static struct secashead *
key_newsah(saidx)
	struct secasindex *saidx;
{
	struct secashead *newsah;
	u_int stateidx;

	/* sanity check */
	if (saidx == NULL)
		panic("key_newsaidx: NULL pointer is passed.\n");

	KMALLOC(newsah, struct secashead *, sizeof(struct secashead));
	if (newsah == NULL) {
		return NULL;
	}
	bzero((caddr_t)newsah, sizeof(struct secashead));

	bcopy(saidx, &newsah->saidx, sizeof(newsah->saidx));

	for (stateidx = 0;
	     stateidx < _ARRAYLEN(saorder_state_any);
	     stateidx++) {
		LIST_INIT(&newsah->savtree[saorder_state_any[stateidx]]);
	}

	/* add to saidxtree */
	newsah->state = SADB_SASTATE_MATURE;
	LIST_INSERT_HEAD(&sahtree, newsah, chain);

	return(newsah);
}

/*
 * delete SA index and all SA registerd.
 */
static void
key_delsah(sah)
	struct secashead *sah;
{
	struct secasvar *sav, *nextsav;
	u_int stateidx, state;
	int s;

	/* sanity check */
	if (sah == NULL)
		panic("key_delsah: NULL pointer is passed.\n");

	s = splnet();	/*called from softclock()*/

	/* remove from tree of SA index */
	if (__LIST_CHAINED(sah))
		LIST_REMOVE(sah, chain);

	/* searching all SA registerd in the secindex. */
	for (stateidx = 0;
	     stateidx < _ARRAYLEN(saorder_state_any);
	     stateidx++) {

		state = saorder_state_any[stateidx];
		for (sav = (struct secasvar *)LIST_FIRST(&sah->savtree[state]);
		     sav != NULL;
		     sav = nextsav) {

			nextsav = LIST_NEXT(sav, chain);

			/* sanity check */
			KEY_CHKSASTATE(state, sav->state, "key_delsah");

			/* remove back pointer */
			sav->sah = NULL;

			if (sav->refcnt < 0) {
				printf("key_delsah: why refcnt < 0 ?, "
					"sav->refcnt=%d\n",
					sav->refcnt);
			}
			key_freesav(sav);
			sav = NULL;
		}
	}

	if (sah->sa_route.ro_rt) {
		RTFREE(sah->sa_route.ro_rt);
		sah->sa_route.ro_rt = (struct rtentry *)NULL;
	}

	KFREE(sah);

	splx(s);
	return;
}

/*
 * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
 * and copy the values of mhp into new buffer.
 * When SAD message type is GETSPI:
 *	to set sequence number from acq_seq++,
 *	to set zero to SPI.
 *	not to call key_setsava().
 * OUT:	NULL	: fail
 *	others	: pointer to new secasvar.
 */
static struct secasvar *
key_newsav(mhp, sah)
	caddr_t *mhp;
	struct secashead *sah;
{
	struct secasvar *newsav;
	struct sadb_msg *msg0;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL || sah == NULL)
		panic("key_newsa: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	KMALLOC(newsav, struct secasvar *, sizeof(struct secasvar));
	if (newsav == NULL) {
		printf("key_newsa: No more memory.\n");
		msg0->sadb_msg_errno = ENOBUFS;
		return NULL;
	}
	bzero((caddr_t)newsav, sizeof(struct secasvar));

	switch (msg0->sadb_msg_type) {
	case SADB_GETSPI:
		newsav->spi = 0;

		/* sync sequence number */
		if (msg0->sadb_msg_seq == 0)
			newsav->seq =
				(acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
		else
			newsav->seq = msg0->sadb_msg_seq;
		break;

	case SADB_ADD:
		/* sanity check */
		if (mhp[SADB_EXT_SA] == NULL) {
			KFREE(newsav);
			printf("key_newsa: invalid message is passed.\n");
			msg0->sadb_msg_errno = EINVAL;
			return NULL;
		}
		newsav->spi = ((struct sadb_sa *)mhp[SADB_EXT_SA])->sadb_sa_spi;
		newsav->seq = msg0->sadb_msg_seq;
		break;
	default:
		KFREE(newsav);
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	/* copy sav values */
	if (msg0->sadb_msg_type != SADB_GETSPI && key_setsaval(newsav, mhp)) {
		KFREE(newsav);
		/* msg0->sadb_msg_errno is set at key_setsaval. */
		return NULL;
	}

	/* reset tick */
	newsav->tick = 0;

	newsav->pid = msg0->sadb_msg_pid;

	/* add to satree */
	newsav->sah = sah;
	newsav->refcnt = 1;
	newsav->state = SADB_SASTATE_LARVAL;
	LIST_INSERT_HEAD(&sah->savtree[SADB_SASTATE_LARVAL], newsav, chain);

	return newsav;
}

/*
 * free() SA variable entry.
 */
static void
key_delsav(sav)
	struct secasvar *sav;
{
	/* sanity check */
	if (sav == NULL)
		panic("key_delsav: NULL pointer is passed.\n");

	if (sav->refcnt > 0) return; /* can't free */

	/* remove from SA header */
	if (__LIST_CHAINED(sav))
		LIST_REMOVE(sav, chain);

	if (sav->key_auth != NULL)
		KFREE(sav->key_auth);
	if (sav->key_enc != NULL)
		KFREE(sav->key_enc);
	if (sav->replay != NULL) {
		if (sav->replay->bitmap != NULL)
			KFREE(sav->replay->bitmap);
		KFREE(sav->replay);
	}
	if (sav->lft_c != NULL)
		KFREE(sav->lft_c);
	if (sav->lft_h != NULL)
		KFREE(sav->lft_h);
	if (sav->lft_s != NULL)
		KFREE(sav->lft_s);
	if (sav->iv != NULL)
		KFREE(sav->iv);
#if notyet
	if (sav->misc1 != NULL)
		KFREE(sav->misc1);
	if (sav->misc2 != NULL)
		KFREE(sav->misc2);
	if (sav->misc3 != NULL)
		KFREE(sav->misc3);
#endif

	sav->sah = NULL;
		/* XXX for making sure.  See key_checkrequest(),
		 * Refcnt may be suspicious. */

	KFREE(sav);

	return;
}

/*
 * search SAD.
 * OUT:
 *	NULL	: not found
 *	others	: found, pointer to a SA.
 */
static struct secashead *
key_getsah(saidx)
	struct secasindex *saidx;
{
	struct secashead *sah;

	__LIST_FOREACH(sah, &sahtree, chain) {
		if (sah->state == SADB_SASTATE_DEAD)
			continue;
		if (key_cmpsaidx_exactly(&sah->saidx, saidx))
			return(sah);
	}

	return NULL;
}

/*
 * check not to be duplicated SPI.
 * NOTE: this function is too slow due to searching all SAD.
 * OUT:
 *	NULL	: not found
 *	others	: found, pointer to a SA.
 */
static struct secasvar *
key_checkspidup(saidx, spi)
	struct secasindex *saidx;
	u_int32_t spi;
{
	struct secashead *sah;
	struct secasvar *sav;

	/* check address family */
	if (saidx->src.ss_family != saidx->src.ss_family) {
		printf("key_checkspidup: address family mismatched.\n");
		return NULL;
	}

	/* check all SAD */
	__LIST_FOREACH(sah, &sahtree, chain) {
		if (!key_ismyaddr(sah->saidx.dst.ss_family,
		                  _INADDRBYSA(&sah->saidx.dst)))
			continue;
		sav = key_getsavbyspi(sah, spi);
		if (sav != NULL)
			return sav;
	}

	return NULL;
}

/*
 * search SAD litmited alive SA, protocol, SPI.
 * OUT:
 *	NULL	: not found
 *	others	: found, pointer to a SA.
 */
static struct secasvar *
key_getsavbyspi(sah, spi)
	struct secashead *sah;
	u_int32_t spi;
{
	struct secasvar *sav;
	u_int stateidx, state;

	/* search all status */
	for (stateidx = 0;
	     stateidx < _ARRAYLEN(saorder_state_alive);
	     stateidx++) {

		state = saorder_state_alive[stateidx];
		__LIST_FOREACH(sav, &sah->savtree[state], chain) {

			/* sanity check */
			if (sav->state != state) {
				printf("key_getsavbyspi: "
					"invalid sav->state "
					"(queue: %d SA: %d)\n",
					state, sav->state);
				continue;
			}

			if (sav->spi == spi)
				return sav;
		}
	}

	return NULL;
}

/*
 * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
 * You must update these if need.
 * OUT:	0:	success.
 *	1:	failure. set errno to (mhp[0])->sadb_msg_errno.
 */
static int
key_setsaval(sav, mhp)
	struct secasvar *sav;
	caddr_t *mhp;
{
	struct sadb_msg *msg0;
	int error = 0;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL)
		panic("key_setsaval: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	/* initialization */
	sav->replay = NULL;
	sav->key_auth = NULL;
	sav->key_enc = NULL;
	sav->iv = NULL;
	sav->lft_c = NULL;
	sav->lft_h = NULL;
	sav->lft_s = NULL;

	/* SA */
	if (mhp[SADB_EXT_SA] != NULL) {
		struct sadb_sa *sa0 = (struct sadb_sa *)mhp[SADB_EXT_SA];

		sav->alg_auth = sa0->sadb_sa_auth;
		sav->alg_enc = sa0->sadb_sa_encrypt;
		sav->flags = sa0->sadb_sa_flags;

		/* replay window */
		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
			KMALLOC(sav->replay, struct secreplay *,
				sizeof(struct secreplay));
			if (sav->replay == NULL) {
				printf("key_setsaval: No more memory.\n");
				error = ENOBUFS;
				goto err;
			}
			bzero(sav->replay, sizeof(struct secreplay));

			if ((sav->replay->wsize = sa0->sadb_sa_replay) != 0) {
				KMALLOC(sav->replay->bitmap, caddr_t,
					sav->replay->wsize);
				if (sav->replay->bitmap == NULL) {
					printf("key_setsaval: "
					       "No more memory.\n");
					error = ENOBUFS;
					goto err;
				}
				bzero(sav->replay->bitmap, sa0->sadb_sa_replay);
			}
		}
	}

	/* Authentication keys */
	if (mhp[SADB_EXT_KEY_AUTH] != NULL) {
		struct sadb_key *key0;
		u_int len;

		key0 = (struct sadb_key *)mhp[SADB_EXT_KEY_AUTH];
		len = PFKEY_UNUNIT64(key0->sadb_key_len);

		error = 0;
		if (len < sizeof(struct sadb_key))
			error = EINVAL;
		switch (msg0->sadb_msg_satype) {
		case SADB_SATYPE_AH:
		case SADB_SATYPE_ESP:
			if (len == sizeof(struct sadb_key)
			 && sav->alg_auth != SADB_AALG_NULL) {
				error = EINVAL;
			}
			break;
		case SADB_X_SATYPE_IPCOMP:
			error = EINVAL;
			break;
		default:
			error = EINVAL;
			break;
		}
		if (error) {
			printf("key_setsaval: invalid key_auth values.\n");
			goto err;
		}

		KEY_NEWBUF(sav->key_auth, struct sadb_key *, key0, len);
		if (sav->key_auth == NULL) {
			printf("key_setsaval: No more memory.\n");
			error = ENOBUFS;
			goto err;
		}

		/* make length shift up for kernel*/
		sav->key_auth->sadb_key_len = len;
	}

	/* Encryption key */
	if (mhp[SADB_EXT_KEY_ENCRYPT] != NULL) {
		struct sadb_key *key0;
		u_int len;

		key0 = (struct sadb_key *)mhp[SADB_EXT_KEY_ENCRYPT];
		len = PFKEY_UNUNIT64(key0->sadb_key_len);

		error = 0;
		if (len < sizeof(struct sadb_key))
			error = EINVAL;
		switch (msg0->sadb_msg_satype) {
		case SADB_SATYPE_ESP:
			if (len == sizeof(struct sadb_key)
			 && sav->alg_enc != SADB_EALG_NULL) {
				error = EINVAL;
			}
			break;
		case SADB_SATYPE_AH:
			error = EINVAL;
			break;
		case SADB_X_SATYPE_IPCOMP:
			break;
		default:
			error = EINVAL;
			break;
		}
		if (error) {
			printf("key_setsatval: invalid key_enc value.\n");
			goto err;
		}

		KEY_NEWBUF(sav->key_enc, struct sadb_key *, key0, len);
		if (sav->key_enc == NULL) {
			printf("key_setsaval: No more memory.\n");
			error = ENOBUFS;
			goto err;
		}

		/* make length shift up for kernel*/
		sav->key_enc->sadb_key_len = len;
	}

	/* set iv */
	sav->ivlen = 0;

	switch (msg0->sadb_msg_satype) {
	case SADB_SATYPE_ESP:
#ifdef IPSEC_ESP
	    {
		struct esp_algorithm *algo;

		algo = &esp_algorithms[sav->alg_enc];
		if (algo && algo->ivlen)
			sav->ivlen = (*algo->ivlen)(sav);
		KMALLOC(sav->iv, caddr_t, sav->ivlen);
		if (sav->iv == 0) {
			printf("key_setsaval: No more memory.\n");
			error = ENOBUFS;
			goto err;
		}
		/* initialize ? */
		break;
	    }
#else
		break;
#endif
	case SADB_SATYPE_AH:
		break;
	default:
		printf("key_setsaval: invalid SA type.\n");
		error = EINVAL;
		goto err;
	}

	/* reset tick */
	sav->tick = 0;

	/* make lifetime for CURRENT */
    {
	struct timeval tv;

	KMALLOC(sav->lft_c, struct sadb_lifetime *,
		sizeof(struct sadb_lifetime));
	if (sav->lft_c == NULL) {
		printf("key_setsaval: No more memory.\n");
		error = ENOBUFS;
		goto err;
	}

	microtime(&tv);

	sav->lft_c->sadb_lifetime_len =
		PFKEY_UNIT64(sizeof(struct sadb_lifetime));
	sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
	sav->lft_c->sadb_lifetime_allocations = 0;
	sav->lft_c->sadb_lifetime_bytes = 0;
	sav->lft_c->sadb_lifetime_addtime = tv.tv_sec;
	sav->lft_c->sadb_lifetime_usetime = 0;
    }

	/* lifetimes for HARD and SOFT */
    {
	struct sadb_lifetime *lft0;

	lft0 = (struct sadb_lifetime *)mhp[SADB_EXT_LIFETIME_HARD];
	if (lft0 != NULL) {
		KEY_NEWBUF(sav->lft_h, struct sadb_lifetime *,
		           lft0, sizeof(*lft0));
		if (sav->lft_h == NULL) {
			printf("key_setsaval: No more memory.\n");
			error = ENOBUFS;
			goto err;
		}
		/* to be initialize ? */
	}

	lft0 = (struct sadb_lifetime *)mhp[SADB_EXT_LIFETIME_SOFT];
	if (lft0 != NULL) {
		KEY_NEWBUF(sav->lft_s, struct sadb_lifetime *,
		           lft0, sizeof(*lft0));
		if (sav->lft_s == NULL) {
			printf("key_setsaval: No more memory.\n");
			error = ENOBUFS;
			goto err;
		}
		/* to be initialize ? */
	}
    }

	msg0->sadb_msg_errno = 0;
	return 0;

    err:
	/* initialization */
	if (sav->replay != NULL) {
		if (sav->replay->bitmap != NULL)
			KFREE(sav->replay->bitmap);
		KFREE(sav->replay);
	}
	if (sav->key_auth != NULL)
		KFREE(sav->key_auth);
	if (sav->key_enc != NULL)
		KFREE(sav->key_enc);
	if (sav->iv != NULL)
		KFREE(sav->iv);
	if (sav->lft_c != NULL)
		KFREE(sav->lft_c);
	if (sav->lft_h != NULL)
		KFREE(sav->lft_h);
	if (sav->lft_s != NULL)
		KFREE(sav->lft_s);

	msg0->sadb_msg_errno = error;
	return 1;
}

/*
 * get message buffer length.
 */
static u_int
key_getmsglen(sav)
	struct secasvar *sav;
{
	int len = sizeof(struct sadb_msg);

	len += sizeof(struct sadb_sa);
	len += (sizeof(struct sadb_address)
		+ PFKEY_ALIGN8(_SALENBYAF(sav->sah->saidx.src.ss_family)));
	len += (sizeof(struct sadb_address)
		+ PFKEY_ALIGN8(_SALENBYAF(sav->sah->saidx.dst.ss_family)));

	if (sav->key_auth != NULL)
		len += sav->key_auth->sadb_key_len;
	if (sav->key_enc != NULL)
		len += sav->key_enc->sadb_key_len;

	if (sav->lft_c != NULL)
		len += sizeof(struct sadb_lifetime);
	if (sav->lft_h != NULL)
		len += sizeof(struct sadb_lifetime);
	if (sav->lft_s != NULL)
		len += sizeof(struct sadb_lifetime);

	return len;
}

/*
 * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
 * OUT:	0:	valid
 *	other:	errno
 */
static int
key_mature(sav)
	struct secasvar *sav;
{
	int mature;
	int checkmask = 0;	/* 2^0: ealg  2^1: aalg  2^2: calg */
	int mustmask = 0;	/* 2^0: ealg  2^1: aalg  2^2: calg */

	mature = 0;

	/* check SPI value */
	if (ntohl(sav->spi) >= 0 && ntohl(sav->spi) <= 255) {
		printf("key_mature: illegal range of SPI %d.\n", sav->spi);
		return EINVAL;
	}

	/* check satype */
	switch (sav->sah->saidx.proto) {
	case IPPROTO_ESP:
		/* check flags */
		if ((sav->flags & SADB_X_EXT_OLD)
		 && (sav->flags & SADB_X_EXT_DERIV)) {
			printf("key_mature: "
				"invalid flag (derived) given to old-esp.\n");
			return EINVAL;
		}
		checkmask = 3;
		mustmask = 1;
		break;
	case IPPROTO_AH:
		/* check flags */
		if (sav->flags & SADB_X_EXT_DERIV) {
			printf("key_mature: "
				"invalid flag (derived) given to AH SA.\n");
			return EINVAL;
		}
		if (sav->alg_enc != SADB_EALG_NONE) {
			printf("key_mature: "
				"protocol and algorithm mismated.\n");
			return(EINVAL);
		}
		checkmask = 2;
		mustmask = 2;
		break;
	default:
		printf("key_mature: Invalid satype.\n");
		return EPROTONOSUPPORT;
	}

	/* check authentication algorithm */
	if ((checkmask & 2) != 0) {
		struct ah_algorithm *algo;
		int keylen;

		/* XXX: should use algorithm map to check. */
		switch (sav->alg_auth) {
		case SADB_AALG_NONE:
		case SADB_AALG_MD5HMAC:
		case SADB_AALG_SHA1HMAC:
		case SADB_AALG_MD5:
		case SADB_AALG_SHA:
		case SADB_AALG_NULL:
			break;
		default:
			printf("key_mature: "
				"unknown authentication algorithm.\n");
			return EINVAL;
		}

		/* algorithm-dependent check */
		algo = &ah_algorithms[sav->alg_auth];

		if (sav->key_auth)
			keylen = sav->key_auth->sadb_key_bits;
		else
			keylen = 0;
		if (keylen < algo->keymin || algo->keymax < keylen) {
			printf("key_mature: invalid AH key length %d "
				"(%d-%d allowed)\n", keylen,
				algo->keymin, algo->keymax);
			return EINVAL;
		}

		if (algo->mature) {
			if ((*algo->mature)(sav)) {
				/* message generated in per-algorithm function*/
				return EINVAL;
			} else
				mature = SADB_SATYPE_AH;
		}

		if ((mustmask & 2) != 0 &&  mature != SADB_SATYPE_AH)
			return EINVAL;
	}

	/* check encryption algorithm */
	if ((checkmask & 1) != 0) {
#ifdef IPSEC_ESP
		struct esp_algorithm *algo;
		int keylen;

		switch (sav->alg_enc) {
		case SADB_EALG_NONE:
		case SADB_EALG_DESCBC:
		case SADB_EALG_3DESCBC:
		case SADB_EALG_NULL:
		case SADB_EALG_BLOWFISHCBC:
		case SADB_EALG_CAST128CBC:
		case SADB_EALG_RC5CBC:
			break;
		default:
			printf("key_mature: unknown encryption algorithm.\n");
			return(EINVAL);
		}

		/* algorithm-dependent check */
		algo = &esp_algorithms[sav->alg_enc];

		if (sav->key_enc)
			keylen = sav->key_enc->sadb_key_bits;
		else
			keylen = 0;
		if (keylen < algo->keymin || algo->keymax < keylen) {
			printf("key_mature: invalid ESP key length %d "
				"(%d-%d allowed)\n", keylen,
				algo->keymin, algo->keymax);
			return EINVAL;
		}

		if (algo->mature) {
			if ((*algo->mature)(sav)) {
				/* message generated in per-algorithm function*/
				return EINVAL;
			} else
				mature = SADB_SATYPE_ESP;
		}

		if ((mustmask & 1) != 0 &&  mature != SADB_SATYPE_ESP)
			return EINVAL;
#else
		printf("key_mature: ESP not supported in this configuration\n");
		return EINVAL;
#endif
	}

	key_sa_chgstate(sav, SADB_SASTATE_MATURE);

	return 0;
}

/*
 * subroutine for SADB_GET and SADB_DUMP.
 * the buf must be allocated sufficent space.
 */
static u_int
key_setdumpsa(newmsg, sav, type, satype, seq, pid)
	struct sadb_msg *newmsg;
	struct secasvar *sav;
	u_int8_t type, satype;
	u_int32_t seq, pid;
{
	u_int tlen;
	caddr_t p;
	int i;

	tlen = key_getmsglen(sav);

	p = key_setsadbmsg((caddr_t)newmsg, type, tlen,
	                   satype, seq, pid,
	                   sav->sah->saidx.mode, sav->refcnt);

	for (i = 1; i <= SADB_EXT_MAX; i++) {
		switch (i) {
		case SADB_EXT_SA:
			p = key_setsadbsa(p, sav);
			break;

		case SADB_EXT_ADDRESS_SRC:
			p = key_setsadbaddr(p,
			      SADB_EXT_ADDRESS_SRC,
			      (struct sockaddr *)&sav->sah->saidx.src,
			      _INALENBYAF(sav->sah->saidx.src.ss_family) << 3,
			      IPSEC_ULPROTO_ANY);
			break;

		case SADB_EXT_ADDRESS_DST:
			p = key_setsadbaddr(p,
			      SADB_EXT_ADDRESS_DST,
			      (struct sockaddr *)&sav->sah->saidx.dst,
			      _INALENBYAF(sav->sah->saidx.dst.ss_family) << 3,
			      IPSEC_ULPROTO_ANY);
			break;

		case SADB_EXT_KEY_AUTH:
		    {
			u_int len;
			if (sav->key_auth == NULL) break;
			len = sav->key_auth->sadb_key_len; /* real length */
			bcopy((caddr_t)sav->key_auth, p, len);
			((struct sadb_ext *)p)->sadb_ext_len = PFKEY_UNIT64(len);
			p += len;
		    }
			break;

		case SADB_EXT_KEY_ENCRYPT:
		    {
			u_int len;
			if (sav->key_enc == NULL) break;
			len = sav->key_enc->sadb_key_len; /* real length */
			bcopy((caddr_t)sav->key_enc, p, len);
			((struct sadb_ext *)p)->sadb_ext_len = PFKEY_UNIT64(len);
			p += len;
		    }
			break;;

		case SADB_EXT_LIFETIME_CURRENT:
			if (sav->lft_c == NULL) break;
			p = key_setsadbext(p, (caddr_t)sav->lft_c);
			break;

		case SADB_EXT_LIFETIME_HARD:
			if (sav->lft_h == NULL) break;
			p = key_setsadbext(p, (caddr_t)sav->lft_h);
			break;

		case SADB_EXT_LIFETIME_SOFT:
			if (sav->lft_s == NULL) break;
			p = key_setsadbext(p, (caddr_t)sav->lft_s);
			break;

		case SADB_EXT_IDENTITY_SRC:
		case SADB_EXT_IDENTITY_DST:
			/* XXX: should we brought from SPD ? */
		case SADB_EXT_SENSITIVITY:
		default:
			break;
		}
	}

	return tlen;
}

/*
 * set data into sadb_msg.
 * `buf' must has been allocated sufficiently.
 */
static caddr_t
key_setsadbmsg(buf, type, tlen, satype, seq, pid, reserved1, reserved2)
	caddr_t buf;
	u_int8_t type, satype;
	u_int16_t tlen;
	u_int32_t seq;
	pid_t pid;
	u_int8_t reserved1;
	u_int8_t reserved2;
{
	struct sadb_msg *p;
	u_int len;

	p = (struct sadb_msg *)buf;
	len = sizeof(struct sadb_msg);

	bzero(p, len);
	p->sadb_msg_version = PF_KEY_V2;
	p->sadb_msg_type = type;
	p->sadb_msg_errno = 0;
	p->sadb_msg_satype = satype;
	p->sadb_msg_len = PFKEY_UNIT64(tlen);
	p->sadb_msg_mode = reserved1;
	p->sadb_msg_reserved = reserved2;
	p->sadb_msg_seq = seq;
	p->sadb_msg_pid = (u_int32_t)pid;

	return(buf + len);
}

/*
 * copy secasvar data into sadb_address.
 * `buf' must has been allocated sufficiently.
 */
static caddr_t
key_setsadbsa(buf, sav)
	caddr_t buf;
	struct secasvar *sav;
{
	struct sadb_sa *p;
	u_int len;

	p = (struct sadb_sa *)buf;
	len = sizeof(struct sadb_sa);

	bzero(p, len);
	p->sadb_sa_len = PFKEY_UNIT64(len);
	p->sadb_sa_exttype = SADB_EXT_SA;
	p->sadb_sa_spi = sav->spi;
	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
	p->sadb_sa_state = sav->state;
	p->sadb_sa_auth = sav->alg_auth;
	p->sadb_sa_encrypt = sav->alg_enc;
	p->sadb_sa_flags = sav->flags;

	return(buf + len);
}

/*
 * set data into sadb_address.
 * `buf' must has been allocated sufficiently.
 */
static caddr_t
key_setsadbaddr(buf, exttype, saddr, prefixlen, ul_proto)
	caddr_t buf;
	u_int16_t exttype;
	struct sockaddr *saddr;
	u_int8_t prefixlen;
	u_int16_t ul_proto;
{
	struct sadb_address *p;
	u_int len;

	p = (struct sadb_address *)buf;
	len = sizeof(struct sadb_address) + PFKEY_ALIGN8(saddr->sa_len);

	bzero(p, len);
	p->sadb_address_len = PFKEY_UNIT64(len);
	p->sadb_address_exttype = exttype;
	p->sadb_address_proto = ul_proto;
	p->sadb_address_prefixlen = prefixlen;
	p->sadb_address_reserved = 0;

	bcopy(saddr, p + 1, saddr->sa_len);

	return(buf + len);
}

/*
 * set data into sadb_ident.
 * `buf' must has been allocated sufficiently.
 */
static caddr_t
key_setsadbident(buf, exttype, idtype, string, stringlen, id)
	caddr_t buf;
	u_int16_t exttype, idtype;
	caddr_t string;
	int stringlen;
	u_int64_t id;
{
	struct sadb_ident *p;
	u_int len;

	p = (struct sadb_ident *)buf;
	len = sizeof(struct sadb_ident) + PFKEY_ALIGN8(stringlen);

	bzero(p, len);
	p->sadb_ident_len = PFKEY_UNIT64(len);
	p->sadb_ident_exttype = exttype;
	p->sadb_ident_type = idtype;
	p->sadb_ident_reserved = 0;
	p->sadb_ident_id = id;

	bcopy(string, p + 1, stringlen);

	return(buf + len);
}

/*
 * copy buffer of any sadb extension type into sadb_ext.
 * assume that sadb_ext_len shifted down >> 3.
 * i.e. shift length up when setting length of extension.
 */
static caddr_t
key_setsadbext(p, ext)
	caddr_t p, ext;
{
	u_int len;

	len = PFKEY_UNUNIT64(((struct sadb_ext *)ext)->sadb_ext_len);

	bcopy(ext, p, len);

	return(p + len);
}

/* %%% utilities */
/*
 * copy a buffer into the new buffer allocated.
 */
static void *
key_newbuf(src, len)
	void *src;
	u_int len;
{
	caddr_t new;

	KMALLOC(new, caddr_t, len);
	if (new == NULL) {
		printf("key_newbuf: No more memory.\n");
		return NULL;
	}
	bcopy((caddr_t)src, new, len);

	return new;
}

/* compare my own address
 * OUT:	1: true, i.e. my address.
 *	0: false
 */
int
key_ismyaddr(family, addr)
	u_int family;
	caddr_t addr;
{
	/* sanity check */
	if (addr == NULL)
		panic("key_ismyaddr: NULL pointer is passed.\n");

	switch (family) {
	case AF_INET:
	{
		struct in_ifaddr *ia;

		for (ia = in_ifaddrhead.tqh_first; ia;
		     ia = ia->ia_link.tqe_next)
			if (bcmp(addr,
			        (caddr_t)&ia->ia_addr.sin_addr,
			        _INALENBYAF(family)) == 0)
				return 1;
	}
		break;
#ifdef INET6
	case AF_INET6:
		return key_ismyaddr6(addr);
#endif
	}

	return 0;
}

#ifdef INET6
/*
 * compare my own address for IPv6.
 * 1: ours
 * 0: other
 * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
 */
#include <netinet6/in6.h>
#include <netinet6/in6_var.h>

static int
key_ismyaddr6(addr)
	caddr_t addr;
{
	struct in6_addr *a = (struct in6_addr *)addr;
	struct in6_ifaddr *ia;

	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
		if (bcmp(addr, (caddr_t)&ia->ia_addr.sin6_addr,
				_INALENBYAF(AF_INET6)) == 0) {
			return 1;
		}

		/* XXX Multicast */
	    {
	  	struct	in6_multi *in6m = 0;

		IN6_LOOKUP_MULTI(*(struct in6_addr *)addr, ia->ia_ifp, in6m);
		if (in6m)
			return 1;
	    }
	}

	/* loopback, just for safety */
	if (IN6_IS_ADDR_LOOPBACK(a))
		return 1;

	/* XXX anycast */

	return 0;
}
#endif /*INET6*/

/*
 * compare two secasindex structure exactly.
 * IN:
 *	saidx0: source, it can be in SAD.
 *	saidx1: object, it can be from SPD.
 * OUT:
 *	1 : equal
 *	0 : not equal
 */
static int
key_cmpsaidx_exactly(saidx0, saidx1)
	struct secasindex *saidx0, *saidx1;
{
	/* sanity */
	if (saidx0 == NULL && saidx1 == NULL)
		return 1;

	if (saidx0 == NULL || saidx1 == NULL)
		return 0;

	if (saidx0->proto != saidx1->proto
	 || saidx0->mode != saidx1->mode)
		return 0;

	if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.ss_len) != 0
	 || bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.ss_len) != 0)
		return 0;

	return 1;
}

/*
 * compare two secasindex structure with consideration mode.
 * don't compare port.
 * IN:
 *	saidx0: source, it is often in SAD.
 *	saidx1: object, it is often from SPD.
 * OUT:
 *	1 : equal
 *	0 : not equal
 */
static int
key_cmpsaidx_withmode(saidx0, saidx1)
	struct secasindex *saidx0, *saidx1;
{
	/* sanity */
	if (saidx0 == NULL && saidx1 == NULL)
		return 1;

	if (saidx0 == NULL || saidx1 == NULL)
		return 0;

	if (saidx0->proto != saidx1->proto
	 || saidx0->src.ss_family != saidx1->src.ss_family
	 || saidx0->dst.ss_family != saidx1->dst.ss_family)
		return 0;

	if (saidx0->mode != IPSEC_MODE_ANY
	 && saidx0->mode != saidx1->mode)
		return 0;

    {
	int sa_len = _INALENBYAF(saidx0->src.ss_family);

	if (bcmp(_INADDRBYSA(&saidx0->src), _INADDRBYSA(&saidx1->src), sa_len)
	 || bcmp(_INADDRBYSA(&saidx0->dst), _INADDRBYSA(&saidx1->dst), sa_len))
		return 0;
    }

	return 1;
}

/*
 * compare two secindex structure exactly.
 * IN:
 *	spidx0: source, it is often in SPD.
 *	spidx1: object, it is often from PFKEY message.
 * OUT:
 *	1 : equal
 *	0 : not equal
 */
static int
key_cmpspidx_exactly(spidx0, spidx1)
	struct secpolicyindex *spidx0, *spidx1;
{
	/* sanity */
	if (spidx0 == NULL && spidx1 == NULL)
		return 1;

	if (spidx0 == NULL || spidx1 == NULL)
		return 0;

	if (spidx0->prefs != spidx1->prefs
	 || spidx0->prefd != spidx1->prefd
	 || spidx0->ul_proto != spidx1->ul_proto)
		return 0;

	if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.ss_len) != 0
	 || bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.ss_len) != 0)
		return 0;

	return 1;
}

/*
 * compare two secindex structure with mask.
 * IN:
 *	spidx0: source, it is often in SPD.
 *	spidx1: object, it is often from IP header.
 * OUT:
 *	1 : equal
 *	0 : not equal
 */
static int
key_cmpspidx_withmask(spidx0, spidx1)
	struct secpolicyindex *spidx0, *spidx1;
{
	/* sanity */
	if (spidx0 == NULL && spidx1 == NULL)
		return 1;

	if (spidx0 == NULL || spidx1 == NULL)
		return 0;

	if (spidx0->src.ss_family != spidx1->src.ss_family
	 || spidx0->dst.ss_family != spidx1->dst.ss_family)
		return 0;

	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
	 && spidx0->ul_proto != spidx1->ul_proto)
		return 0;

	if (_INPORTBYSA(&spidx0->src) != IPSEC_PORT_ANY
	 && _INPORTBYSA(&spidx0->src) != _INPORTBYSA(&spidx1->src))
		return 0;

	if (_INPORTBYSA(&spidx0->dst) != IPSEC_PORT_ANY
	 && _INPORTBYSA(&spidx0->dst) != _INPORTBYSA(&spidx1->dst))
		return 0;

	if (!key_bbcmp(_INADDRBYSA(&spidx0->src),
	               _INADDRBYSA(&spidx1->src),
	               spidx0->prefs))
		return 0;

	if (!key_bbcmp(_INADDRBYSA(&spidx0->dst),
	               _INADDRBYSA(&spidx1->dst),
	               spidx0->prefd))
		return 0;

	/* XXX Do we check other field ?  e.g. flowinfo, scope_id. */

	return 1;
}

/*
 * compare two buffers with mask.
 * IN:
 *	addr1: source
 *	addr2: object
 *	bits:  Number of bits to compare
 * OUT:
 *	1 : equal
 *	0 : not equal
 */
static int
key_bbcmp(p1, p2, bits)
	register caddr_t p1, p2;
	register u_int bits;
{
	u_int8_t mask;

	/* XXX: This could be considerably faster if we compare a word
	 * at a time, but it is complicated on LSB Endian machines */

	/* Handle null pointers */
	if (p1 == NULL || p2 == NULL)
		return (p1 == p2);

	while (bits >= 8) {
		if (*p1++ != *p2++)
			return 0;
		bits -= 8;
	}

	if (bits > 0) {
		mask = ~((1<<(8-bits))-1);
		if ((*p1 & mask) != (*p2 & mask))
			return 0;
	}
	return 1;	/* Match! */
}

/*
 * time handler.
 * scanning SPD and SAD to check status for each entries,
 * and do to remove or to expire.
 */
void
key_timehandler(void)
{
	u_int dir;
	int s;

	s = splnet();	/*called from softclock()*/

	/* SPD */
    {
	struct secpolicy *sp, *nextsp;

	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
		for (sp = LIST_FIRST(&sptree[dir]);
		     sp != NULL;
		     sp = nextsp) {

			nextsp = LIST_NEXT(sp, chain);

			if (sp->state == IPSEC_SPSTATE_DEAD)
				key_freesp(sp);
		}
	}
    }

	/* SAD */
    {
	struct secashead *sah, *nextsah;
	struct secasvar *sav, *nextsav;

	for (sah = LIST_FIRST(&sahtree);
	     sah != NULL;
	     sah = nextsah) {

		nextsah = LIST_NEXT(sah, chain);

		/* if sah has been dead, then delete it and process next sah. */
		if (sah->state == SADB_SASTATE_DEAD) {
			key_delsah(sah);
			continue;
		}

		/* if LARVAL entry doesn't become MATURE, delete it. */
		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]);
		     sav != NULL;
		     sav = nextsav) {

			nextsav = LIST_NEXT(sav, chain);

			sav->tick++;

			if (key_larval_lifetime < sav->tick) {
				key_freesav(sav);
			}
		}

		/*
		 * check MATURE entry to start to send expire message
		 * whether or not.
		 */
		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]);
		     sav != NULL;
		     sav = nextsav) {

			nextsav = LIST_NEXT(sav, chain);

			sav->tick++;

			/* we don't need to check. */
			if (sav->lft_s == NULL)
				continue;

			/* sanity check */
			if (sav->lft_c == NULL) {
				printf("key_timehandler: "
					"There is no CURRENT time, why?\n");
				continue;
			}

			/* compare SOFT lifetime and tick */
			if (sav->lft_s->sadb_lifetime_addtime != 0
			 && sav->lft_s->sadb_lifetime_addtime < sav->tick) {
				/*
				 * check SA to be used whether or not.
				 * when SA hasn't been used, delete it.
				 */
				if (sav->lft_c->sadb_lifetime_usetime == 0) {
					key_sa_chgstate(sav, SADB_SASTATE_DEAD);
					key_freesav(sav);
					sav = NULL;
				} else {
					key_sa_chgstate(sav, SADB_SASTATE_DYING);
					/*
					 * XXX If we keep to send expire
					 * message in the status of
					 * DYING. Do remove below code.
					 */
					key_expire(sav);
				}
			}
			/* check SOFT lifetime by bytes */
			/*
			 * XXX I don't know the way to delete this SA
			 * when new SA is installed.  Caution when it's
			 * installed too big lifetime by time.
			 */
			else if (sav->lft_s->sadb_lifetime_bytes != 0
			      && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {

				key_sa_chgstate(sav, SADB_SASTATE_DYING);
				/*
				 * XXX If we keep to send expire
				 * message in the status of
				 * DYING. Do remove below code.
				 */
				key_expire(sav);
			}
		}

		/* check DYING entry to change status to DEAD. */
		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]);
		     sav != NULL;
		     sav = nextsav) {

			nextsav = LIST_NEXT(sav, chain);

			sav->tick++;

			/* we don't need to check. */
			if (sav->lft_h == NULL)
				continue;

			/* sanity check */
			if (sav->lft_c == NULL) {
				printf("key_timehandler: "
					"There is no CURRENT time, why?\n");
				continue;
			}

			/* compare HARD lifetime and tick */
			if (sav->lft_h->sadb_lifetime_addtime != 0
			 && sav->lft_h->sadb_lifetime_addtime < sav->tick) {
				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
				key_freesav(sav);
				sav = NULL;
			}
			/* check HARD lifetime by bytes */
			else if (sav->lft_h->sadb_lifetime_bytes != 0
			      && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
				key_freesav(sav);
				sav = NULL;
			}
		}

		/* delete entry in DEAD */
		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]);
		     sav != NULL;
		     sav = nextsav) {

			nextsav = LIST_NEXT(sav, chain);

			/* sanity check */
			if (sav->state != SADB_SASTATE_DEAD) {
				printf("key_timehandler: "
					"invalid sav->state "
					"(queue: %d SA: %d): "
					"kill it anyway\n",
					SADB_SASTATE_DEAD, sav->state);
			}

			/*
			 * do not call key_freesav() here.
			 * sav should already be freed, and sav->refcnt
			 * shows other references to sav
			 * (such as from SPD).
			 */
		}
	}
    }

#ifndef IPSEC_NONBLOCK_ACQUIRE
	/* ACQ tree */
    {
	struct secacq *acq, *nextacq;

	for (acq = LIST_FIRST(&acqtree);
	     acq != NULL;
	     acq = nextacq) {

		nextacq = LIST_NEXT(acq, chain);

		acq->tick++;

		if (key_blockacq_lifetime < acq->tick && __LIST_CHAINED(acq)) {
			LIST_REMOVE(acq, chain);
			KFREE(acq);
		}
	}
    }
#endif

	/* initialize random seed */
	if (key_tick_init_random++ > key_int_random) {
		key_tick_init_random = 0;
		key_srandom();
	}

#ifndef IPSEC_DEBUG2
	/* do exchange to tick time !! */
	(void)timeout((void *)key_timehandler, (void *)0, 100);
#endif /* IPSEC_DEBUG2 */

	splx(s);
	return;
}

/*
 * to initialize a seed for random()
 */
void
key_srandom()
{
	struct timeval tv;

	microtime(&tv);
	srandom(tv.tv_usec);

	return;
}

/*
 * map SADB_SATYPE_* to IPPROTO_*.
 * if satype == SADB_SATYPE then satype is mapped to ~0.
 * OUT:
 *	0: invalid satype.
 */
static u_int16_t
key_satype2proto(satype)
	u_int8_t satype;
{
	switch (satype) {
	case SADB_SATYPE_UNSPEC:
		return IPSEC_PROTO_ANY;
	case SADB_SATYPE_AH:
		return IPPROTO_AH;
	case SADB_SATYPE_ESP:
		return IPPROTO_ESP;
	default:
		return 0;
	}
	/* NOTREACHED */
}

/*
 * map IPPROTO_* to SADB_SATYPE_*
 * OUT:
 *	0: invalid protocol type.
 */
static u_int8_t
key_proto2satype(proto)
	u_int16_t proto;
{
	switch (proto) {
	case IPPROTO_AH:
		return SADB_SATYPE_AH;
	case IPPROTO_ESP:
		return SADB_SATYPE_ESP;
	default:
		return 0;
	}
	/* NOTREACHED */
}

/* %%% PF_KEY */
/*
 * SADB_GETSPI processing is to receive
 *	<base, src address, dst address, (SPI range)>
 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
 * tree with the status of LARVAL, and send
 *	<base, SA(*), address(SD)>
 * to the IKMPd.
 *
 * IN:	mhp: pointer to the pointer to each header.
 * OUT:	NULL if fail.
 *	other if success, return pointer to the message to send.
 */
static struct sadb_msg *
key_getspi(mhp)
	caddr_t *mhp;
{
	struct sadb_msg *msg0;
	struct sadb_address *src0, *dst0;
	struct secasindex saidx;
	struct secashead *newsah;
	struct secasvar *newsav;
	u_int8_t proto;
	u_int32_t spi;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL)
		panic("key_getspi: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	if (mhp[SADB_EXT_ADDRESS_SRC] == NULL
	 || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
		printf("key_getspi: invalid message is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
	dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);

	/* map satype to proto */
	if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
		printf("key_getspi: invalid satype is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	KEY_SETSECASIDX(proto, msg0->sadb_msg_mode, src0+1, dst0+1, &saidx);

	/* SPI allocation */
	spi = key_do_getnewspi((struct sadb_spirange *)mhp[SADB_EXT_SPIRANGE],
	                       &saidx);
	if (spi == 0) {
		msg0->sadb_msg_errno = EEXIST;
		return NULL;
	}

	/* get a SA index */
	if ((newsah = key_getsah(&saidx)) == NULL) {

		/* create a new SA index */
		if ((newsah = key_newsah(&saidx)) == NULL) {
			printf("key_getspi: No more memory.\n");
			msg0->sadb_msg_errno = ENOBUFS;
			return NULL;
		}
	}

	/* get a new SA */
	if ((newsav = key_newsav(mhp, newsah)) == NULL) {
		msg0->sadb_msg_errno = ENOBUFS;
		/* XXX don't free new SA index allocated in above. */
		return NULL;
	}

	/* set spi */
	newsav->spi = htonl(spi);

#ifndef IPSEC_NONBLOCK_ACQUIRE
	/* delete the entry in acqtree */
	if (msg0->sadb_msg_seq != 0) {
		struct secacq *acq;
		if ((acq = key_getacqbyseq(msg0->sadb_msg_seq)) != NULL) {
			/* reset counter in order to deletion by timehander. */
			acq->tick = key_blockacq_lifetime;
			acq->count = 0;
		}
    	}
#endif

    {
	struct sadb_msg *newmsg;
	u_int len;
	caddr_t p;

	/* create new sadb_msg to reply. */
	len = sizeof(struct sadb_msg)
	    + sizeof(struct sadb_sa)
	    + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_SRC])
	    + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_DST]);

	KMALLOC(newmsg, struct sadb_msg *, len);
	if (newmsg == NULL) {
		printf("key_getspi: No more memory.\n");
		msg0->sadb_msg_errno = ENOBUFS;
		return NULL;
	}
	bzero((caddr_t)newmsg, len);

	bcopy((caddr_t)mhp[0], (caddr_t)newmsg, sizeof(*msg0));
	newmsg->sadb_msg_seq = newsav->seq;
	newmsg->sadb_msg_errno = 0;
	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
	p = (caddr_t)newmsg + sizeof(*msg0);

      {
	struct sadb_sa *m_sa;
	m_sa = (struct sadb_sa *)p;
	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
	m_sa->sadb_sa_exttype = SADB_EXT_SA;
	m_sa->sadb_sa_spi = htonl(spi);
	p += sizeof(struct sadb_sa);
      }

	p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_SRC]);
	p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_DST]);

	return newmsg;
    }
}

/*
 * allocating new SPI
 * called by key_getspi().
 * OUT:
 *	0:	failure.
 *	others: success.
 */
static u_int32_t
key_do_getnewspi(spirange, saidx)
	struct sadb_spirange *spirange;
	struct secasindex *saidx;
{
	u_int32_t newspi;
	u_int32_t min, max;
	int count = key_spi_trycnt;

	/* set spi range to allocate */
	if (spirange != NULL) {
		min = spirange->sadb_spirange_min;
		max = spirange->sadb_spirange_max;
	} else {
		min = key_spi_minval;
		max = key_spi_maxval;
	}

	if (min == max) {
		if (key_checkspidup(saidx, min) != NULL) {
			printf("key_do_getnewspi: SPI %u exists already.\n", min);
			return 0;
		}

		count--; /* taking one cost. */
		newspi = min;

	} else {

		/* init SPI */
		newspi = 0;

		/* when requesting to allocate spi ranged */
		while (count--) {
			/* generate pseudo-random SPI value ranged. */
			newspi = min + (random() % ( max - min + 1 ));

			if (key_checkspidup(saidx, newspi) == NULL)
				break;
		}

		if (count == 0 || newspi == 0) {
			printf("key_do_getnewspi: to allocate spi is failed.\n");
			return 0;
		}
	}

	/* statistics */
	keystat.getspi_count =
		(keystat.getspi_count + key_spi_trycnt - count) / 2;

	return newspi;
}

/*
 * SADB_UPDATE processing
 * receive
 *   <base, SA, (lifetime(HSC),) address(SD), (address(P),)
 *       key(AE), (identity(SD),) (sensitivity)>
 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
 * and send
 *   <base, SA, (lifetime(HSC),) address(SD), (address(P),)
 *       (identity(SD),) (sensitivity)>
 * to the ikmpd.
 *
 * IN:	mhp: pointer to the pointer to each header.
 * OUT:	NULL if fail.
 *	other if success, return pointer to the message to send.
 */
static struct sadb_msg *
key_update(mhp)
	caddr_t *mhp;
{
	struct sadb_msg *msg0;
	struct sadb_sa *sa0;
	struct sadb_address *src0, *dst0;
	struct secasindex saidx;
	struct secashead *sah;
	struct secasvar *sav;
	u_int16_t proto;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL)
		panic("key_update: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	/* map satype to proto */
	if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
		printf("key_update: invalid satype is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	if (mhp[SADB_EXT_SA] == NULL
	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
	 || (msg0->sadb_msg_satype == SADB_SATYPE_ESP
	  && mhp[SADB_EXT_KEY_ENCRYPT] == NULL)
	 || (msg0->sadb_msg_satype == SADB_SATYPE_AH
	  && mhp[SADB_EXT_KEY_AUTH] == NULL)
	 || (mhp[SADB_EXT_LIFETIME_HARD] != NULL
	  && mhp[SADB_EXT_LIFETIME_SOFT] == NULL)
	 || (mhp[SADB_EXT_LIFETIME_HARD] == NULL
	  && mhp[SADB_EXT_LIFETIME_SOFT] != NULL)) {
		printf("key_update: invalid message is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	sa0 = (struct sadb_sa *)mhp[SADB_EXT_SA];
	src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
	dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);

	KEY_SETSECASIDX(proto, msg0->sadb_msg_mode, src0+1, dst0+1, &saidx);

	/* get a SA header */
	if ((sah = key_getsah(&saidx)) == NULL) {
		printf("key_update: no SA index found.\n");
		msg0->sadb_msg_errno = ENOENT;
		return NULL;
	}

	/* find a SA with sequence number. */
	if ((sav = key_getsavbyseq(sah, msg0->sadb_msg_seq)) == NULL) {
		printf("key_update: no larval SA with sequence %u exists.\n",
			msg0->sadb_msg_seq);
		msg0->sadb_msg_errno = ENOENT;
		return NULL;
	}

	/* validity check */
	if (sav->sah->saidx.proto != proto) {
		printf("key_update: protocol mismatched (DB=%u param=%u)\n",
			sav->sah->saidx.proto, proto);
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}
	if (sav->spi != sa0->sadb_sa_spi) {
		printf("key_update: SPI mismatched (DB:%u param:%u)\n",
			(u_int32_t)ntohl(sav->spi),
			(u_int32_t)ntohl(sa0->sadb_sa_spi));
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}
	if (sav->pid != msg0->sadb_msg_pid) {
		printf("key_update: pid mismatched (DB:%u param:%u)\n",
			sav->pid, msg0->sadb_msg_pid);
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	/* copy sav values */
	if (key_setsaval(sav, mhp)) {
		key_freesav(sav);
		return NULL;
	}

	/* check SA values to be mature. */
	if ((msg0->sadb_msg_errno = key_mature(sav)) != 0) {
		key_freesav(sav);
		return NULL;
	}

	/*
	 * we must call key_freesav() whenever we leave a function context,
	 * as we did not allocated a new sav (we updated existing sav).
	 */
	key_freesav(sav);
	sav = NULL;

    {
	struct sadb_msg *newmsg;

	/* set msg buf from mhp */
	if ((newmsg = key_getmsgbuf_x1(mhp)) == NULL) {
		printf("key_update: No more memory.\n");
		msg0->sadb_msg_errno = ENOBUFS;
		return NULL;
	}
	return newmsg;
    }
}

/*
 * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
 * only called by key_update().
 * OUT:
 *	NULL	: not found
 *	others	: found, pointer to a SA.
 */
static struct secasvar *
key_getsavbyseq(sah, seq)
	struct secashead *sah;
	u_int32_t seq;
{
	struct secasvar *sav;
	u_int state;

	state = SADB_SASTATE_LARVAL;

	/* search SAD with sequence number ? */
	__LIST_FOREACH(sav, &sah->savtree[state], chain) {

		KEY_CHKSASTATE(state, sav->state, "key_getsabyseq");

		if (sav->seq == seq) {
			sav->refcnt++;
			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
				printf("DP key_getsavbyseq cause "
					"refcnt++:%d SA:%p\n",
					sav->refcnt, sav));
			return sav;
		}
	}

	return NULL;
}

/*
 * SADB_ADD processing
 * add a entry to SA database, when received
 *   <base, SA, (lifetime(HSC),) address(SD), (address(P),)
 *       key(AE), (identity(SD),) (sensitivity)>
 * from the ikmpd,
 * and send
 *   <base, SA, (lifetime(HSC),) address(SD), (address(P),)
 *       (identity(SD),) (sensitivity)>
 * to the ikmpd.
 *
 * IGNORE identity and sensitivity messages.
 *
 * IN:	mhp: pointer to the pointer to each header.
 * OUT:	NULL if fail.
 *	other if success, return pointer to the message to send.
 */
static struct sadb_msg *
key_add(mhp)
	caddr_t *mhp;
{
	struct sadb_msg *msg0;
	struct sadb_sa *sa0;
	struct sadb_address *src0, *dst0;
	struct secasindex saidx;
	struct secashead *newsah;
	struct secasvar *newsav;
	u_int16_t proto;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL)
		panic("key_add: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	/* map satype to proto */
	if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
		printf("key_add: invalid satype is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	if (mhp[SADB_EXT_SA] == NULL
	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
	 || (msg0->sadb_msg_satype == SADB_SATYPE_ESP
	  && mhp[SADB_EXT_KEY_ENCRYPT] == NULL)
	 || (msg0->sadb_msg_satype == SADB_SATYPE_AH
	  && mhp[SADB_EXT_KEY_AUTH] == NULL)
	 || (mhp[SADB_EXT_LIFETIME_HARD] != NULL
	  && mhp[SADB_EXT_LIFETIME_SOFT] == NULL)
	 || (mhp[SADB_EXT_LIFETIME_HARD] == NULL
	  && mhp[SADB_EXT_LIFETIME_SOFT] != NULL)) {
		printf("key_add: invalid message is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	sa0 = (struct sadb_sa *)mhp[SADB_EXT_SA];
	src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
	dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);

	KEY_SETSECASIDX(proto, msg0->sadb_msg_mode, src0+1, dst0+1, &saidx);

	/* get a SA header */
	if ((newsah = key_getsah(&saidx)) == NULL) {

		/* create a new SA header */
		if ((newsah = key_newsah(&saidx)) == NULL) {
			printf("key_add: No more memory.\n");
			msg0->sadb_msg_errno = ENOBUFS;
			return NULL;
		}
	}

	/* create new SA entry. */
	/* We can create new SA only if SPI is differenct. */
	if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
		printf("key_add: SA already exists.\n");
		msg0->sadb_msg_errno = EEXIST;
		return NULL;
	}
	if ((newsav = key_newsav(mhp, newsah)) == NULL)
		return NULL;

	/* check SA values to be mature. */
	if ((msg0->sadb_msg_errno = key_mature(newsav)) != NULL) {
		key_freesav(newsav);
		return NULL;
	}

	/*
	 * don't call key_freesav() here, as we would like to keep the SA
	 * in the database on success.
	 */

    {
	struct sadb_msg *newmsg;

	/* set msg buf from mhp */
	if ((newmsg = key_getmsgbuf_x1(mhp)) == NULL) {
		printf("key_add: No more memory.\n");
		msg0->sadb_msg_errno = ENOBUFS;
		return NULL;
	}

	return newmsg;
    }
}

static struct sadb_msg *
key_getmsgbuf_x1(mhp)
	caddr_t *mhp;
{
	struct sadb_msg *msg0;
	struct sadb_msg *newmsg;
	u_int len;
	caddr_t p;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL)
		panic("key_getmsgbuf_x1: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	/* create new sadb_msg to reply. */
	len = sizeof(struct sadb_msg)
	    + sizeof(struct sadb_sa)
	    + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_SRC])
	    + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_DST])
	    + (mhp[SADB_EXT_LIFETIME_HARD] == NULL
		? 0 : sizeof(struct sadb_lifetime))
	    + (mhp[SADB_EXT_LIFETIME_SOFT] == NULL
		? 0 : sizeof(struct sadb_lifetime));

	KMALLOC(newmsg, struct sadb_msg *, len);
	if (newmsg == NULL)
		return NULL;
	bzero((caddr_t)newmsg, len);

	bcopy((caddr_t)mhp[0], (caddr_t)newmsg, sizeof(*msg0));
	newmsg->sadb_msg_errno = 0;
	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
	p = (caddr_t)newmsg + sizeof(*msg0);

	p = key_setsadbext(p, mhp[SADB_EXT_SA]);
	p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_SRC]);
	p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_DST]);

	if (mhp[SADB_EXT_LIFETIME_HARD] != NULL)
		p = key_setsadbext(p, mhp[SADB_EXT_LIFETIME_HARD]);

	if (mhp[SADB_EXT_LIFETIME_SOFT] != NULL)
		p = key_setsadbext(p, mhp[SADB_EXT_LIFETIME_SOFT]);

	return newmsg;
}

/*
 * SADB_DELETE processing
 * receive
 *   <base, SA(*), address(SD)>
 * from the ikmpd, and set SADB_SASTATE_DEAD,
 * and send,
 *   <base, SA(*), address(SD)>
 * to the ikmpd.
 *
 * IN:	mhp: pointer to the pointer to each header.
 * OUT:	NULL if fail.
 *	other if success, return pointer to the message to send.
 */
static struct sadb_msg *
key_delete(mhp)
	caddr_t *mhp;
{
	struct sadb_msg *msg0;
	struct sadb_sa *sa0;
	struct sadb_address *src0, *dst0;
	struct secasindex saidx;
	struct secashead *sah;
	struct secasvar *sav;
	u_int16_t proto;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL)
		panic("key_delete: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	/* map satype to proto */
	if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
		printf("key_delete: invalid satype is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	if (mhp[SADB_EXT_SA] == NULL
	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
	 || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
		printf("key_delete: invalid message is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}
	sa0 = (struct sadb_sa *)mhp[SADB_EXT_SA];
	src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
	dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);

	KEY_SETSECASIDX(proto, msg0->sadb_msg_mode, src0+1, dst0+1, &saidx);

	/* get a SA header */
	if ((sah = key_getsah(&saidx)) == NULL) {
		printf("key_delete: no SA found.\n");
		msg0->sadb_msg_errno = ENOENT;
		return NULL;
	}

	/* get a SA with SPI. */
	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
	if (sav == NULL) {
		printf("key_delete: no alive SA found.\n");
		msg0->sadb_msg_errno = ENOENT;
		return NULL;
	}

	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
	key_freesav(sav);
	sav = NULL;

    {
	struct sadb_msg *newmsg;
	u_int len;
	caddr_t p;

	/* create new sadb_msg to reply. */
	len = sizeof(struct sadb_msg)
	    + sizeof(struct sadb_sa)
	    + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_SRC])
	    + PFKEY_EXTLEN(mhp[SADB_EXT_ADDRESS_DST]);

	KMALLOC(newmsg, struct sadb_msg *, len);
	if (newmsg == NULL) {
		printf("key_delete: No more memory.\n");
		msg0->sadb_msg_errno = ENOBUFS;
		return NULL;
	}
	bzero((caddr_t)newmsg, len);

	bcopy((caddr_t)mhp[0], (caddr_t)newmsg, sizeof(*msg0));
	newmsg->sadb_msg_errno = 0;
	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
	p = (caddr_t)newmsg + sizeof(*msg0);

	p = key_setsadbext(p, mhp[SADB_EXT_SA]);
	p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_SRC]);
	p = key_setsadbext(p, mhp[SADB_EXT_ADDRESS_DST]);

	return newmsg;
    }
}

/*
 * SADB_GET processing
 * receive
 *   <base, SA(*), address(SD)>
 * from the ikmpd, and get a SP and a SA to respond,
 * and send,
 *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
 *       (identity(SD),) (sensitivity)>
 * to the ikmpd.
 *
 * IN:	mhp: pointer to the pointer to each header.
 * OUT:	NULL if fail.
 *	other if success, return pointer to the message to send.
 */
static struct sadb_msg *
key_get(mhp)
	caddr_t *mhp;
{
	struct sadb_msg *msg0;
	struct sadb_sa *sa0;
	struct sadb_address *src0, *dst0;
	struct secasindex saidx;
	struct secashead *sah;
	struct secasvar *sav;
	u_int16_t proto;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL)
		panic("key_get: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	/* map satype to proto */
	if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
		printf("key_get: invalid satype is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	if (mhp[SADB_EXT_SA] == NULL
	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
	 || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
		printf("key_get: invalid message is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}
	sa0 = (struct sadb_sa *)mhp[SADB_EXT_SA];
	src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
	dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);

	KEY_SETSECASIDX(proto, msg0->sadb_msg_mode, src0+1, dst0+1, &saidx);

	/* get a SA header */
	if ((sah = key_getsah(&saidx)) == NULL) {
		printf("key_get: no SA found.\n");
		msg0->sadb_msg_errno = ENOENT;
		return NULL;
	}

	/* get a SA with SPI. */
	sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
	if (sav == NULL) {
		printf("key_get: no SA with state of mature found.\n");
		msg0->sadb_msg_errno = ENOENT;
		return NULL;
	}

    {
	struct sadb_msg *newmsg;
	u_int len;
	u_int8_t satype;

	/* map proto to satype */
	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
		printf("key_get: there was invalid proto in SAD.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	/* calculate a length of message buffer */
	len = key_getmsglen(sav);

	KMALLOC(newmsg, struct sadb_msg *, len);
	if (newmsg == NULL) {
		printf("key_get: No more memory.\n");
		msg0->sadb_msg_errno = ENOBUFS;
		return NULL;
	}

	/* create new sadb_msg to reply. */
	(void)key_setdumpsa(newmsg, sav, SADB_GET,
	                    satype, msg0->sadb_msg_seq, msg0->sadb_msg_pid);

	return newmsg;
    }
}

/*
 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
 * send
 *   <base, SA, address(SD), (address(P)),
 *       (identity(SD),) (sensitivity,) proposal>
 * to KMD, and expect to receive
 *   <base> with SADB_ACQUIRE if error occured,
 * or
 *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
 * from KMD by PF_KEY.
 *
 * sensitivity is not supported.
 *
 * OUT:
 *    0     : succeed
 *    others: error number
 */
static int
key_acquire(saidx, spidx)
	struct secasindex *saidx;
	struct secpolicyindex *spidx;
{
#ifndef IPSEC_NONBLOCK_ACQUIRE
	struct secacq *newacq;
#endif
	u_int8_t satype;
	int error;

	/* sanity check */
	if (saidx == NULL || spidx == NULL)
		panic("key_acquire: NULL pointer is passed.\n");
	if ((satype = key_proto2satype(saidx->proto)) == 0)
		panic("key_acquire: invalid proto is passed.\n");

#ifndef IPSEC_NONBLOCK_ACQUIRE
	/*
	 * We never do anything about acquirng SA.  There is anather
	 * solution that kernel blocks to send SADB_ACQUIRE message until
	 * getting something message from IKEd.  In later case, to be
	 * managed with ACQUIRING list.
	 */
	/* get a entry to check whether sending message or not. */
	if ((newacq = key_getacq(saidx)) != NULL) {
		if (key_blockacq_count < newacq->count) {
			/* reset counter and do send message. */
			newacq->count = 0;
		} else {
			/* increment counter and do nothing. */
			newacq->count++;
			return 0;
		}
	} else {
		/* make new entry for blocking to send SADB_ACQUIRE. */
		if ((newacq = key_newacq(saidx)) == NULL)
			return ENOBUFS;

		/* add to acqtree */
		LIST_INSERT_HEAD(&acqtree, newacq, chain);
	}
#endif

    {
	struct sadb_msg *newmsg = NULL;
	union sadb_x_ident_id id;
	u_int len;
	caddr_t p;

	/* create new sadb_msg to reply. */
	len = sizeof(struct sadb_msg)
		+ sizeof(struct sadb_address)
		+ PFKEY_ALIGN8(saidx->src.ss_len)
		+ sizeof(struct sadb_address)
		+ PFKEY_ALIGN8(saidx->dst.ss_len)
		+ sizeof(struct sadb_ident)
		+ PFKEY_ALIGN8(spidx->src.ss_len)
		+ sizeof(struct sadb_ident)
		+ PFKEY_ALIGN8(spidx->dst.ss_len)
		+ sizeof(struct sadb_prop)
		+ sizeof(struct sadb_comb); /* XXX to be multiple */

	KMALLOC(newmsg, struct sadb_msg *, len);
	if (newmsg == 0) {
		printf("key_acquire: No more memory.\n");
		return ENOBUFS;
	}
	bzero((caddr_t)newmsg, len);

	newmsg->sadb_msg_version = PF_KEY_V2;
	newmsg->sadb_msg_type = SADB_ACQUIRE;
	newmsg->sadb_msg_errno = 0;
	newmsg->sadb_msg_satype = satype;
	newmsg->sadb_msg_len = PFKEY_UNIT64(len);

#ifndef IPSEC_NONBLOCK_ACQUIRE
	newmsg->sadb_msg_seq = newacq->seq;
#else
	newmsg->sadb_msg_seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
#endif

	newmsg->sadb_msg_pid = 0;
	p = (caddr_t)newmsg + sizeof(struct sadb_msg);

	/* set sadb_address for saidx's. */
	p = key_setsadbaddr(p,
	                    SADB_EXT_ADDRESS_SRC,
	                    (struct sockaddr *)&saidx->src,
	                    _INALENBYAF(saidx->src.ss_family) << 3,
	                    IPSEC_ULPROTO_ANY);
	p = key_setsadbaddr(p,
	                    SADB_EXT_ADDRESS_DST,
	                    (struct sockaddr *)&saidx->dst,
	                    _INALENBYAF(saidx->dst.ss_family) << 3,
	                    IPSEC_ULPROTO_ANY);

	/* set sadb_address for spidx's. */
	id.sadb_x_ident_id_addr.prefix = spidx->prefs;
	id.sadb_x_ident_id_addr.ul_proto = spidx->ul_proto;
	p = key_setsadbident(p,
	                    SADB_EXT_IDENTITY_SRC,
			    SADB_X_IDENTTYPE_ADDR,
	                    (caddr_t)&spidx->src,
			    spidx->src.ss_len,
			    *(u_int64_t *)&id);

	id.sadb_x_ident_id_addr.prefix = spidx->prefd;
	id.sadb_x_ident_id_addr.ul_proto = spidx->ul_proto;
	p = key_setsadbident(p,
	                    SADB_EXT_IDENTITY_DST,
			    SADB_X_IDENTTYPE_ADDR,
	                    (caddr_t)&spidx->dst,
			    spidx->dst.ss_len,
			    *(u_int64_t *)&id);

	/* create proposal extension */
	/* set combination extension */
	/* XXX: to be defined by proposal database */
    {
	struct sadb_prop *prop;
	struct sadb_comb *comb;

	prop = (struct sadb_prop *)p;
	prop->sadb_prop_len = PFKEY_UNIT64(sizeof(*prop) + sizeof(*comb));
		/* XXX to be multiple */
	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
	prop->sadb_prop_replay = 32;	/* XXX be variable ? */
	p += sizeof(struct sadb_prop);

	comb = (struct sadb_comb *)p;
	comb->sadb_comb_auth = SADB_AALG_SHA1HMAC; /* XXX ??? */
	comb->sadb_comb_encrypt = SADB_EALG_DESCBC; /* XXX ??? */
	comb->sadb_comb_flags = 0;
	comb->sadb_comb_auth_minbits = 8; /* XXX */
	comb->sadb_comb_auth_maxbits = 1024; /* XXX */
	comb->sadb_comb_encrypt_minbits = 64; /* XXX */
	comb->sadb_comb_encrypt_maxbits = 64; /* XXX */
	comb->sadb_comb_soft_allocations = 0;
	comb->sadb_comb_hard_allocations = 0;
	comb->sadb_comb_soft_bytes = 0;
	comb->sadb_comb_hard_bytes = 0;
	comb->sadb_comb_soft_addtime = 0;
	comb->sadb_comb_hard_addtime = 0;
	comb->sadb_comb_soft_usetime = 0;
	comb->sadb_comb_hard_usetime = 0;

	p += sizeof(*comb);
    }

	error = key_sendall(newmsg, len);
	if (error != 0)
		printf("key_acquire: key_sendall returned %d\n", error);
	return error;
    }

	return 0;
}

#ifndef IPSEC_NONBLOCK_ACQUIRE
static struct secacq *
key_newacq(saidx)
	struct secasindex *saidx;
{
	struct secacq *newacq;

	/* get new entry */
	KMALLOC(newacq, struct secacq *, sizeof(struct secacq));
	if (newacq == NULL) {
		printf("key_newacq: No more memory.\n");
		return NULL;
	}
	bzero(newacq, sizeof(*newacq));

	/* copy secindex */
	bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
	newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
	newacq->tick = 0;
	newacq->count = 0;

	return newacq;
}

static struct secacq *
key_getacq(saidx)
	struct secasindex *saidx;
{
	struct secacq *acq;

	__LIST_FOREACH(acq, &acqtree, chain) {
		if (key_cmpsaidx_exactly(saidx, &acq->saidx))
			return acq;
	}

	return NULL;
}

static struct secacq *
key_getacqbyseq(seq)
	u_int32_t seq;
{
	struct secacq *acq;

	__LIST_FOREACH(acq, &acqtree, chain) {
		if (acq->seq == seq)
			return acq;
	}

	return NULL;
}
#endif

/*
 * SADB_ACQUIRE processing,
 * in first situation, is receiving
 *   <base>
 * from the ikmpd, and clear sequence of its secasvar entry.
 *
 * In second situation, is receiving
 *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
 * from a user land process, and return
 *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
 * to the socket.
 *
 * IN:	mhp: pointer to the pointer to each header.
 * OUT:	NULL if fail.
 *	other if success, return pointer to the message to send.
 */
static struct sadb_msg *
key_acquire2(mhp)
	caddr_t *mhp;
{
	struct sadb_msg *msg0;
	struct sadb_address *src0, *dst0;
	struct secasindex saidx;
	struct secashead *sah;
	u_int16_t proto;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL)
		panic("key_acquire2: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	/*
	 * Error message from KMd.
	 * We assume that if error was occured in IKEd, the length of PFKEY
	 * message is equal to the size of sadb_msg structure.
	 * We return ~0 even if error occured in this function.
	 */
	if (msg0->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {

#ifndef IPSEC_NONBLOCK_ACQUIRE
		struct secacq *acq;

		/* check sequence number */
		if (msg0->sadb_msg_seq == 0) {
			printf("key_acquire2: must specify sequence number.\n");
			return (struct sadb_msg *)~0;
		}

		if ((acq = key_getacqbyseq(msg0->sadb_msg_seq)) == NULL) {
			printf("key_acquire2: "
				"invalid sequence number is passed.\n");
			return (struct sadb_msg *)~0;
		}

		/* reset acq counter in order to deletion by timehander. */
		acq->tick = key_blockacq_lifetime;
		acq->count = 0;
#endif
		return (struct sadb_msg *)~0;
		/* NOTREACHED */
	}

	/*
	 * This message is from user land.
	 */

	/* map satype to proto */
	if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
		printf("key_acquire2: invalid satype is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	if (mhp[SADB_EXT_ADDRESS_SRC] == NULL
	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
	 || mhp[SADB_EXT_PROPOSAL] == NULL) {
		/* error */
		printf("key_acquire2: invalid message is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}
	src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
	dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);

	KEY_SETSECASIDX(proto, msg0->sadb_msg_mode, src0+1, dst0+1, &saidx);

	/* get a SA index */
	if ((sah = key_getsah(&saidx)) != NULL) {
		printf("key_acquire2: a SA exists already.\n");
		msg0->sadb_msg_errno = EEXIST;
		return NULL;
	}

	msg0->sadb_msg_errno = key_acquire(&saidx, NULL);
	if (msg0->sadb_msg_errno != 0) {
		/* XXX What I do ? */
		printf("key_acquire2: error %d returned "
			"from key_acquire.\n", msg0->sadb_msg_errno);
		return NULL;
	}

    {
	struct sadb_msg *newmsg;
	u_int len;

	/* create new sadb_msg to reply. */
	len = PFKEY_UNUNIT64(msg0->sadb_msg_len);

	KMALLOC(newmsg, struct sadb_msg *, len);
	if (newmsg == NULL) {
		printf("key_acquire2: No more memory.\n");
		msg0->sadb_msg_errno = ENOBUFS;
		return NULL;
	}
	bzero((caddr_t)newmsg, len);

	bcopy(mhp[0], (caddr_t)newmsg, len);

	return newmsg;
    }
}

/*
 * SADB_REGISTER processing.
 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
 * receive
 *   <base>
 * from the ikmpd, and register a socket to send PF_KEY messages,
 * and send
 *   <base, supported>
 * to KMD by PF_KEY.
 * If socket is detached, must free from regnode.
 * OUT:
 *    0     : succeed
 *    others: error number
 */
static struct sadb_msg *
key_register(mhp, so)
	caddr_t *mhp;
	struct socket *so;
{
	struct sadb_msg *msg0;
	struct secreg *reg, *newreg = 0;

	/* sanity check */
	if (mhp == NULL || so == NULL || mhp[0] == NULL)
		panic("key_register: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
	if (msg0->sadb_msg_satype == SADB_SATYPE_UNSPEC)
		goto setmsg;

	/* check whether existing or not */
	__LIST_FOREACH(reg, &regtree[msg0->sadb_msg_satype], chain) {
		if (reg->so == so) {
			printf("key_register: socket exists already.\n");
			msg0->sadb_msg_errno = EEXIST;
			return NULL;
		}
	}

	/* create regnode */
	KMALLOC(newreg, struct secreg *, sizeof(struct secreg));
	if (newreg == NULL) {
		printf("key_register: No more memory.\n");
		msg0->sadb_msg_errno = ENOBUFS;
		return NULL;
	}
	bzero((caddr_t)newreg, sizeof(struct secreg));

	newreg->so = so;
	((struct keycb *)sotorawcb(so))->kp_registered++;

	/* add regnode to regtree. */
	LIST_INSERT_HEAD(&regtree[msg0->sadb_msg_satype], newreg, chain);

  setmsg:
  {
	struct sadb_msg *newmsg;
	struct sadb_supported *sup;
	u_int len, alen, elen;
	caddr_t p;

	/* create new sadb_msg to reply. */
	alen = sizeof(struct sadb_supported)
		+ ((SADB_AALG_MAX - 1) * sizeof(struct sadb_alg));

#ifdef IPSEC_ESP
	elen = sizeof(struct sadb_supported)
		+ ((SADB_EALG_MAX - 1) * sizeof(struct sadb_alg));
#else
	elen = 0;
#endif

	len = sizeof(struct sadb_msg)
		+ alen
		+ elen;

	KMALLOC(newmsg, struct sadb_msg *, len);
	if (newmsg == NULL) {
		printf("key_register: No more memory.\n");
		msg0->sadb_msg_errno = ENOBUFS;
		return NULL;
	}
	bzero((caddr_t)newmsg, len);

	bcopy((caddr_t)mhp[0], (caddr_t)newmsg, sizeof(*msg0));
	newmsg->sadb_msg_errno = 0;
	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
	p = (caddr_t)newmsg + sizeof(*msg0);

	/* for authentication algorithm */
	sup = (struct sadb_supported *)p;
	sup->sadb_supported_len = PFKEY_UNIT64(alen);
	sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
	p += sizeof(*sup);

    {
	int i;
	struct sadb_alg *alg;
	struct ah_algorithm *algo;

	for (i = 1; i < SADB_AALG_MAX; i++) {
		algo = &ah_algorithms[i];
		alg = (struct sadb_alg *)p;
		alg->sadb_alg_id = i;
		alg->sadb_alg_ivlen = 0;
		alg->sadb_alg_minbits = algo->keymin;
		alg->sadb_alg_maxbits = algo->keymax;
		p += sizeof(struct sadb_alg);
	}
    }

#ifdef IPSEC_ESP
	/* for encryption algorithm */
	sup = (struct sadb_supported *)p;
	sup->sadb_supported_len = PFKEY_UNIT64(elen);
	sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
	p += sizeof(*sup);

    {
	int i;
	struct sadb_alg *alg;
	struct esp_algorithm *algo;

	for (i = 1; i < SADB_EALG_MAX; i++) {
		algo = &esp_algorithms[i];

		alg = (struct sadb_alg *)p;
		alg->sadb_alg_id = i;
		if (algo && algo->ivlen) {
			/*
			 * give NULL to get the value preferred by algorithm
			 * XXX SADB_X_EXT_DERIV ?
			 */
			alg->sadb_alg_ivlen = (*algo->ivlen)(NULL);
		} else
			alg->sadb_alg_ivlen = 0;
		alg->sadb_alg_minbits = algo->keymin;
		alg->sadb_alg_maxbits = algo->keymax;
		p += sizeof(struct sadb_alg);
	}
    }
#endif

	return newmsg;
  }
}

/*
 * free secreg entry registered.
 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
 */
void
key_freereg(so)
	struct socket *so;
{
	struct secreg *reg;
	int i;

	/* sanity check */
	if (so == NULL)
		panic("key_freereg: NULL pointer is passed.\n");

	/*
	 * check whether existing or not.
	 * check all type of SA, because there is a potential that
	 * one socket is registered to multiple type of SA.
	 */
	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
		__LIST_FOREACH(reg, &regtree[i], chain) {
			if (reg->so == so
			 && __LIST_CHAINED(reg)) {
				LIST_REMOVE(reg, chain);
				KFREE(reg);
				break;
			}
		}
	}

	return;
}

/*
 * SADB_EXPIRE processing
 * send
 *   <base, SA, lifetime(C and one of HS), address(SD)>
 * to KMD by PF_KEY.
 * NOTE: We send only soft lifetime extension.
 *
 * OUT:	0	: succeed
 *	others	: error number
 */
static int
key_expire(sav)
	struct secasvar *sav;
{
	int s;
	int satype;

	/* XXX: Why do we lock ? */
	s = splnet();	/*called from softclock()*/

	/* sanity check */
	if (sav == NULL)
		panic("key_expire: NULL pointer is passed.\n");
	if (sav->sah == NULL)
		panic("key_expire: Why was SA index in SA NULL.\n");
	if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
		panic("key_expire: invalid proto is passed.\n");

    {
	struct sadb_msg *newmsg = NULL;
	u_int len;
	caddr_t p;
	int error;

	/* create new sadb_msg to reply. */
	len = sizeof(struct sadb_msg)
		+ sizeof(struct sadb_sa)
		+ sizeof(struct sadb_lifetime)
		+ sizeof(struct sadb_lifetime)
		+ sizeof(struct sadb_address)
		+ PFKEY_ALIGN8(sav->sah->saidx.src.ss_len)
		+ sizeof(struct sadb_address)
		+ PFKEY_ALIGN8(sav->sah->saidx.dst.ss_len);

	KMALLOC(newmsg, struct sadb_msg *, len);
	if (newmsg == NULL) {
		printf("key_expire: No more memory.\n");
		splx(s);
		return ENOBUFS;
	}
	bzero((caddr_t)newmsg, len);

	/* set msg header */
	p = key_setsadbmsg((caddr_t)newmsg, SADB_EXPIRE, len,
	                   satype, sav->seq, 0,
	                   sav->sah->saidx.mode, sav->refcnt);

	/* create SA extension */
	p = key_setsadbsa(p, sav);

	/* create lifetime extension */
    {
	struct sadb_lifetime *m_lt = (struct sadb_lifetime *)p;

	m_lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
	m_lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
	m_lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
	m_lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
	m_lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime;
	m_lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime;
	p += sizeof(struct sadb_lifetime);

	/* copy SOFT lifetime extension. */
	bcopy(sav->lft_s, p, sizeof(struct sadb_lifetime));
	p += sizeof(struct sadb_lifetime);
    }

	/* set sadb_address for source */
	p = key_setsadbaddr(p,
	                    SADB_EXT_ADDRESS_SRC,
	                    (struct sockaddr *)&sav->sah->saidx.src,
	                    _INALENBYAF(sav->sah->saidx.src.ss_family) << 3,
	                    IPSEC_ULPROTO_ANY);

	/* set sadb_address for destination */
	p = key_setsadbaddr(p,
	                    SADB_EXT_ADDRESS_DST,
	                    (struct sockaddr *)&sav->sah->saidx.dst,
	                    _INALENBYAF(sav->sah->saidx.dst.ss_family) << 3,
	                    IPSEC_ULPROTO_ANY);

	error = key_sendall(newmsg, len);
	splx(s);
	return error;
    }
}

/*
 * SADB_FLUSH processing
 * receive
 *   <base>
 * from the ikmpd, and free all entries in secastree.
 * and send,
 *   <base>
 * to the ikmpd.
 * NOTE: to do is only marking SADB_SASTATE_DEAD.
 *
 * IN:	mhp: pointer to the pointer to each header.
 * OUT:	NULL if fail.
 *	other if success, return pointer to the message to send.
 */
static struct sadb_msg *
key_flush(mhp)
	caddr_t *mhp;
{
	struct sadb_msg *msg0;
	struct secashead *sah, *nextsah;
	struct secasvar *sav, *nextsav;
	u_int16_t proto;
	u_int8_t state;
	u_int stateidx;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL)
		panic("key_flush: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	/* map satype to proto */
	if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
		printf("key_flush: invalid satype is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	/* no SATYPE specified, i.e. flushing all SA. */
	for (sah = LIST_FIRST(&sahtree);
	     sah != NULL;
	     sah = nextsah) {

		nextsah = LIST_NEXT(sah, chain);

		if (msg0->sadb_msg_satype != SADB_SATYPE_UNSPEC
		 && proto != sah->saidx.proto)
			continue;

		for (stateidx = 0;
		     stateidx < _ARRAYLEN(saorder_state_alive);
		     stateidx++) {

			state = saorder_state_any[stateidx];
			for (sav = LIST_FIRST(&sah->savtree[state]);
			     sav != NULL;
			     sav = nextsav) {

				nextsav = LIST_NEXT(sav, chain);

				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
			}
		}

		sah->state = SADB_SASTATE_DEAD;
	}

    {
	struct sadb_msg *newmsg;
	u_int len;

	/* create new sadb_msg to reply. */
	len = sizeof(struct sadb_msg);

	KMALLOC(newmsg, struct sadb_msg *, len);
	if (newmsg == NULL) {
		printf("key_flush: No more memory.\n");
		msg0->sadb_msg_errno = ENOBUFS;
		return NULL;
	}
	bzero((caddr_t)newmsg, len);

	bcopy((caddr_t)mhp[0], (caddr_t)newmsg, sizeof(*msg0));
	newmsg->sadb_msg_errno = 0;
	newmsg->sadb_msg_len = PFKEY_UNIT64(len);

	return newmsg;
    }
}

/*
 * SADB_DUMP processing
 * dump all entries including status of DEAD in SAD.
 * receive
 *   <base>
 * from the ikmpd, and dump all secasvar leaves
 * and send,
 *   <base> .....
 * to the ikmpd.
 *
 * IN:	mhp: pointer to the pointer to each header.
 * OUT:	error code.  0 on success.
 */
static int
key_dump(mhp, so, target)
	caddr_t *mhp;
	struct socket *so;
	int target;
{
	struct sadb_msg *msg0;
	struct secashead *sah;
	struct secasvar *sav;
	u_int16_t proto;
	u_int stateidx;
	u_int8_t satype;
	u_int8_t state;
	int len, cnt;
	struct sadb_msg *newmsg;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL)
		panic("key_dump: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];

	/* map satype to proto */
	if ((proto = key_satype2proto(msg0->sadb_msg_satype)) == 0) {
		printf("key_dump: invalid satype is passed.\n");
		msg0->sadb_msg_errno = EINVAL;
		return NULL;
	}

	/* count sav entries to be sent to the userland. */
	cnt = 0;
	__LIST_FOREACH(sah, &sahtree, chain) {

		if (msg0->sadb_msg_satype != SADB_SATYPE_UNSPEC
		 && proto != sah->saidx.proto)
			continue;

		for (stateidx = 0;
		     stateidx < _ARRAYLEN(saorder_state_any);
		     stateidx++) {

			state = saorder_state_any[stateidx];
			__LIST_FOREACH(sav, &sah->savtree[state], chain) {
				cnt++;
			}
		}
	}

	if (cnt == 0)
		return ENOENT;

	/* send this to the userland, one at a time. */
	newmsg = NULL;
	__LIST_FOREACH(sah, &sahtree, chain) {

		if (msg0->sadb_msg_satype != SADB_SATYPE_UNSPEC
		 && proto != sah->saidx.proto)
			continue;

		/* map proto to satype */
		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
			printf("key_dump: there was invalid proto in SAD.\n");
			msg0->sadb_msg_errno = EINVAL;
			return NULL;
		}

		for (stateidx = 0;
		     stateidx < _ARRAYLEN(saorder_state_any);
		     stateidx++) {

			state = saorder_state_any[stateidx];
			__LIST_FOREACH(sav, &sah->savtree[state], chain) {

				len = key_getmsglen(sav);
				KMALLOC(newmsg, struct sadb_msg *, len);
				if (newmsg == NULL) {
					printf("key_dump: No more memory.\n");
					return ENOBUFS;
				}
				bzero((caddr_t)newmsg, len);

				--cnt;
				(void)key_setdumpsa(newmsg, sav, SADB_DUMP,
				               satype, cnt, msg0->sadb_msg_pid);

				key_sendup(so, newmsg, len, target);
				KFREE(newmsg);
				newmsg = NULL;
			}
		}
	}

	return 0;
}

/*
 * SADB_X_PROMISC processing
 */
static void
key_promisc(mhp, so)
	caddr_t *mhp;
	struct socket *so;
{
	struct sadb_msg *msg0;
	int olen;

	/* sanity check */
	if (mhp == NULL || mhp[0] == NULL)
		panic("key_promisc: NULL pointer is passed.\n");

	msg0 = (struct sadb_msg *)mhp[0];
	olen = PFKEY_UNUNIT64(msg0->sadb_msg_len);

	if (olen < sizeof(struct sadb_msg)) {
		return;
	} else if (olen == sizeof(struct sadb_msg)) {
		/* enable/disable promisc mode */
		struct keycb *kp;
		int target = 0;

		target = KEY_SENDUP_ONE;

		if (so == NULL) {
			return;
		}
		if ((kp = (struct keycb *)sotorawcb(so)) == NULL) {
			msg0->sadb_msg_errno = EINVAL;
			goto sendorig;
		}
		msg0->sadb_msg_errno = 0;
		if (msg0->sadb_msg_satype == 1 || msg0->sadb_msg_satype == 0) {
			kp->kp_promisc = msg0->sadb_msg_satype;
		} else {
			msg0->sadb_msg_errno = EINVAL;
			goto sendorig;
		}

		/* send the original message back to everyone */
		msg0->sadb_msg_errno = 0;
		target = KEY_SENDUP_ALL;
sendorig:
		key_sendup(so, msg0, PFKEY_UNUNIT64(msg0->sadb_msg_len), target);
	} else {
		/* send packet as is */
		struct sadb_msg *msg;
		int len;

		len = olen - sizeof(struct sadb_msg);
		KMALLOC(msg, struct sadb_msg *, len);
		if (msg == NULL) {
			msg0->sadb_msg_errno = ENOBUFS;
			key_sendup(so, msg0, PFKEY_UNUNIT64(msg0->sadb_msg_len),
				KEY_SENDUP_ONE);	/*XXX*/
		}

		/* XXX if sadb_msg_seq is specified, send to specific pid */
		key_sendup(so, msg, len, KEY_SENDUP_ALL);
		KFREE(msg);
	}
}

/*
 * send message to the socket.
 * OUT:
 *	0	: success
 *	others	: fail
 */
static int
key_sendall(msg, len)
	struct sadb_msg *msg;
	u_int len;
{
	struct secreg *reg;
	int error = 0;

	/* sanity check */
	if (msg == NULL)
		panic("key_sendall: NULL pointer is passed.\n");

	/* search table registerd socket to send a message. */
	__LIST_FOREACH(reg, &regtree[msg->sadb_msg_satype], chain) {
		error = key_sendup(reg->so, msg, len, KEY_SENDUP_ONE);
		if (error != 0) {
			if (error == ENOBUFS)
				printf("key_sendall: No more memory.\n");
			else {
				printf("key_sendall: key_sendup returned %d\n",
					error);
			}
			KFREE(msg);
			return error;
		}
	}

	KFREE(msg);
	return 0;
}

/*
 * parse sadb_msg buffer to process PFKEYv2,
 * and create a data to response if needed.
 * I think to be dealed with mbuf directly.
 * IN:
 *     msgp  : pointer to pointer to a received buffer pulluped.
 *             This is rewrited to response.
 *     so    : pointer to socket.
 * OUT:
 *    length for buffer to send to user process.
 */
int
key_parse(msgp, so, targetp)
	struct sadb_msg **msgp;
	struct socket *so;
	int *targetp;
{
	struct sadb_msg *msg = *msgp, *newmsg = NULL;
	caddr_t mhp[SADB_EXT_MAX + 1];
	u_int orglen;
	int error;

	/* sanity check */
	if (msg == NULL || so == NULL)
		panic("key_parse: NULL pointer is passed.\n");

	KEYDEBUG(KEYDEBUG_KEY_DUMP,
		printf("key_parse: passed sadb_msg\n");
		kdebug_sadb(msg));

	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);

	if (targetp)
		*targetp = KEY_SENDUP_ONE;

	/* check version */
	if (msg->sadb_msg_version != PF_KEY_V2) {
		printf("key_parse: PF_KEY version %u is mismatched.\n",
		    msg->sadb_msg_version);
		return EINVAL;
	}

	/* check type */
	if (msg->sadb_msg_type > SADB_MAX) {
		printf("key_parse: invalid type %u is passed.\n",
		    msg->sadb_msg_type);
		msg->sadb_msg_errno = EINVAL;
		return orglen;
	}

	/* align message. */
	if (key_align(msg, mhp) != 0) {
		msg->sadb_msg_errno = EINVAL;
		return orglen;
	}

	/* check SA type */
	switch (msg->sadb_msg_satype) {
	case SADB_SATYPE_UNSPEC:
		switch (msg->sadb_msg_type) {
		case SADB_GETSPI:
		case SADB_UPDATE:
		case SADB_ADD:
		case SADB_DELETE:
		case SADB_GET:
		case SADB_ACQUIRE:
		case SADB_EXPIRE:
			printf("key_parse: must specify satype "
				"when msg type=%u.\n",
				msg->sadb_msg_type);
			msg->sadb_msg_errno = EINVAL;
			return orglen;
		}
		break;
	case SADB_SATYPE_AH:
	case SADB_SATYPE_ESP:
		switch (msg->sadb_msg_type) {
		case SADB_X_SPDADD:
		case SADB_X_SPDDELETE:
		case SADB_X_SPDGET:
		case SADB_X_SPDDUMP:
		case SADB_X_SPDFLUSH:
			printf("key_parse: illegal satype=%u\n", msg->sadb_msg_type);
			msg->sadb_msg_errno = EINVAL;
			return orglen;
		}
		break;
	case SADB_SATYPE_RSVP:
	case SADB_SATYPE_OSPFV2:
	case SADB_SATYPE_RIPV2:
	case SADB_SATYPE_MIP:
		printf("key_parse: type %u isn't supported.\n",
		    msg->sadb_msg_satype);
		msg->sadb_msg_errno = EOPNOTSUPP;
		return orglen;
	case 1:	/* XXX: What does it do ? */
		if (msg->sadb_msg_type == SADB_X_PROMISC)
			break;
		/*FALLTHROUGH*/
	default:
		printf("key_parse: invalid type %u is passed.\n",
		    msg->sadb_msg_satype);
		msg->sadb_msg_errno = EINVAL;
		return orglen;
	}

	/* check field of upper layer protocol and address family */
	if (mhp[SADB_EXT_ADDRESS_SRC] != NULL
	 && mhp[SADB_EXT_ADDRESS_DST] != NULL) {
		struct sadb_address *src0, *dst0;
		u_int prefix;

		src0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_SRC]);
		dst0 = (struct sadb_address *)(mhp[SADB_EXT_ADDRESS_DST]);

		/* check upper layer protocol */
		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
			printf("key_parse: upper layer protocol mismatched.\n");
			msg->sadb_msg_errno = EINVAL;
			return orglen;
		}

		/* check family */
		if (PFKEY_ADDR_SADDR(src0)->sa_family
		 != PFKEY_ADDR_SADDR(dst0)->sa_family) {
			printf("key_parse: address family mismatched.\n");
			msg->sadb_msg_errno = EINVAL;
			return orglen;
		}

		prefix = _INALENBYAF(PFKEY_ADDR_SADDR(src0)->sa_family) << 3;

		/* check max prefixlen */
		if (prefix < src0->sadb_address_prefixlen
		 || prefix < dst0->sadb_address_prefixlen) {
			printf("key_parse: illegal prefixlen.\n");
			msg->sadb_msg_errno = EINVAL;
			return orglen;
		}

		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
		case AF_INET:
		case AF_INET6:
			break;
		default:
			printf("key_parse: invalid address family.\n");
			msg->sadb_msg_errno = EINVAL;
			return orglen;
		}

		/*
		 * prefixlen == 0 is valid because there can be a case when
		 * all addresses are matched.
		 */
	}

	switch (msg->sadb_msg_type) {
	case SADB_GETSPI:
		if ((newmsg = key_getspi(mhp)) == NULL)
			return orglen;
		if (targetp)
			*targetp = KEY_SENDUP_ALL;
		break;

	case SADB_UPDATE:
		if ((newmsg = key_update(mhp)) == NULL)
			return orglen;
		if (targetp)
			*targetp = KEY_SENDUP_ALL;
		break;

	case SADB_ADD:
		if ((newmsg = key_add(mhp)) == NULL)
			return orglen;
		if (targetp)
			*targetp = KEY_SENDUP_ALL;
		break;

	case SADB_DELETE:
		if ((newmsg = key_delete(mhp)) == NULL)
			return orglen;
		if (targetp)
			*targetp = KEY_SENDUP_ALL;
		break;

	case SADB_GET:
		if ((newmsg = key_get(mhp)) == NULL)
			return orglen;
		break;

	case SADB_ACQUIRE:
		if ((newmsg = key_acquire2(mhp)) == NULL)
			return orglen;

		if (newmsg == (struct sadb_msg *)~0) {
			/*
			 * It's not need to reply because of the message
			 * that was reporting an error occured from the KMd.
			 */
			KFREE(msg);
			return 0;
		}
		break;

	case SADB_REGISTER:
		if ((newmsg = key_register(mhp, so)) == NULL)
			return orglen;
		if (targetp)
			*targetp = KEY_SENDUP_REGISTERED;
		break;

	case SADB_EXPIRE:
		printf("key_parse: why is SADB_EXPIRE received ?\n");
		msg->sadb_msg_errno = EINVAL;
		if (targetp)
			*targetp = KEY_SENDUP_ALL;
		return orglen;

	case SADB_FLUSH:
		if ((newmsg = key_flush(mhp)) == NULL)
			return orglen;
		if (targetp)
			*targetp = KEY_SENDUP_ALL;
		break;

	case SADB_DUMP:
		/* key_dump will call key_sendup() on her own */
		error = key_dump(mhp, so, KEY_SENDUP_ONE);
		if (error) {
			msg->sadb_msg_errno = error;
			return orglen;
		} else {
			KFREE(msg);
			return 0;
		}
	        break;

	case SADB_X_PROMISC:
		/* everything is handled in key_promisc() */
		key_promisc(mhp, so);
		KFREE(msg);
		return 0;	/*nothing to reply*/

	case SADB_X_PCHANGE:
		printf("key_parse: SADB_X_PCHANGE isn't supported.\n");
		msg->sadb_msg_errno = EINVAL;
		return orglen;

	case SADB_X_SPDADD:
		if ((newmsg = key_spdadd(mhp)) == NULL)
			return orglen;
		if (targetp)
			*targetp = KEY_SENDUP_ALL;
	        break;

	case SADB_X_SPDDELETE:
		if ((newmsg = key_spddelete(mhp)) == NULL)
			return orglen;
		if (targetp)
			*targetp = KEY_SENDUP_ALL;
	        break;

	case SADB_X_SPDDUMP:
		/* key_spddump will call key_sendup() on her own */
		error = key_spddump(mhp, so, KEY_SENDUP_ONE);
		if (error) {
			msg->sadb_msg_errno = error;
			return orglen;
		} else {
			KFREE(msg);
			return 0;
		}
	        break;


	case SADB_X_SPDFLUSH:
		if ((newmsg = key_spdflush(mhp)) == NULL)
			return orglen;
		if (targetp)
			*targetp = KEY_SENDUP_ALL;
	        break;

	default:
		msg->sadb_msg_errno = EOPNOTSUPP;
		return orglen;
	}

	/* switch from old sadb_msg to new one if success. */
	KFREE(msg);
	*msgp = newmsg;

	return PFKEY_UNUNIT64((*msgp)->sadb_msg_len);
}

/*
 * set the pointer to each header into message buffer.
 * IN:	msg: pointer to message buffer.
 *	mhp: pointer to the buffer allocated like below:
 *		caddr_t mhp[SADB_EXT_MAX + 1];
 * OUT: 0:
 *      EINVAL:
 */
static int
key_align(msg, mhp)
	struct sadb_msg *msg;
	caddr_t *mhp;
{
	struct sadb_ext *ext;
	int tlen, extlen;
	int i;

	/* sanity check */
	if (msg == NULL || mhp == NULL)
		panic("key_align: NULL pointer is passed.\n");

	/* initialize */
	for (i = 0; i < SADB_EXT_MAX + 1; i++)
		mhp[i] = NULL;

	mhp[0] = (caddr_t)msg;

	tlen = PFKEY_UNUNIT64(msg->sadb_msg_len) - sizeof(struct sadb_msg);
	ext = (struct sadb_ext *)((caddr_t)msg + sizeof(struct sadb_msg));

	while (tlen > 0) {
		/* duplicate check */
		/* XXX Are there duplication either KEY_AUTH or KEY_ENCRYPT ?*/
		if (mhp[ext->sadb_ext_type] != NULL) {
			printf("key_align: duplicate ext_type %u is passed.\n",
				ext->sadb_ext_type);
			return EINVAL;
		}

		/* set pointer */
		switch (ext->sadb_ext_type) {
		case SADB_EXT_SA:
		case SADB_EXT_LIFETIME_CURRENT:
		case SADB_EXT_LIFETIME_HARD:
		case SADB_EXT_LIFETIME_SOFT:
		case SADB_EXT_ADDRESS_SRC:
		case SADB_EXT_ADDRESS_DST:
		case SADB_EXT_ADDRESS_PROXY:
		case SADB_EXT_KEY_AUTH:
			/* must to be chek weak keys. */
		case SADB_EXT_KEY_ENCRYPT:
			/* must to be chek weak keys. */
		case SADB_EXT_IDENTITY_SRC:
		case SADB_EXT_IDENTITY_DST:
		case SADB_EXT_SENSITIVITY:
		case SADB_EXT_PROPOSAL:
		case SADB_EXT_SUPPORTED_AUTH:
		case SADB_EXT_SUPPORTED_ENCRYPT:
		case SADB_EXT_SPIRANGE:
		case SADB_X_EXT_POLICY:
			mhp[ext->sadb_ext_type] = (caddr_t)ext;
			break;
		default:
			printf("key_align: invalid ext_type %u is passed.\n",
				ext->sadb_ext_type);
			return EINVAL;
		}

		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
		tlen -= extlen;
		ext = (struct sadb_ext *)((caddr_t)ext + extlen);
	}

	return 0;
}

void
key_init()
{
	int i;

	bzero((caddr_t)&key_cb, sizeof(key_cb));

	for (i = 0; i < IPSEC_DIR_MAX; i++) {
		LIST_INIT(&sptree[i]);
	}

	LIST_INIT(&sahtree);

	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
		LIST_INIT(&regtree[i]);
	}

#ifndef IPSEC_NONBLOCK_ACQUIRE
	LIST_INIT(&acqtree);
#endif

	/* system default */
	ip4_def_policy.policy = IPSEC_POLICY_NONE;
	ip4_def_policy.refcnt++;	/*never reclaim this*/
#ifdef INET6
	ip6_def_policy.policy = IPSEC_POLICY_NONE;
	ip6_def_policy.refcnt++;	/*never reclaim this*/
#endif

#ifndef IPSEC_DEBUG2
	timeout((void *)key_timehandler, (void *)0, 100);
#endif /*IPSEC_DEBUG2*/

	/* initialize key statistics */
	keystat.getspi_count = 1;

	printf("IPsec: Initialized Security Association Processing.\n");

	return;
}

/*
 * XXX: maybe This function is called after INBOUND IPsec processing.
 *
 * Special check for tunnel-mode packets.
 * We must make some checks for consistency between inner and outer IP header.
 *
 * xxx more checks to be provided
 */
int
key_checktunnelsanity(sav, family, src, dst)
	struct secasvar *sav;
	u_int family;
	caddr_t src;
	caddr_t dst;
{
	/* sanity check */
	if (sav->sah == NULL)
		panic("sav->sah == NULL at key_checktunnelsanity");

	/* XXX: check inner IP header */

	return 1;
}

#if 0
#ifdef __FreeBSD__
#define	hostnamelen	strlen(hostname)
#endif

/*
 * Get FQDN for the host.
 * If the administrator configured hostname (by hostname(1)) without
 * domain name, returns nothing.
 */
static const char *
key_getfqdn()
{
	int i;
	int hasdot;
	static char fqdn[MAXHOSTNAMELEN + 1];

	if (!hostnamelen)
		return NULL;

	/* check if it comes with domain name. */
	hasdot = 0;
	for (i = 0; i < hostnamelen; i++) {
		if (hostname[i] == '.')
			hasdot++;
	}
	if (!hasdot)
		return NULL;

	/* NOTE: hostname may not be NUL-terminated. */
	bzero(fqdn, sizeof(fqdn));
	bcopy(hostname, fqdn, hostnamelen);
	fqdn[hostnamelen] = '\0';
	return fqdn;
}

/*
 * get username@FQDN for the host/user.
 */
static const char *
key_getuserfqdn()
{
	const char *host;
	static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
	struct proc *p = curproc;
	char *q;

	if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
		return NULL;
	if (!(host = key_getfqdn()))
		return NULL;

	/* NOTE: s_login may not be-NUL terminated. */
	bzero(userfqdn, sizeof(userfqdn));
	bcopy(p->p_pgrp->pg_session->s_login, userfqdn, MAXLOGNAME);
	userfqdn[MAXLOGNAME] = '\0';	/* safeguard */
	q = userfqdn + strlen(userfqdn);
	*q++ = '@';
	bcopy(host, q, strlen(host));
	q += strlen(host);
	*q++ = '\0';

	return userfqdn;
}
#endif

/* record data transfer on SA, and update timestamps */
void
key_sa_recordxfer(sav, m)
	struct secasvar *sav;
	struct mbuf *m;
{
	if (!sav)
		panic("key_sa_recordxfer called with sav == NULL");
	if (!m)
		panic("key_sa_recordxfer called with m == NULL");
	if (!sav->lft_c)
		return;

	sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
	/* to check bytes lifetime is done in key_timehandler(). */

	/*
	 * We use the number of packets as the unit of
	 * sadb_lifetime_allocations.  We increment the variable
	 * whenever {esp,ah}_{in,out}put is called.
	 */
	sav->lft_c->sadb_lifetime_allocations++;
	/* XXX check for expires? */

	/*
	 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
	 * in seconds.  HARD and SOFT lifetime are measured by the time
	 * difference (again in seconds) from sadb_lifetime_usetime.
	 *
	 *	usetime
	 *	v     expire   expire
	 * -----+-----+--------+---> t
	 *	<--------------> HARD
	 *	<-----> SOFT
	 */
    {
	struct timeval tv;
	microtime(&tv);
	sav->lft_c->sadb_lifetime_usetime = tv.tv_sec;
	/* XXX check for expires? */
    }

	return;
}

/* dumb version */
void
key_sa_routechange(dst)
	struct sockaddr *dst;
{
	struct secashead *sah;
	struct route *ro;

	__LIST_FOREACH(sah, &sahtree, chain) {
		ro = &sah->sa_route;
		if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
		 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
			RTFREE(ro->ro_rt);
			ro->ro_rt = (struct rtentry *)NULL;
		}
	}

	return;
}

static void
key_sa_chgstate(sav, state)
	struct secasvar *sav;
	u_int8_t state;
{
	if (sav == NULL)
		panic("key_sa_chgstate called with sav == NULL");

	if (sav->state == state)
		return;

	if (__LIST_CHAINED(sav))
		LIST_REMOVE(sav, chain);

	sav->state = state;
	LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
}
OpenPOWER on IntegriCloud