summaryrefslogtreecommitdiff
path: root/sbin/isakmpd/pf_key_v2.c
blob: 9d867604b31d5d7caa712ed899a229ccfcffaffd (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
/*      $OpenBSD: pf_key_v2.c,v 1.90 2001/10/12 15:47:49 ho Exp $  */
/*	$EOM: pf_key_v2.c,v 1.79 2000/12/12 00:33:19 niklas Exp $	*/

/*
 * Copyright (c) 1999, 2000, 2001 Niklas Hallqvist.  All rights reserved.
 * Copyright (c) 1999, 2000, 2001 Angelos D. Keromytis.  All rights reserved.
 * Copyright (c) 2001 Håkan Olsson.  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. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Ericsson Radio Systems.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR 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.
 */

/*
 * This code was written under funding by Ericsson Radio Systems.
 */

#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/queue.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/uio.h>
#include <net/pfkeyv2.h>
#include <netinet/in.h>
#ifdef SADB_X_EXT_FLOW_TYPE
#include <sys/mbuf.h>
#include <netinet/ip_ipsp.h>
#endif
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pwd.h>
#include <errno.h>
#include <bitstring.h>

#include "sysdep.h"

#include "cert.h"
#include "conf.h"
#include "exchange.h"
#include "ipsec.h"
#include "ipsec_num.h"
#include "key.h"
#include "log.h"
#include "pf_key_v2.h"
#include "sa.h"
#include "timer.h"
#include "transport.h"
#include "util.h"

#ifdef USE_KEYNOTE
#include "policy.h"
#endif

#define IN6_IS_ADDR_FULL(a)						\
  ((*(u_int32_t *)(void *)(&(a)->s6_addr[0]) == 0xffff)			\
   && (*(u_int32_t *)(void *)(&(a)->s6_addr[4]) == 0xffff)		\
   && (*(u_int32_t *)(void *)(&(a)->s6_addr[8]) == 0xffff)		\
   && (*(u_int32_t *)(void *)(&(a)->s6_addr[12]) == 0xffff))

#define ADDRESS_MAX sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"

/*
 * PF_KEY v2 always work with 64-bit entities and aligns on 64-bit boundaries.
 */
#define PF_KEY_V2_CHUNK 8
#define PF_KEY_V2_ROUND(x)						\
  (((x) + PF_KEY_V2_CHUNK - 1) & ~(PF_KEY_V2_CHUNK - 1))

/* How many microseconds we will wait for a reply from the PF_KEY socket.  */
#define PF_KEY_REPLY_TIMEOUT 1000

struct pf_key_v2_node {
  TAILQ_ENTRY (pf_key_v2_node) link;
  void *seg;
  size_t sz;
  int cnt;
  u_int16_t type;
  u_int8_t flags;
};

TAILQ_HEAD (pf_key_v2_msg, pf_key_v2_node);

#define PF_KEY_V2_NODE_MALLOCED 1
#define PF_KEY_V2_NODE_MARK 2

/* Used to derive "unique" connection identifiers. */
int connection_seq = 0;

#ifdef KAME
/*
 * KAME requires the sadb_msg_seq of an UPDATE be the same of that of the
 * GETSPI creating the larval SA.
 */
struct pf_key_v2_sa_seq {
  TAILQ_ENTRY (pf_key_v2_sa_seq) link;
  u_int8_t *spi;
  size_t sz;
  u_int8_t proto;
  struct sockaddr *dst;
  int dstlen;
  u_int32_t seq;
};

TAILQ_HEAD (, pf_key_v2_sa_seq) pf_key_v2_sa_seq_map;
#endif

#ifndef KAME
static u_int8_t *pf_key_v2_convert_id (u_int8_t *, int, size_t *, int *);
#endif
static struct pf_key_v2_msg *pf_key_v2_call (struct pf_key_v2_msg *);
static struct pf_key_v2_node *pf_key_v2_find_ext (struct pf_key_v2_msg *,
						  u_int16_t);
static void pf_key_v2_notify (struct pf_key_v2_msg *);
static struct pf_key_v2_msg *pf_key_v2_read (u_int32_t);
static u_int32_t pf_key_v2_seq (void);
static u_int32_t pf_key_v2_write (struct pf_key_v2_msg *);
static int pf_key_v2_remove_conf (char *);
static int pf_key_v2_conf_refhandle (int, char *);
#ifdef SADB_X_ASKPOLICY
static int pf_key_v2_conf_refinc (int, char *);
#endif

/* The socket to use for PF_KEY interactions.  */
static int pf_key_v2_socket;

#ifdef KAME
static int
pf_key_v2_register_sa_seq (u_int8_t *spi, size_t sz, u_int8_t proto,
			   struct sockaddr *dst, int dstlen, u_int32_t seq)
{
  struct pf_key_v2_sa_seq *node = 0;

  node = malloc (sizeof *node);
  if (!node)
    goto cleanup;
  memset (node, '0', sizeof *node);
  node->spi = malloc (sz);
  if (!node->spi)
    goto cleanup;
  node->dst = malloc (dst->sa_len);
  if (!node->spi)
    goto cleanup;
  memcpy (node->dst, dst, dst->sa_len);
  node->dstlen = dst->sa_len;
  memcpy (node->spi, spi, sz);
  node->sz = sz;
  node->proto = proto;
  node->seq = seq;
  TAILQ_INSERT_TAIL (&pf_key_v2_sa_seq_map, node, link);
  return 1;

 cleanup:
  if (node->dst)
    free (node->dst);
  if (node)
    free (node);
  return 0;
}

static u_int32_t
pf_key_v2_seq_by_sa (u_int8_t *spi, size_t sz, u_int8_t proto,
		     struct sockaddr *dst, int dstlen)
{
  struct pf_key_v2_sa_seq *node;

  for (node = TAILQ_FIRST (&pf_key_v2_sa_seq_map); node;
       node = TAILQ_NEXT (node, link))
    if (node->proto == proto
	&& node->sz == sz && memcmp (node->spi, spi, sz) == 0
	&& node->dstlen == dst->sa_len
	&& memcmp (node->dst, dst, dst->sa_len) == 0)
      return node->seq;
  return 0;
}
#endif

static struct pf_key_v2_msg *
pf_key_v2_msg_new (struct sadb_msg *msg, int flags)
{
  struct pf_key_v2_node *node = 0;
  struct pf_key_v2_msg *ret;

  node = malloc (sizeof *node);
  if (!node)
    goto cleanup;
  ret = malloc (sizeof *ret);
  if (!ret)
    goto cleanup;
  TAILQ_INIT (ret);
  node->seg = msg;
  node->sz = sizeof *msg;
  node->type = 0;
  node->cnt = 1;
  node->flags = flags;
  TAILQ_INSERT_HEAD (ret, node, link);
  return ret;

 cleanup:
  if (node)
    free (node);
  return 0;
}

/* Add a SZ sized segment SEG to the PF_KEY message MSG.  */
static int
pf_key_v2_msg_add (struct pf_key_v2_msg *msg, struct sadb_ext *ext, int flags)
{
  struct pf_key_v2_node *node;

  node = malloc (sizeof *node);
  if (!node)
    return -1;
  node->seg = ext;
  node->sz = ext->sadb_ext_len * PF_KEY_V2_CHUNK;
  node->type = ext->sadb_ext_type;
  node->flags = flags;
  TAILQ_FIRST (msg)->cnt++;
  TAILQ_INSERT_TAIL (msg, node, link);
  return 0;
}

/* Deallocate the PF_KEY message MSG.  */
static void
pf_key_v2_msg_free (struct pf_key_v2_msg *msg)
{
  struct pf_key_v2_node *np;

  np = TAILQ_FIRST (msg);
  while (np)
    {
      TAILQ_REMOVE (msg, np, link);
      if (np->flags & PF_KEY_V2_NODE_MALLOCED)
	free (np->seg);
      free (np);
      np = TAILQ_FIRST (msg);
    }
  free (msg);
}

/* Just return a new sequence number.  */
static u_int32_t
pf_key_v2_seq (void)
{
  static u_int32_t seq = 0;

  return ++seq;
}

/*
 * Read a PF_KEY packet with SEQ as the sequence number, looping if necessary.
 * If SEQ is zero just read the first message we see, otherwise we queue
 * messages up untile both the PID and the sequence number match.
 */
static struct pf_key_v2_msg *
pf_key_v2_read (u_int32_t seq)
{
  ssize_t n;
  u_int8_t *buf = 0;
  struct pf_key_v2_msg *ret = 0;
  struct sadb_msg *msg;
  struct sadb_msg hdr;
  struct sadb_ext *ext;
  struct timeval tv;
  fd_set *fds;

  while (1)
    {
      /*
       * If this is a read of a reply we should actually expect the reply to
       * get lost as PF_KEY is an unreliable service per the specs.
       * Currently we do this by setting a short timeout, and if it is not
       * readable in that time, we fail the read.
       */
      if (seq)
	{
	  fds = calloc (howmany (pf_key_v2_socket + 1, NFDBITS),
			sizeof (fd_mask));
	  if (!fds)
	    {
	      log_error ("pf_key_v2_read: calloc (%d, %d) failed",
			 howmany (pf_key_v2_socket + 1, NFDBITS),
			 sizeof (fd_mask));
	      goto cleanup;
	    }
	  FD_SET (pf_key_v2_socket, fds);
	  tv.tv_sec = 0;
	  tv.tv_usec = PF_KEY_REPLY_TIMEOUT;
	  n = select (pf_key_v2_socket + 1, fds, 0, 0, &tv);
	  free (fds);
	  if (n == -1)
	    {
	      log_error ("pf_key_v2_read: select (%d, fds, 0, 0, &tv) failed",
			 pf_key_v2_socket + 1);
	      goto cleanup;
	    }
	  if (!n)
	    {
	      log_print ("pf_key_v2_read: no reply from PF_KEY");
	      goto cleanup;
	    }
	}
      n = recv (pf_key_v2_socket, &hdr, sizeof hdr, MSG_PEEK);
      if (n == -1)
	{
	  log_error ("pf_key_v2_read: recv (%d, ...) failed",
		     pf_key_v2_socket);
	  goto cleanup;
	}
      if (n != sizeof hdr)
	{
	  log_error ("pf_key_v2_read: recv (%d, ...) returned short packet "
		     "(%d bytes)",
		     pf_key_v2_socket, n);
	  goto cleanup;
	}

      n = hdr.sadb_msg_len * PF_KEY_V2_CHUNK;
      buf = malloc (n);
      if (!buf)
	{
	  log_error ("pf_key_v2_read: malloc (%d) failed", n);
	  goto cleanup;
	}

      n = read (pf_key_v2_socket, buf, n);
      if (n == -1)
	{
	  log_error ("pf_key_v2_read: read (%d, ...) failed",
		     pf_key_v2_socket);
	  goto cleanup;
	}

      if ((size_t)n != hdr.sadb_msg_len * PF_KEY_V2_CHUNK)
	{
	  log_print ("pf_key_v2_read: read (%d, ...) returned short packet "
		     "(%d bytes)",
		     pf_key_v2_socket, n);
	  goto cleanup;
	}

      LOG_DBG_BUF ((LOG_SYSDEP, 80, "pf_key_v2_read: msg", buf, n));

      /* We drop all messages that is not what we expect.  */
      msg = (struct sadb_msg *)buf;
      if (msg->sadb_msg_version != PF_KEY_V2
	  || (msg->sadb_msg_pid != 0 && msg->sadb_msg_pid != getpid ()))
	{
	  if (seq)
	    {
	      free (buf);
	      buf = 0;
	      continue;
	    }
	  else
	    {
	      LOG_DBG ((LOG_SYSDEP, 90,
			"pf_key_v2_read:"
			"bad version (%d) or PID (%d, mine is %d), ignored",
			msg->sadb_msg_version, msg->sadb_msg_pid,
			getpid ()));
	      goto cleanup;
	    }
	}

      /* Parse the message.  */
      ret = pf_key_v2_msg_new (msg, PF_KEY_V2_NODE_MALLOCED);
      if (!ret)
	goto cleanup;
      buf = 0;
      for (ext = (struct sadb_ext *)(msg + 1);
	   (u_int8_t *)ext - (u_int8_t *)msg
	     < msg->sadb_msg_len * PF_KEY_V2_CHUNK;
	   ext = (struct sadb_ext *)((u_int8_t *)ext
				     + ext->sadb_ext_len * PF_KEY_V2_CHUNK))
	pf_key_v2_msg_add (ret, ext, 0);

      /* If the message is not the one we are waiting for, queue it up.  */
      if (seq && (msg->sadb_msg_pid != getpid () || msg->sadb_msg_seq != seq))
	{
	  gettimeofday (&tv, 0);
	  timer_add_event ("pf_key_v2_notify",
			   (void (*) (void *))pf_key_v2_notify, ret, &tv);
	  ret = 0;
	  continue;
	}

      return ret;
    }

 cleanup:
  if (buf)
    free (buf);
  if (ret)
    pf_key_v2_msg_free (ret);
  return 0;
}

/* Write the message in PMSG to the PF_KEY socket.  */
u_int32_t
pf_key_v2_write (struct pf_key_v2_msg *pmsg)
{
  struct iovec *iov = 0;
  ssize_t n;
  size_t len;
  int i, cnt = TAILQ_FIRST (pmsg)->cnt;
  char header[80];
  struct sadb_msg *msg = TAILQ_FIRST (pmsg)->seg;
  struct pf_key_v2_node *np = TAILQ_FIRST (pmsg);

  iov = (struct iovec *)malloc (cnt * sizeof *iov);
  if (!iov)
    {
      log_error ("pf_key_v2_write: malloc (%d) failed", cnt * sizeof *iov);
      return 0;
    }

  msg->sadb_msg_version = PF_KEY_V2;
  msg->sadb_msg_errno = 0;
  msg->sadb_msg_reserved = 0;
  msg->sadb_msg_pid = getpid ();
  if (!msg->sadb_msg_seq)
    msg->sadb_msg_seq = pf_key_v2_seq ();

  /* Compute the iovec segments as well as the message length.  */
  len = 0;
  for (i = 0; i < cnt; i++)
    {
      iov[i].iov_base = np->seg;
      len += iov[i].iov_len = np->sz;

      /*
       * XXX One can envision setting specific extension fields, like
       * *_reserved ones here.  For now we require them to be set by the
       * caller.
       */

      np = TAILQ_NEXT (np, link);
    }
  msg->sadb_msg_len = len / PF_KEY_V2_CHUNK;

  for (i = 0; i < cnt; i++)
    {
      sprintf (header, "pf_key_v2_write: iov[%d]", i);
      LOG_DBG_BUF ((LOG_SYSDEP, 80, header, (u_int8_t *)iov[i].iov_base,
		    iov[i].iov_len));
    }

  n = writev (pf_key_v2_socket, iov, cnt);
  if (n == -1)
    {
      log_error ("pf_key_v2_write: writev (%d, %p, %d) failed",
		 pf_key_v2_socket, iov, cnt);
      goto cleanup;
    }
  if ((size_t)n != len)
    {
      log_error ("pf_key_v2_write: writev (%d, ...) returned prematurely (%d)",
		 pf_key_v2_socket, n);
      goto cleanup;
    }
  free (iov);
  return msg->sadb_msg_seq;

 cleanup:
  if (iov)
    free (iov);
  return 0;
}

/*
 * Do a PF_KEY "call", i.e. write a message MSG, read the reply and return
 * it to the caller.
 */
static struct pf_key_v2_msg *
pf_key_v2_call (struct pf_key_v2_msg *msg)
{
  u_int32_t seq;

  seq = pf_key_v2_write (msg);
  if (!seq)
    return 0;
  return pf_key_v2_read (seq);
}

/* Find the TYPE extension in MSG.  Return zero if none found.  */
static struct pf_key_v2_node *
pf_key_v2_find_ext (struct pf_key_v2_msg *msg, u_int16_t type)
{
  struct pf_key_v2_node *ext;

  for (ext = TAILQ_NEXT (TAILQ_FIRST (msg), link); ext;
       ext = TAILQ_NEXT (ext, link))
    if (ext->type == type)
      return ext;
  return 0;
}

/*
 * Open the PF_KEYv2 sockets and return the descriptor used for notifies.
 * Return -1 for failure and -2 if no notifies will show up.
 */
int
pf_key_v2_open (void)
{
  int fd = -1, err;
  struct sadb_msg msg;
  struct pf_key_v2_msg *regmsg = 0, *ret = 0;

  /* Open the socket we use to speak to IPSec. */
  pf_key_v2_socket = -1;
  fd = socket (PF_KEY, SOCK_RAW, PF_KEY_V2);
  if (fd == -1)
    {
      log_error ("pf_key_v2_open: "
		 "socket (PF_KEY, SOCK_RAW, PF_KEY_V2) failed");
      goto cleanup;
    }
  pf_key_v2_socket = fd;

  /* Register it to get ESP and AH acquires from the kernel.  */
  msg.sadb_msg_seq = 0;
  msg.sadb_msg_type = SADB_REGISTER;
  msg.sadb_msg_satype = SADB_SATYPE_ESP;
  regmsg = pf_key_v2_msg_new (&msg, 0);
  if (!regmsg)
    goto cleanup;
  ret = pf_key_v2_call (regmsg);
  pf_key_v2_msg_free (regmsg);
  if (!ret)
    goto cleanup;
  err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
  if (err)
    {
      log_print ("pf_key_v2_open: REGISTER: %s", strerror (err));
      goto cleanup;
    }

  /* XXX Register the accepted transforms.  */

  pf_key_v2_msg_free (ret);
  ret = 0;

  msg.sadb_msg_seq = 0;
  msg.sadb_msg_type = SADB_REGISTER;
  msg.sadb_msg_satype = SADB_SATYPE_AH;
  regmsg = pf_key_v2_msg_new (&msg, 0);
  if (!regmsg)
    goto cleanup;
  ret = pf_key_v2_call (regmsg);
  pf_key_v2_msg_free (regmsg);
  if (!ret)
    goto cleanup;
  err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
  if (err)
    {
      log_print ("pf_key_v2_open: REGISTER: %s", strerror (err));
      goto cleanup;
    }

  /* XXX Register the accepted transforms.  */

  pf_key_v2_msg_free (ret);
  ret = 0;

#ifdef SADB_X_SATYPE_IPCOMP
  msg.sadb_msg_seq = 0;
  msg.sadb_msg_type = SADB_REGISTER;
  msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
  regmsg = pf_key_v2_msg_new (&msg, 0);
  if (!regmsg)
    goto cleanup;
  ret = pf_key_v2_call (regmsg);
  pf_key_v2_msg_free (regmsg);
  if (!ret)
    goto cleanup;
  err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
  if (err)
    {
      log_print ("pf_key_v2_open: REGISTER: %s", strerror (err));
      goto cleanup;
    }

  /* XXX Register the accepted transforms.  */

  pf_key_v2_msg_free (ret);
#endif /* SADB_X_SATYPE_IPCOMP */

#ifdef KAME
  TAILQ_INIT (&pf_key_v2_sa_seq_map);
#endif

  return fd;

 cleanup:
  if (pf_key_v2_socket != -1)
    {
      close (pf_key_v2_socket);
      pf_key_v2_socket = -1;
    }
  if (ret)
    pf_key_v2_msg_free (ret);
  return -1;
}

/*
 * Generate a SPI for protocol PROTO and the source/destination pair given by
 * SRC, SRCLEN, DST & DSTLEN.  Stash the SPI size in SZ.
 */
u_int8_t *
pf_key_v2_get_spi (size_t *sz, u_int8_t proto, struct sockaddr *src,
		   struct sockaddr *dst, u_int32_t seq)
{
  struct sadb_msg msg;
  struct sadb_sa *sa;
  struct sadb_address *addr = 0;
  struct sadb_spirange spirange;
  struct pf_key_v2_msg *getspi = 0, *ret = 0;
  struct pf_key_v2_node *ext;
  u_int8_t *spi = 0;
  int len, err;
#ifdef KAME
  struct sadb_x_sa2 ssa2;
#endif

  msg.sadb_msg_type = SADB_GETSPI;
  switch (proto)
    {
    case IPSEC_PROTO_IPSEC_ESP:
      msg.sadb_msg_satype = SADB_SATYPE_ESP;
      break;
    case IPSEC_PROTO_IPSEC_AH:
      msg.sadb_msg_satype = SADB_SATYPE_AH;
      break;
#ifdef SADB_X_SATYPE_IPCOMP
    case IPSEC_PROTO_IPCOMP:
      msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
      break;
#endif
    default:
      log_print ("pf_key_v2_get_spi: invalid proto %d", proto);
      goto cleanup;
    }

  /* Set the sequence number from the ACQUIRE message. */
  msg.sadb_msg_seq = seq;
  getspi = pf_key_v2_msg_new (&msg, 0);
  if (!getspi)
    goto cleanup;

#ifdef KAME
  memset (&ssa2, 0, sizeof ssa2);
  ssa2.sadb_x_sa2_exttype = SADB_X_EXT_SA2;
  ssa2.sadb_x_sa2_len = sizeof ssa2 / PF_KEY_V2_CHUNK;
  ssa2.sadb_x_sa2_mode = 0;
  if (pf_key_v2_msg_add (getspi, (struct sadb_ext *)&ssa2, 0) == -1)
    goto cleanup;
#endif

  /* Setup the ADDRESS extensions.  */
  len = sizeof (struct sadb_address) + PF_KEY_V2_ROUND (src->sa_len);
  addr = calloc (1, len);
  if (!addr)
    goto cleanup;
  addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
  addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
#ifndef __OpenBSD__
  addr->sadb_address_proto = 0;
  addr->sadb_address_prefixlen = 0;
#endif
  addr->sadb_address_reserved = 0;
  memcpy (addr + 1, src, src->sa_len);
  switch (((struct sockaddr *)(addr + 1))->sa_family)
    {
    case AF_INET:
      ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
      break;
    case AF_INET6:
      ((struct sockaddr_in6 *)(addr + 1))->sin6_port = 0;
      break;
    }
  if (pf_key_v2_msg_add (getspi, (struct sadb_ext *)addr,
			 PF_KEY_V2_NODE_MALLOCED) == -1)
    goto cleanup;
  addr = 0;

  len = sizeof (struct sadb_address) + PF_KEY_V2_ROUND (dst->sa_len);
  addr = calloc (1, len);
  if (!addr)
    goto cleanup;
  addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
  addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
#ifndef __OpenBSD__
  addr->sadb_address_proto = 0;
  addr->sadb_address_prefixlen = 0;
#endif
  addr->sadb_address_reserved = 0;
  memcpy (addr + 1, dst, dst->sa_len);
  switch (((struct sockaddr *)(addr + 1))->sa_family)
    {
    case AF_INET:
      ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
      break;
    case AF_INET6:
      ((struct sockaddr_in6 *)(addr + 1))->sin6_port = 0;
      break;
    }
  if (pf_key_v2_msg_add (getspi, (struct sadb_ext *)addr,
			 PF_KEY_V2_NODE_MALLOCED) == -1)
    goto cleanup;
  addr = 0;

  /* Setup the SPIRANGE extension.  */
  spirange.sadb_spirange_exttype = SADB_EXT_SPIRANGE;
  spirange.sadb_spirange_len = sizeof spirange / PF_KEY_V2_CHUNK;
  spirange.sadb_spirange_min = IPSEC_SPI_LOW;
  spirange.sadb_spirange_max = 0xffffffff;
  spirange.sadb_spirange_reserved = 0;
  if (pf_key_v2_msg_add (getspi, (struct sadb_ext *)&spirange, 0) == -1)
    goto cleanup;

  ret = pf_key_v2_call (getspi);
  pf_key_v2_msg_free (getspi);
  getspi = 0;
  if (!ret)
    goto cleanup;
  err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
  if (err)
    {
      log_print ("pf_key_v2_get_spi: GETSPI: %s", strerror (err));
      goto cleanup;
    }

  ext = pf_key_v2_find_ext (ret, SADB_EXT_SA);
  if (!ext)
    {
      log_print ("pf_key_v2_get_spi: no SA extension found");
      goto cleanup;
    }
  sa = ext->seg;

  /* IPCOMP CPIs are only 16 bits long.  */
  *sz = (proto == IPSEC_PROTO_IPCOMP) ? sizeof (u_int16_t)
    : sizeof sa->sadb_sa_spi;
  spi = malloc (*sz);
  if (!spi)
    goto cleanup;
  /* XXX This is ugly.  */
  if (proto == IPSEC_PROTO_IPCOMP)
    *(u_int16_t *)spi = (u_int16_t)sa->sadb_sa_spi;
  else
    memcpy (spi, &sa->sadb_sa_spi, *sz);

#ifdef KAME
  if (!pf_key_v2_register_sa_seq (spi, *sz, proto, dst, dst->sa_len,
				  ((struct sadb_msg *)(TAILQ_FIRST (ret)->seg))
				  ->sadb_msg_seq))
    goto cleanup;
#endif
  pf_key_v2_msg_free (ret);

  LOG_DBG_BUF ((LOG_SYSDEP, 50, "pf_key_v2_get_spi: spi", spi, *sz));

  return spi;

 cleanup:
  if (spi)
    free (spi);
  if (addr)
    free (addr);
  if (getspi)
    pf_key_v2_msg_free (getspi);
  if (ret)
    pf_key_v2_msg_free (ret);
  return 0;
}

/*
 * Store/update a PF_KEY_V2 security association with full information from the
 * IKE SA and PROTO into the kernel.  INCOMING is set if we are setting the
 * parameters for the incoming SA, and cleared otherwise.
 */
int
pf_key_v2_set_spi (struct sa *sa, struct proto *proto, int incoming,
		   struct sa *isakmp_sa)
{
  struct sadb_msg msg;
  struct sadb_sa ssa;
  struct sadb_lifetime *life = 0;
  struct sadb_address *addr = 0;
  struct sadb_key *key = 0;
  struct sockaddr *src, *dst;
  struct sadb_ident *sid = 0;
#ifndef KAME
  char *pp;
  int idtype;
#endif
  int keylen, hashlen, err;
  struct pf_key_v2_msg *update = 0, *ret = 0;
  struct ipsec_proto *iproto = proto->data;
#if defined (SADB_X_CREDTYPE_NONE) || defined (SADB_X_AUTHTYPE_NONE)
  struct sadb_x_cred *cred;
#endif
  size_t len;
#ifdef KAME
  struct sadb_x_sa2 ssa2;
#endif
#ifdef USE_DEBUG
  char *addr_str;
#endif

  msg.sadb_msg_type = incoming ? SADB_UPDATE : SADB_ADD;
  switch (proto->proto)
    {
    case IPSEC_PROTO_IPSEC_ESP:
      msg.sadb_msg_satype = SADB_SATYPE_ESP;
      keylen = ipsec_esp_enckeylength (proto);
      hashlen = ipsec_esp_authkeylength (proto);

      switch (proto->id)
	{
	case IPSEC_ESP_DES:
	case IPSEC_ESP_DES_IV32:
	case IPSEC_ESP_DES_IV64:
	  ssa.sadb_sa_encrypt = SADB_EALG_DESCBC;
	  break;

	case IPSEC_ESP_3DES:
	  ssa.sadb_sa_encrypt = SADB_EALG_3DESCBC;
	  break;

#ifdef SADB_X_EALG_AES
	case IPSEC_ESP_AES:
	  ssa.sadb_sa_encrypt = SADB_X_EALG_AES;
	  break;
#endif

#ifdef SADB_X_EALG_CAST
	case IPSEC_ESP_CAST:
	  ssa.sadb_sa_encrypt = SADB_X_EALG_CAST;
	  break;
#endif

#ifdef SADB_X_EALG_BLF
	case IPSEC_ESP_BLOWFISH:
	  ssa.sadb_sa_encrypt = SADB_X_EALG_BLF;
	  break;
#endif

	default:
	  LOG_DBG ((LOG_SYSDEP, 50,
		    "pf_key_v2_set_spi: unknown encryption algorithm %d",
		    proto->id));
	  return -1;
	}

      switch (iproto->auth)
	{
	case IPSEC_AUTH_HMAC_MD5:
#ifdef SADB_AALG_MD5HMAC96
	  ssa.sadb_sa_auth = SADB_AALG_MD5HMAC96;
#else
	  ssa.sadb_sa_auth = SADB_AALG_MD5HMAC;
#endif
	  break;

	case IPSEC_AUTH_HMAC_SHA:
#ifdef SADB_AALG_SHA1HMAC96
	  ssa.sadb_sa_auth = SADB_AALG_SHA1HMAC96;
#else
	  ssa.sadb_sa_auth = SADB_AALG_SHA1HMAC;
#endif
	  break;

#ifndef KAME
        case IPSEC_AUTH_HMAC_RIPEMD:
#ifdef SADB_X_AALG_RIPEMD160HMAC96
	  ssa.sadb_sa_auth = SADB_X_AALG_RIPEMD160HMAC96;
#else
	  ssa.sadb_sa_auth = SADB_AALG_RIPEMD160HMAC;
#endif
	  break;
#endif

	case IPSEC_AUTH_DES_MAC:
	case IPSEC_AUTH_KPDK:
	  /* XXX We should be supporting KPDK */
	  LOG_DBG ((LOG_SYSDEP, 50,
		    "pf_key_v2_set_spi: unknown authentication algorithm %d",
		    iproto->auth));
	  return -1;

	default:
	  ssa.sadb_sa_auth = SADB_AALG_NONE;
	}
      break;

    case IPSEC_PROTO_IPSEC_AH:
      msg.sadb_msg_satype = SADB_SATYPE_AH;
      hashlen = ipsec_ah_keylength (proto);
      keylen = 0;

      ssa.sadb_sa_encrypt = SADB_EALG_NONE;
      switch (proto->id)
	{
	case IPSEC_AH_MD5:
#ifdef SADB_AALG_MD5HMAC96
	  ssa.sadb_sa_auth = SADB_AALG_MD5HMAC96;
#else
	  ssa.sadb_sa_auth = SADB_AALG_MD5HMAC;
#endif
	  break;

	case IPSEC_AH_SHA:
#ifdef SADB_AALG_SHA1HMAC96
	  ssa.sadb_sa_auth = SADB_AALG_SHA1HMAC96;
#else
	  ssa.sadb_sa_auth = SADB_AALG_SHA1HMAC;
#endif
	  break;

#ifndef KAME
	case IPSEC_AH_RIPEMD:
#ifdef SADB_X_AALG_RIPEMD160HMAC96
	  ssa.sadb_sa_auth = SADB_X_AALG_RIPEMD160HMAC96;
#else
	  ssa.sadb_sa_auth = SADB_AALG_RIPEMD160HMAC;
#endif
	  break;
#endif

	default:
	  LOG_DBG ((LOG_SYSDEP, 50,
		    "pf_key_v2_set_spi: unknown authentication algorithm %d",
		    proto->id));
	  goto cleanup;
	}
      break;

#ifdef SADB_X_SATYPE_IPCOMP
    case IPSEC_PROTO_IPCOMP:
      msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
      ssa.sadb_sa_auth = SADB_AALG_NONE;
      keylen = 0;
      hashlen = 0;

      /* Put compression algorithm type in the sadb_sa_encrypt field.  */
      switch (proto->id)
	{
#ifdef SADB_X_CALG_OUI
	case IPSEC_IPCOMP_OUI:
	  ssa.sadb_sa_encrypt = SADB_X_CALG_OUI;
	  break;
#endif

#ifdef SADB_X_CALG_DEFLATE
	case IPSEC_IPCOMP_DEFLATE:
	  ssa.sadb_sa_encrypt = SADB_X_CALG_DEFLATE;
	  break;
#endif

#ifdef SADB_X_CALG_LSZ
	case IPSEC_IPCOMP_LZS:
	  ssa.sadb_sa_encrypt = SADB_X_CALG_LSZ;
	  break;
#endif

#ifdef SADB_X_CALG_V42BIS
	case IPSEC_IPCOMP_V42BIS:
	  ssa.sadb_sa_encrypt = SADB_X_CALG_V42BIS;
	  break;
#endif

	default:
	  break;
	}
      break;
#endif /* SADB_X_SATYPE_IPCOMP */

    default:
      log_print ("pf_key_v2_set_spi: invalid proto %d", proto->proto);
      goto cleanup;
    }
  if (incoming)
    sa->transport->vtbl->get_src (sa->transport, &dst);
  else
    sa->transport->vtbl->get_dst (sa->transport, &dst);
#ifdef KAME
  msg.sadb_msg_seq
    = (incoming ? pf_key_v2_seq_by_sa (proto->spi[incoming],
				       sizeof ssa.sadb_sa_spi, proto->proto,
				       dst, dst->sa_len)
       : 0);
#else
  msg.sadb_msg_seq = sa->seq;
#endif
  update = pf_key_v2_msg_new (&msg, 0);
  if (!update)
    goto cleanup;

#ifdef KAME
  memset (&ssa2, 0, sizeof ssa2);
  ssa2.sadb_x_sa2_exttype = SADB_X_EXT_SA2;
  ssa2.sadb_x_sa2_len = sizeof ssa2 / PF_KEY_V2_CHUNK;
  ssa2.sadb_x_sa2_mode = 0;
  if (pf_key_v2_msg_add (update, (struct sadb_ext *)&ssa2, 0) == -1)
    goto cleanup;
#endif

  /* Setup the rest of the SA extension.  */
  ssa.sadb_sa_exttype = SADB_EXT_SA;
  ssa.sadb_sa_len = sizeof ssa / PF_KEY_V2_CHUNK;
  memcpy (&ssa.sadb_sa_spi, proto->spi[incoming], sizeof ssa.sadb_sa_spi);
  ssa.sadb_sa_replay
    = conf_get_str ("General", "Shared-SADB") ? 0 : iproto->replay_window;
  ssa.sadb_sa_state = SADB_SASTATE_MATURE;
#ifdef SADB_X_SAFLAGS_TUNNEL
  ssa.sadb_sa_flags
    = iproto->encap_mode == IPSEC_ENCAP_TUNNEL ? SADB_X_SAFLAGS_TUNNEL : 0;
#else
  ssa.sadb_sa_flags = 0;
#endif
  if (pf_key_v2_msg_add (update, (struct sadb_ext *)&ssa, 0) == -1)
    goto cleanup;

  if (sa->seconds || sa->kilobytes)
    {
      /* Setup the hard limits.  */
      life = malloc (sizeof *life);
      if (!life)
	goto cleanup;
      life->sadb_lifetime_len = sizeof *life / PF_KEY_V2_CHUNK;
      life->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
      life->sadb_lifetime_allocations = 0;
      life->sadb_lifetime_bytes = sa->kilobytes * 1024;
      /*
       * XXX I am not sure which one is best in security respect.  Maybe the
       * RFCs actually mandate what a lifetime really is.
       */
#if 0
      life->sadb_lifetime_addtime = 0;
      life->sadb_lifetime_usetime = sa->seconds;
#else
      life->sadb_lifetime_addtime = sa->seconds;
      life->sadb_lifetime_usetime = 0;
#endif
      if (pf_key_v2_msg_add (update, (struct sadb_ext *)life,
			     PF_KEY_V2_NODE_MALLOCED) == -1)
	goto cleanup;
      life = 0;

      /*
       * Setup the soft limits, we use 90 % of the hard ones.
       * XXX A configurable ratio would be better.
       */
      life = malloc (sizeof *life);
      if (!life)
	goto cleanup;
      life->sadb_lifetime_len = sizeof *life / PF_KEY_V2_CHUNK;
      life->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
      life->sadb_lifetime_allocations = 0;
      life->sadb_lifetime_bytes = sa->kilobytes * 1024 * 9 / 10;
      /*
       * XXX I am not sure which one is best in security respect.  Maybe the
       * RFCs actually mandate what a lifetime really is.
       */
#if 0
      life->sadb_lifetime_addtime = 0;
      life->sadb_lifetime_usetime = sa->seconds * 9 / 10;
#else
      life->sadb_lifetime_addtime = sa->seconds * 9 / 10;
      life->sadb_lifetime_usetime = 0;
#endif
      if (pf_key_v2_msg_add (update, (struct sadb_ext *)life,
			     PF_KEY_V2_NODE_MALLOCED) == -1)
	goto cleanup;
      life = 0;
    }

  /*
   * Setup the ADDRESS extensions.
   */
  if (incoming)
    sa->transport->vtbl->get_dst (sa->transport, &src);
  else
    sa->transport->vtbl->get_src (sa->transport, &src);
  len = sizeof *addr + PF_KEY_V2_ROUND (src->sa_len);
  addr = calloc (1, len);
  if (!addr)
    goto cleanup;
  addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
  addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
#ifndef __OpenBSD__
  addr->sadb_address_proto = 0;
  addr->sadb_address_prefixlen = 0;
#endif
  addr->sadb_address_reserved = 0;
  memcpy (addr + 1, src, src->sa_len);
  switch (((struct sockaddr *)(addr + 1))->sa_family)
    {
    case AF_INET:
      ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
      break;
    case AF_INET6:
      ((struct sockaddr_in6 *)(addr + 1))->sin6_port = 0;
      break;
    }
  if (pf_key_v2_msg_add (update, (struct sadb_ext *)addr,
			 PF_KEY_V2_NODE_MALLOCED) == -1)
    goto cleanup;
  addr = 0;

  len = sizeof *addr + PF_KEY_V2_ROUND (dst->sa_len);
  addr = calloc (1, len);
  if (!addr)
    goto cleanup;
  addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
  addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
#ifndef __OpenBSD__
  addr->sadb_address_proto = 0;
  addr->sadb_address_prefixlen = 0;
#endif
  addr->sadb_address_reserved = 0;
  memcpy (addr + 1, dst, dst->sa_len);
  switch (((struct sockaddr *)(addr + 1))->sa_family)
    {
    case AF_INET:
      ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
      break;
    case AF_INET6:
      ((struct sockaddr_in6 *)(addr + 1))->sin6_port = 0;
      break;
    }
  if (pf_key_v2_msg_add (update, (struct sadb_ext *)addr,
			 PF_KEY_V2_NODE_MALLOCED) == -1)
    goto cleanup;
  addr = 0;

#if 0
  /* XXX I am not sure about what to do here just yet.  */
  if (iproto->encap_mode == IPSEC_ENCAP_TUNNEL)
    {
      len = sizeof *addr + PF_KEY_V2_ROUND (dst->sa_len);
      addr = calloc (1, len);
      if (!addr)
	goto cleanup;
      addr->sadb_address_exttype = SADB_EXT_ADDRESS_PROXY;
      addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
#ifndef __OpenBSD__
      addr->sadb_address_proto = 0;
      addr->sadb_address_prefixlen = 0;
#endif
      addr->sadb_address_reserved = 0;
      memcpy (addr + 1, dst, dst->sa_len);
      switch (((struct sockaddr *)(addr + 1))->sa_family)
	{
	case AF_INET:
	  ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
	  break;
	case AF_INET6:
	  ((struct sockaddr_in6 *)(addr + 1))->sin6_port = 0;
	  break;
	}
      if (pf_key_v2_msg_add (update, (struct sadb_ext *)addr,
			     PF_KEY_V2_NODE_MALLOCED) == -1)
	goto cleanup;
      addr = 0;
#if 0
      msg->em_odst = msg->em_dst;
      msg->em_osrc = msg->em_src;
#endif
    }
#endif

  /* Setup the KEY extensions.  */
  len = sizeof *key + PF_KEY_V2_ROUND (hashlen);
  key = malloc (len);
  if (!key)
    goto cleanup;
  key->sadb_key_exttype = SADB_EXT_KEY_AUTH;
  key->sadb_key_len = len / PF_KEY_V2_CHUNK;
  key->sadb_key_bits = hashlen * 8;
  key->sadb_key_reserved = 0;
  memcpy (key + 1,
	  iproto->keymat[incoming]
	  + (proto->proto == IPSEC_PROTO_IPSEC_ESP ? keylen : 0),
	  hashlen);
  if (pf_key_v2_msg_add (update, (struct sadb_ext *)key,
			 PF_KEY_V2_NODE_MALLOCED) == -1)
    goto cleanup;
  key = 0;

  if (keylen)
    {
      len = sizeof *key + PF_KEY_V2_ROUND (keylen);
      key = malloc (len);
      if (!key)
	goto cleanup;
      key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
      key->sadb_key_len = len / PF_KEY_V2_CHUNK;
      key->sadb_key_bits = keylen * 8;
      key->sadb_key_reserved = 0;
      memcpy (key + 1, iproto->keymat[incoming], keylen);
      if (pf_key_v2_msg_add (update, (struct sadb_ext *)key,
			     PF_KEY_V2_NODE_MALLOCED) == -1)
	goto cleanup;
      key = 0;
    }

#ifndef KAME
  /* Setup identity extensions. */
  if (isakmp_sa->id_i)
    {
      pp = pf_key_v2_convert_id (isakmp_sa->id_i, isakmp_sa->id_i_len,
				 &len, &idtype);
      if (!pp)
	goto nosid;

      sid = calloc (PF_KEY_V2_ROUND (len + 1) + sizeof *sid, sizeof (u_int8_t));
      if (!sid)
	{
	  free (pp);
	  goto cleanup;
	}

      sid->sadb_ident_type = idtype;
      sid->sadb_ident_len = ((sizeof *sid) / PF_KEY_V2_CHUNK)
			    + PF_KEY_V2_ROUND (len + 1) / PF_KEY_V2_CHUNK;
      if ((isakmp_sa->initiator && !incoming)
	  || (!isakmp_sa->initiator && incoming))
	sid->sadb_ident_exttype = SADB_EXT_IDENTITY_SRC;
      else
	sid->sadb_ident_exttype = SADB_EXT_IDENTITY_DST;

      memcpy(sid + 1, pp, len);
      free (pp);

      if (pf_key_v2_msg_add (update, (struct sadb_ext *)sid,
			      PF_KEY_V2_NODE_MALLOCED) == -1)
	goto cleanup;
      sid = 0;

 nosid:
      if (sid)
	free (sid);
      sid = 0;
    }

  if (isakmp_sa->id_r)
    {
      pp = pf_key_v2_convert_id (isakmp_sa->id_r, isakmp_sa->id_r_len,
				 &len, &idtype);
      if (!pp)
	goto nodid;

      sid = calloc (PF_KEY_V2_ROUND (len + 1) + sizeof *sid, sizeof (u_int8_t));
      if (!sid)
	{
	  free (pp);
	  goto cleanup;
	}

      sid->sadb_ident_type = idtype;
      sid->sadb_ident_len = ((sizeof *sid) / PF_KEY_V2_CHUNK)
			    + PF_KEY_V2_ROUND (len + 1) / PF_KEY_V2_CHUNK;
      if ((isakmp_sa->initiator && !incoming)
	  || (!isakmp_sa->initiator && incoming))
	sid->sadb_ident_exttype = SADB_EXT_IDENTITY_DST;
      else
	sid->sadb_ident_exttype = SADB_EXT_IDENTITY_SRC;

      memcpy (sid + 1, pp, len);
      free (pp);

      if (pf_key_v2_msg_add (update, (struct sadb_ext *)sid,
			      PF_KEY_V2_NODE_MALLOCED) == -1)
	goto cleanup;
      sid = 0;

 nodid:
      if (sid)
	free (sid);
      sid = 0;
    }
#endif /* KAME */

#ifdef SADB_X_CREDTYPE_NONE
  /*
   * Send received credentials to the kernel. We don't bother with
   * our credentials, since the process either knows them (if it specified
   * them with setsockopt()), or has no business looking at them (e.g.,
   * system wide certs).
   */
  if (isakmp_sa->recv_cert)
    {
      switch (isakmp_sa->recv_certtype)
	{
	case ISAKMP_CERTENC_NONE:
	  /* Nothing to be done here. */
	  break;

#if defined (USE_KEYNOTE) && defined (SADB_X_EXT_REMOTE_CREDENTIALS)
	case ISAKMP_CERTENC_KEYNOTE:
	  len = strlen (isakmp_sa->recv_cert);
	  cred = calloc (PF_KEY_V2_ROUND (len) + sizeof *cred,
			 sizeof (u_int8_t));
	  if (!cred)
	    goto cleanup;

	  cred->sadb_x_cred_len = ((sizeof *cred) / PF_KEY_V2_CHUNK) +
	    PF_KEY_V2_ROUND (len) / PF_KEY_V2_CHUNK;
	  cred->sadb_x_cred_exttype = SADB_X_EXT_REMOTE_CREDENTIALS;
	  cred->sadb_x_cred_type = SADB_X_CREDTYPE_KEYNOTE;
	  memcpy (cred + 1, isakmp_sa->recv_cert, len);

	  if (pf_key_v2_msg_add (update, (struct sadb_ext *)cred,
				 PF_KEY_V2_NODE_MALLOCED) == -1)
	    goto cleanup;
	  break;
#endif /* USE_KEYNOTE */

#if defined (USE_X509) && defined (SADB_X_EXT_REMOTE_CREDENTIALS)
	case ISAKMP_CERTENC_X509_SIG:
	  {
	    u_int8_t *data;
	    u_int32_t datalen;
	    struct cert_handler *handler;

	    /* We do it this way to avoid weird includes. */
	    handler = cert_get (ISAKMP_CERTENC_X509_SIG);
	    if (!handler)
	      break;
	    handler->cert_serialize (isakmp_sa->recv_cert, &data, &datalen);
	    if (!data)
	      break;

	    len = datalen;
	    cred = calloc (PF_KEY_V2_ROUND (len) + sizeof *cred,
			   sizeof (u_int8_t));
	    if (!cred)
	      {
		free (data);
		goto cleanup;
	      }

	    cred->sadb_x_cred_len = ((sizeof *cred) / PF_KEY_V2_CHUNK) +
	      PF_KEY_V2_ROUND (len) / PF_KEY_V2_CHUNK;
	    cred->sadb_x_cred_exttype = SADB_X_EXT_REMOTE_CREDENTIALS;
	    cred->sadb_x_cred_type = SADB_X_CREDTYPE_X509;
	    memcpy (cred + 1, data, len);
	    free (data);

	    if (pf_key_v2_msg_add (update, (struct sadb_ext *)cred,
				   PF_KEY_V2_NODE_MALLOCED) == -1)
	      goto cleanup;
	  }
	  break;
#endif /* USE_X509 */
	}
    }
#endif /* SADB_X_CREDTYPE_NONE */

#ifdef SADB_X_AUTHTYPE_NONE
  /*
   * Tell the kernel what the peer used to authenticate, unless it was a
   * passphrase.
   */
  if (isakmp_sa->recv_key)
    {
      u_int8_t *data;

      /*
       * If it's a private key, we shouldn't pass it to the kernel for
       * processes to see; successful authentication of Phase 1 implies
       * that the process already knew the passphrase. On the other hand,
       * we don't want to reveal to processes any system-wide passphrases
       * used for authentication with remote systems. Same reason we don't
       * send up the key (private or passphrase) we used to authenticate
       * with the peer.
       */
      if (isakmp_sa->recv_keytype == ISAKMP_KEY_PASSPHRASE)
	goto doneauth;

      key_serialize (isakmp_sa->recv_keytype, ISAKMP_KEYTYPE_PUBLIC,
		     isakmp_sa->recv_key, &data, &len);
      if (!data)
	goto cleanup;

      cred = calloc (PF_KEY_V2_ROUND (len) + sizeof *cred, sizeof (u_int8_t));
      if (!cred)
	{
	  free (data);
	  goto cleanup;
	}

      cred->sadb_x_cred_len = ((sizeof *cred) / PF_KEY_V2_CHUNK) +
	PF_KEY_V2_ROUND (len) / PF_KEY_V2_CHUNK;
      cred->sadb_x_cred_exttype = SADB_X_EXT_REMOTE_AUTH;
      memcpy (cred + 1, data, len);
      free (data);

      switch (isakmp_sa->recv_keytype)
	{
	case ISAKMP_KEY_RSA:
	  cred->sadb_x_cred_type = SADB_X_AUTHTYPE_RSA;
	  break;

	default:
	  log_print ("pf_key_v2_set_spi: unknown received key type %d",
		     isakmp_sa->recv_keytype);
	  free (cred);
	  goto cleanup;
	}

      if (pf_key_v2_msg_add (update, (struct sadb_ext *)cred,
			     PF_KEY_V2_NODE_MALLOCED) == -1)
	goto cleanup;
    }
 doneauth:
#endif /* SADB_X_AUTHTYPE_NONE */

  /* XXX Here can sensitivity extensions be setup.  */

#ifdef USE_DEBUG
  if (sockaddr2text (dst, &addr_str, 0))
    addr_str = 0;

  LOG_DBG ((LOG_SYSDEP, 10, "pf_key_v2_set_spi: satype %d dst %s SPI 0x%x",
	    msg.sadb_msg_satype, addr_str ? addr_str : "unknown",
	    ntohl (ssa.sadb_sa_spi)));

  if (addr_str)
    free (addr_str);
#endif /* USE_DEBUG */

  /*
   * Although PF_KEY knows about expirations, it is unreliable per the specs
   * thus we need to do them inside isakmpd as well.
   */
  if (sa->seconds)
    if (sa_setup_expirations (sa))
      goto cleanup;

  ret = pf_key_v2_call (update);
  pf_key_v2_msg_free (update);
  update = 0;
  if (!ret)
    goto cleanup;
  err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
  pf_key_v2_msg_free (ret);
  ret = 0;

  /*
   * If we are doing an addition into an SADB shared with our peer, errors
   * here are to be expected as the peer will already have created the SA,
   * and can thus be ignored.
   */
  if (err && !(msg.sadb_msg_type == SADB_ADD
	       && conf_get_str ("General", "Shared-SADB")))
    {
      log_print ("pf_key_v2_set_spi: %s: %s",
		 msg.sadb_msg_type == SADB_ADD ? "ADD" : "UPDATE",
		 strerror (err));
      goto cleanup;
    }

  LOG_DBG ((LOG_SYSDEP, 50, "pf_key_v2_set_spi: done"));

  return 0;

 cleanup:
  if (sid)
    free (sid);
  if (addr)
    free (addr);
  if (life)
    free (life);
  if (key)
    free (key);
  if (update)
    pf_key_v2_msg_free (update);
  if (ret)
    pf_key_v2_msg_free (ret);
  return -1;
}

static __inline__ int
pf_key_v2_mask_to_bits (u_int32_t mask)
{
  u_int32_t hmask = ntohl (mask);
  return (33 - ffs (~hmask + 1)) % 33;
}

static int
pf_key_v2_mask6_to_bits (u_int8_t *mask)
{
  int n;
  bit_ffc (mask, 128, &n);
  return n;
}

static void
pf_key_v2_setup_sockaddr (void *res, struct sockaddr *src,
			  struct sockaddr *dst, in_port_t port, int ingress)
{
  struct sockaddr_in *ip4_sa;
  struct sockaddr_in6 *ip6_sa;
  u_int8_t *p;

  switch (src->sa_family)
    {
    case AF_INET:
      ip4_sa = (struct sockaddr_in *)res;
      ip4_sa->sin_family = AF_INET;
      ip4_sa->sin_len = sizeof *ip4_sa;
      ip4_sa->sin_port = port;
      if (dst)
	p = (u_int8_t *)(ingress
			 ? &((struct sockaddr_in *)src)->sin_addr.s_addr
			 : &((struct sockaddr_in *)dst)->sin_addr.s_addr);
      else
	p = (u_int8_t *)&((struct sockaddr_in *)src)->sin_addr.s_addr;
      ip4_sa->sin_addr.s_addr = *((in_addr_t *)p);
      break;

    case AF_INET6:
      ip6_sa = (struct sockaddr_in6 *)res;
      ip6_sa->sin6_family = AF_INET6;
      ip6_sa->sin6_len = sizeof *ip6_sa;
      ip6_sa->sin6_port = port;
      if (dst)
	p = (u_int8_t *)(ingress
			 ? &((struct sockaddr_in6 *)src)->sin6_addr.s6_addr
			 : &((struct sockaddr_in6 *)dst)->sin6_addr.s6_addr);
      else
	p = (u_int8_t *)&((struct sockaddr_in6 *)src)->sin6_addr.s6_addr;
      memcpy (ip6_sa->sin6_addr.s6_addr, p, sizeof (struct in6_addr));
      break;

    default:
      log_print ("pf_key_v2_setup_sockaddr: unknown family %d\n",
		 src->sa_family);
      break;
    }
}

/*
 * Enable/disable a flow.
 * XXX Assumes OpenBSD {ADD,DEL}FLOW extensions.
 * Should probably be moved to sysdep.c
 */
static int
pf_key_v2_flow (struct sockaddr *laddr, struct sockaddr *lmask,
		struct sockaddr *raddr,	struct sockaddr *rmask,
		u_int8_t tproto, u_int16_t sport, u_int16_t dport,
		u_int8_t *spi, u_int8_t proto, struct sockaddr *dst,
		struct sockaddr *src, int delete, int ingress,
		u_int8_t srcid_type, u_int8_t *srcid, int srcid_len,
		u_int8_t dstid_type, u_int8_t *dstid, int dstid_len)
{
#ifdef USE_DEBUG
  char *laddr_str, *lmask_str, *raddr_str, *rmask_str;
#endif
#if defined (SADB_X_ADDFLOW) && defined (SADB_X_DELFLOW)
  struct sadb_msg msg;
#ifdef SADB_X_EXT_FLOW_TYPE
  struct sadb_protocol flowtype;
  struct sadb_ident *sid = 0;
#else
  struct sadb_sa ssa;
#endif
  struct sadb_address *addr = 0;
  struct sadb_protocol tprotocol;
  struct pf_key_v2_msg *flow = 0, *ret = 0;
  size_t len;
  int err;

#if !defined (SADB_X_SAFLAGS_INGRESS_FLOW) && !defined (SADB_X_EXT_FLOW_TYPE)
  if (ingress)
    return 0;
#endif

  msg.sadb_msg_type = delete ? SADB_X_DELFLOW : SADB_X_ADDFLOW;
  switch (proto)
    {
    case IPSEC_PROTO_IPSEC_ESP:
      msg.sadb_msg_satype = SADB_SATYPE_ESP;
      break;
    case IPSEC_PROTO_IPSEC_AH:
      msg.sadb_msg_satype = SADB_SATYPE_AH;
      break;
    default:
      log_print ("pf_key_v2_flow: invalid proto %d", proto);
      goto cleanup;
    }
  msg.sadb_msg_seq = 0;
  flow = pf_key_v2_msg_new (&msg, 0);
  if (!flow)
    goto cleanup;

#ifdef SADB_X_EXT_FLOW_TYPE
  if (!delete)
    {
      /* Setup the source ID, if provided. */
      if (srcid)
        {
	  sid = calloc (PF_KEY_V2_ROUND (srcid_len + 1) + sizeof *sid,
			sizeof (u_int8_t));
	  if (!sid)
	    goto cleanup;

	  sid->sadb_ident_len = ((sizeof *sid) / PF_KEY_V2_CHUNK)
	    + PF_KEY_V2_ROUND (srcid_len + 1) / PF_KEY_V2_CHUNK;
	  sid->sadb_ident_exttype = SADB_EXT_IDENTITY_SRC;
	  sid->sadb_ident_type = srcid_type;

	  memcpy (sid + 1, srcid, srcid_len);

	  if (pf_key_v2_msg_add (flow, (struct sadb_ext *)sid,
				 PF_KEY_V2_NODE_MALLOCED) == -1)
	    goto cleanup;

	  sid = 0;
	}

      /* Setup the destination ID, if provided. */
      if (dstid)
        {
	  sid = calloc (PF_KEY_V2_ROUND (dstid_len + 1) + sizeof *sid,
			sizeof (u_int8_t));
	  if (!sid)
	    goto cleanup;

	  sid->sadb_ident_len = ((sizeof *sid) / PF_KEY_V2_CHUNK)
	    + PF_KEY_V2_ROUND (dstid_len + 1) / PF_KEY_V2_CHUNK;
	  sid->sadb_ident_exttype = SADB_EXT_IDENTITY_DST;
	  sid->sadb_ident_type = dstid_type;

	  memcpy (sid + 1, dstid, dstid_len);

	  if (pf_key_v2_msg_add (flow, (struct sadb_ext *)sid,
				 PF_KEY_V2_NODE_MALLOCED) == -1)
	    goto cleanup;

	  sid = 0;
	}
    }

  /* Setup the flow type extension.  */
  bzero (&flowtype, sizeof flowtype);
  flowtype.sadb_protocol_exttype = SADB_X_EXT_FLOW_TYPE;
  flowtype.sadb_protocol_len = sizeof flowtype / PF_KEY_V2_CHUNK;
  flowtype.sadb_protocol_direction
    = ingress ? IPSP_DIRECTION_IN : IPSP_DIRECTION_OUT;
  flowtype.sadb_protocol_proto
    = ingress ? SADB_X_FLOW_TYPE_USE : SADB_X_FLOW_TYPE_REQUIRE;

  if (pf_key_v2_msg_add (flow, (struct sadb_ext *)&flowtype, 0) == -1)
    goto cleanup;
#else /* SADB_X_EXT_FLOW_TYPE */
  /* Setup the SA extension.  */
  ssa.sadb_sa_exttype = SADB_EXT_SA;
  ssa.sadb_sa_len = sizeof ssa / PF_KEY_V2_CHUNK;
  memcpy (&ssa.sadb_sa_spi, spi, sizeof ssa.sadb_sa_spi);
  ssa.sadb_sa_replay = 0;
  ssa.sadb_sa_state = 0;
  ssa.sadb_sa_auth = 0;
  ssa.sadb_sa_encrypt = 0;
  ssa.sadb_sa_flags = 0;
#ifdef SADB_X_SAFLAGS_INGRESS_FLOW
  if (ingress)
    ssa.sadb_sa_flags |= SADB_X_SAFLAGS_INGRESS_FLOW;
#endif
#ifdef SADB_X_SAFLAGS_REPLACEFLOW
  if (!delete && !ingress)
    ssa.sadb_sa_flags |= SADB_X_SAFLAGS_REPLACEFLOW;
#endif

  if (pf_key_v2_msg_add (flow, (struct sadb_ext *)&ssa, 0) == -1)
    goto cleanup;
#endif /* SADB_X_EXT_FLOW_TYPE */

  /*
   * Setup the ADDRESS extensions.
   */
  len = sizeof *addr + PF_KEY_V2_ROUND (src->sa_len);
#ifndef SADB_X_EXT_FLOW_TYPE
  if (!delete || ingress)
#else
  if (!delete)
#endif /* SADB_X_EXT_FLOW_TYPE */
    {
      addr = calloc (1, len);
      if (!addr)
	goto cleanup;
      addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
      addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
      addr->sadb_address_reserved = 0;
#ifdef SADB_X_EXT_FLOW_TYPE
      pf_key_v2_setup_sockaddr (addr + 1, src, dst, 0, ingress);
#else
      pf_key_v2_setup_sockaddr (addr + 1, dst, 0, 0, 0);
#endif
      if (pf_key_v2_msg_add (flow, (struct sadb_ext *)addr,
			     PF_KEY_V2_NODE_MALLOCED) == -1)
	goto cleanup;
      addr = 0;
    }

  len = sizeof *addr + PF_KEY_V2_ROUND (laddr->sa_len);
  addr = calloc (1, len);
  if (!addr)
    goto cleanup;
  addr->sadb_address_exttype = SADB_X_EXT_SRC_FLOW;
  addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
  addr->sadb_address_reserved = 0;
  pf_key_v2_setup_sockaddr (addr + 1, laddr, 0, sport, 0);
  if (pf_key_v2_msg_add (flow, (struct sadb_ext *)addr,
			 PF_KEY_V2_NODE_MALLOCED) == -1)
    goto cleanup;
  addr = 0;

  addr = calloc (1, len);
  if (!addr)
    goto cleanup;
  addr->sadb_address_exttype = SADB_X_EXT_SRC_MASK;
  addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
  addr->sadb_address_reserved = 0;
  pf_key_v2_setup_sockaddr (addr + 1, lmask, 0, sport ? 0xffff : 0, 0);
  if (pf_key_v2_msg_add (flow, (struct sadb_ext *)addr,
			 PF_KEY_V2_NODE_MALLOCED) == -1)
    goto cleanup;
  addr = 0;

  addr = calloc (1, len);
  if (!addr)
    goto cleanup;
  addr->sadb_address_exttype = SADB_X_EXT_DST_FLOW;
  addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
  addr->sadb_address_reserved = 0;
  pf_key_v2_setup_sockaddr (addr + 1, raddr, 0, sport, 0);
  if (pf_key_v2_msg_add (flow, (struct sadb_ext *)addr,
			 PF_KEY_V2_NODE_MALLOCED) == -1)
    goto cleanup;
  addr = 0;

  addr = calloc (1, len);
  if (!addr)
    goto cleanup;
  addr->sadb_address_exttype = SADB_X_EXT_DST_MASK;
  addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
  addr->sadb_address_reserved = 0;
  pf_key_v2_setup_sockaddr (addr + 1, rmask, 0, sport ? 0xffff : 0, 0);
  if (pf_key_v2_msg_add (flow, (struct sadb_ext *)addr,
			 PF_KEY_V2_NODE_MALLOCED) == -1)
    goto cleanup;
  addr = 0;

  /* Setup the protocol extension.  */
  bzero (&tprotocol, sizeof tprotocol);
  tprotocol.sadb_protocol_exttype = SADB_X_EXT_PROTOCOL;
  tprotocol.sadb_protocol_len = sizeof tprotocol / PF_KEY_V2_CHUNK;
  tprotocol.sadb_protocol_proto = tproto;

  if (pf_key_v2_msg_add (flow, (struct sadb_ext *)&tprotocol, 0) == -1)
    goto cleanup;

#ifdef USE_DEBUG
  if (sockaddr2text (laddr, &laddr_str, 0))
    laddr_str = 0;
  if (sockaddr2text (lmask, &lmask_str, 0))
    lmask_str = 0;
  if (sockaddr2text (raddr, &raddr_str, 0))
    raddr_str = 0;
  if (sockaddr2text (rmask, &rmask_str, 0))
    rmask_str = 0;

  LOG_DBG ((LOG_SYSDEP, 50,
	    "pf_key_v2_flow: src %s %s dst %s %s proto %u sport %u dport %u",
	    laddr_str ? laddr_str : "<???>", lmask_str ? lmask_str : "<???>",
	    raddr_str ? raddr_str : "<???>", rmask_str ? rmask_str : "<???>",
	    tproto, ntohs (sport), ntohs (dport)));

  if (laddr_str)
    free (laddr_str);
  if (lmask_str)
    free (lmask_str);
  if (raddr_str)
    free (raddr_str);
  if (rmask_str)
    free (rmask_str);
#endif /* USE_DEBUG */

  ret = pf_key_v2_call (flow);
  pf_key_v2_msg_free (flow);
  flow = 0;
  if (!ret)
    goto cleanup;
  err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
  if (err)
    {
      if (err == ESRCH) /* These are common and usually harmless.  */
	LOG_DBG ((LOG_SYSDEP, 10, "pf_key_v2_flow: %sFLOW: %s",
		  delete ? "DEL" : "ADD", strerror (err)));
      else
	log_print ("pf_key_v2_flow: %sFLOW: %s", delete ? "DEL" : "ADD",
		   strerror (err));
      goto cleanup;
    }
  pf_key_v2_msg_free (ret);

  LOG_DBG ((LOG_MISC, 50, "pf_key_v2_flow: %sFLOW: done",
	    delete ? "DEL" : "ADD"));

  return 0;

 cleanup:
#ifdef SADB_X_EXT_FLOW_TYPE
  if (sid)
    free (sid);
#endif /* SADB_X_EXT_FLOW_TYPE */
  if (addr)
    free (addr);
  if (flow)
    pf_key_v2_msg_free (flow);
  if (ret)
    pf_key_v2_msg_free (ret);
  return -1;

#elif defined (SADB_X_SPDADD) && defined (SADB_X_SPDDELETE)
  struct sadb_msg msg;
  struct sadb_x_policy *policy = 0;
  struct sadb_x_ipsecrequest *ipsecrequest;
  struct sadb_x_sa2 ssa2;
  struct sadb_address *addr = 0;
  struct sockaddr *saddr;
  struct pf_key_v2_msg *flow = 0, *ret = 0;
  u_int8_t *policy_buf;
  size_t len;
  int err;
  struct sockaddr_in *ip4_sa;
  struct sockaddr_in6 *ip6_sa;

  msg.sadb_msg_type = delete ? SADB_X_SPDDELETE : SADB_X_SPDADD;
  msg.sadb_msg_satype = SADB_SATYPE_UNSPEC;
  msg.sadb_msg_seq = 0;
  flow = pf_key_v2_msg_new (&msg, 0);
  if (!flow)
    goto cleanup;

  memset (&ssa2, 0, sizeof ssa2);
  ssa2.sadb_x_sa2_exttype = SADB_X_EXT_SA2;
  ssa2.sadb_x_sa2_len = sizeof ssa2 / PF_KEY_V2_CHUNK;
  ssa2.sadb_x_sa2_mode = 0;
  if (pf_key_v2_msg_add (flow, (struct sadb_ext *)&ssa2, 0) == -1)
    goto cleanup;

  /*
   * Setup the ADDRESS extensions.
   */
  len = sizeof *addr + PF_KEY_V2_ROUND (src->sa_len);
  addr = calloc (1, len);
  if (!addr)
    goto cleanup;
  addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
  addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
  addr->sadb_address_proto = IPSEC_ULPROTO_ANY;
  addr->sadb_address_reserved = 0;
  pf_key_v2_setup_sockaddr (addr + 1, laddr, 0, IPSEC_PORT_ANY, 0);
  switch (laddr->sa_family)
    {
    case AF_INET:
      ip4_sa = (struct sockaddr_in *)lmask;
      addr->sadb_address_prefixlen
	= pf_key_v2_mask_to_bits (ip4_sa->sin_addr.s_addr);
      break;
    case AF_INET6:
      ip6_sa = (struct sockaddr_in6 *)lmask;
      addr->sadb_address_prefixlen
	= pf_key_v2_mask6_to_bits (&ip6_sa->sin6_addr.s6_addr[0]);
      break;
    }
  if (pf_key_v2_msg_add (flow, (struct sadb_ext *)addr,
			 PF_KEY_V2_NODE_MALLOCED) == -1)
    goto cleanup;
  addr = 0;

  len = sizeof *addr + PF_KEY_V2_ROUND (raddr->sa_len);
  addr = calloc (1, len);
  if (!addr)
    goto cleanup;
  addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
  addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
  addr->sadb_address_proto = IPSEC_ULPROTO_ANY;
  addr->sadb_address_reserved = 0;
  pf_key_v2_setup_sockaddr (addr + 1, raddr, 0, IPSEC_PORT_ANY, 0);
  switch (raddr->sa_family)
    {
    case AF_INET:
      ip4_sa = (struct sockaddr_in *)rmask;
      addr->sadb_address_prefixlen
	= pf_key_v2_mask_to_bits (ip4_sa->sin_addr.s_addr);
      break;
    case AF_INET6:
      ip6_sa = (struct sockaddr_in6 *)rmask;
      addr->sadb_address_prefixlen
	= pf_key_v2_mask6_to_bits (&ip6_sa->sin6_addr.s6_addr[0]);
      break;
    }
  if (pf_key_v2_msg_add (flow, (struct sadb_ext *)addr,
			 PF_KEY_V2_NODE_MALLOCED) == -1)
    goto cleanup;
  addr = 0;

  /* Setup the POLICY extension.  */
  len = sizeof *policy + sizeof *ipsecrequest +
    2 * PF_KEY_V2_ROUND (src->sa_len);
  policy_buf = (u_int8_t *)calloc (1, len);
  if (!policy_buf)
    {
      log_error ("pf_key_v2_flow: calloc %d failed", len);
      goto cleanup;
    }

  policy = (struct sadb_x_policy *)policy_buf;
  policy->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
  policy->sadb_x_policy_len = len / PF_KEY_V2_CHUNK;
  policy->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
  if (ingress)
  	policy->sadb_x_policy_dir = IPSEC_DIR_INBOUND;
  else
  	policy->sadb_x_policy_dir = IPSEC_DIR_OUTBOUND;
  policy->sadb_x_policy_reserved = 0;

  /* Setup the IPSECREQUEST extension part.  */
  ipsecrequest = (struct sadb_x_ipsecrequest *)(policy + 1);
  ipsecrequest->sadb_x_ipsecrequest_len = len - sizeof *policy;
  switch (proto)
    {
    case IPSEC_PROTO_IPSEC_ESP:
      ipsecrequest->sadb_x_ipsecrequest_proto = IPPROTO_ESP;
      break;
    case IPSEC_PROTO_IPSEC_AH:
      ipsecrequest->sadb_x_ipsecrequest_proto = IPPROTO_AH;
      break;
    default:
      log_print ("pf_key_v2_flow: invalid proto %d", proto);
      goto cleanup;
    }
  ipsecrequest->sadb_x_ipsecrequest_mode = IPSEC_MODE_TUNNEL;	/* XXX */
  ipsecrequest->sadb_x_ipsecrequest_level
    = ingress ? IPSEC_LEVEL_USE : IPSEC_LEVEL_REQUIRE;
  ipsecrequest->sadb_x_ipsecrequest_reqid = 0;	/* XXX */

  /* Add source and destination addresses. */
  saddr = (struct sockaddr *)(ipsecrequest + 1);
  pf_key_v2_setup_sockaddr (saddr, src, 0, 0, 0);
  switch (src->sa_family)
    {
    case AF_INET:
      saddr = (struct sockaddr *)((struct sockaddr_in *)saddr + 1);
      break;
    case AF_INET6:
      saddr = (struct sockaddr *)((struct sockaddr_in6 *)saddr + 1);
      break;
    }
  pf_key_v2_setup_sockaddr (saddr, dst, 0, 0, 0);
  if (pf_key_v2_msg_add (flow, (struct sadb_ext *)policy, 0) == -1)
    goto cleanup;

#ifdef USE_DEBUG
  if (sockaddr2text (laddr, &laddr_str, 0))
    laddr_str = 0;
  if (sockaddr2text (lmask, &lmask_str, 0))
    lmask_str = 0;
  if (sockaddr2text (raddr, &raddr_str, 0))
    raddr_str = 0;
  if (sockaddr2text (rmask, &rmask_str, 0))
    rmask_str = 0;

  LOG_DBG ((LOG_SYSDEP, 50, "pf_key_v2_flow: src %x %x dst %x %x",
	    laddr_str ? laddr_str : "<???>", lmask_str ? laddr_str : "<???>",
	    raddr_str ? laddr_str : "<???>", rmask_str ? laddr_str : "<???>"));

  if (laddr_str)
    free (laddr_str);
  if (lmask_str)
    free (lmask_str);
  if (raddr_str)
    free (raddr_str);
  if (rmask_str)
    free (rmask_str);
#endif

  ret = pf_key_v2_call (flow);
  pf_key_v2_msg_free (flow);
  flow = 0;
  if (!ret)
    goto cleanup;
  err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
  if (!delete && err == EEXIST)
    {
      LOG_DBG ((LOG_SYSDEP, 50, "pf_key_v2_flow: SPDADD returns EEXIST"));
    }
  else if (err)
    {
      log_print ("pf_key_v2_flow: SPD%s: %s", delete ? "DELETE" : "ADD",
		 strerror (err));
      goto cleanup;
    }
  pf_key_v2_msg_free (ret);

  LOG_DBG ((LOG_SYSDEP, 50, "pf_key_v2_flow: SPD%s: done",
	    delete ? "DELETE" : "ADD"));

  return 0;

 cleanup:
  if (addr)
    free (addr);
  if (policy)
    free (policy);
  if (flow)
    pf_key_v2_msg_free (flow);
  if (ret)
    pf_key_v2_msg_free (ret);
  return -1;

#else
  log_print ("pf_key_v2_flow: not supported in pure PF_KEYv2");
  return -1;
#endif
}

#ifndef KAME
static u_int8_t *
pf_key_v2_convert_id (u_int8_t *id, int idlen, size_t *reslen, int *idtype)
{
  u_int8_t *res = 0;
  char addrbuf[ADDRESS_MAX + 5];
  char *addr;

  switch (id[0])
    {
    case IPSEC_ID_FQDN:
      res = calloc (idlen - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ,
		    sizeof (u_int8_t));
      if (!res)
	return 0;

      *reslen = idlen - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ;
      memcpy (res, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ, *reslen);
      *idtype = SADB_IDENTTYPE_FQDN;
      LOG_DBG ((LOG_SYSDEP, 40, "pf_key_v2_convert_id: FQDN %s", res));
      return res;

    case IPSEC_ID_USER_FQDN:
      res = calloc (idlen - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ,
		    sizeof (u_int8_t));
      if (!res)
	return 0;

      *reslen = idlen - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ;
      memcpy (res, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ, *reslen);
      *idtype = SADB_IDENTTYPE_USERFQDN;
      LOG_DBG ((LOG_SYSDEP, 40, "pf_key_v2_convert_id: UFQDN %s", res));
      return res;

    case IPSEC_ID_IPV4_ADDR: /* XXX CONNECTION ? */
      if (inet_ntop (AF_INET, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ,
		     addrbuf, ADDRESS_MAX) == NULL)
	return 0;
      *reslen = strlen (addrbuf) + 3;
      strcat (addrbuf, "/32");
      res = strdup (addrbuf);
      if (!res)
	return 0;
      *idtype = SADB_IDENTTYPE_PREFIX;
      LOG_DBG ((LOG_SYSDEP, 40, "pf_key_v2_convert_id: IPv4 address %s", res));
      return res;

    case IPSEC_ID_IPV6_ADDR: /* XXX CONNECTION ? */
      if (inet_ntop (AF_INET6, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ,
		     addrbuf, ADDRESS_MAX) == NULL)
	return 0;
      *reslen = strlen (addrbuf) + 4;
      strcat (addrbuf, "/128");
      res = strdup (addrbuf);
      if (!res)
	return 0;
      LOG_DBG ((LOG_SYSDEP, 40, "pf_key_v2_convert_id: IPv6 address %s", res));
      *idtype = SADB_IDENTTYPE_PREFIX;
      return res;

    case IPSEC_ID_IPV4_ADDR_SUBNET: /* XXX PREFIX */
      addr = id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ;
      if (inet_ntop (AF_INET, addr, addrbuf, ADDRESS_MAX) == NULL)
	return 0;
      sprintf (addrbuf + strlen (addrbuf), "/%d",
	       pf_key_v2_mask_to_bits ((u_int32_t)
				       *(addr + sizeof (struct in_addr))));
      *reslen = strlen (addrbuf);
      res = strdup (addrbuf);
      if (!res)
	return 0;
      *idtype = SADB_IDENTTYPE_PREFIX;
      LOG_DBG ((LOG_SYSDEP, 40, "pf_key_v2_convert_id: IPv4 subnet %s", res));
      return res;

    case IPSEC_ID_IPV6_ADDR_SUBNET: /* XXX PREFIX */
      addr = id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ;
      if (inet_ntop (AF_INET6, addr, addrbuf, ADDRESS_MAX) == NULL)
	return 0;
      sprintf (addrbuf + strlen (addrbuf), "/%d",
	       pf_key_v2_mask6_to_bits (addr + sizeof (struct in6_addr)));
      *reslen = strlen (addrbuf);
      res = strdup (addrbuf);
      if (!res)
	return 0;
      LOG_DBG ((LOG_SYSDEP, 40, "pf_key_v2_convert_id: IPv6 subnet %s", res));
      *idtype = SADB_IDENTTYPE_PREFIX;
      return res;

    case IPSEC_ID_IPV4_RANGE:
    case IPSEC_ID_IPV6_RANGE:
    case IPSEC_ID_DER_ASN1_DN:
    case IPSEC_ID_DER_ASN1_GN:
    case IPSEC_ID_KEY_ID:
      /* XXX Not implemented yet.  */
      return 0;
    }

  return 0;
}
#endif

/* Enable a flow given a SA.  */
int
pf_key_v2_enable_sa (struct sa *sa, struct sa *isakmp_sa)
{
  struct ipsec_sa *isa = sa->data;
  struct sockaddr *dst, *src;
  int error;
  struct proto *proto = TAILQ_FIRST (&sa->protos);
  int sidtype = 0, didtype = 0;
  size_t sidlen = 0, didlen = 0;
  u_int8_t *sid = 0, *did = 0;
#ifndef SADB_X_EXT_FLOW_TYPE
  struct sockaddr_storage hostmask_storage;
  struct sockaddr *hostmask = (struct sockaddr *)&hostmask_storage;
#endif /* SADB_X_EXT_FLOW_TYPE */

  sa->transport->vtbl->get_dst (sa->transport, &dst);
  sa->transport->vtbl->get_src (sa->transport, &src);

#ifdef SADB_X_EXT_FLOW_TYPE
  if (isakmp_sa->id_i)
    {
      if (isakmp_sa->initiator)
	sid = pf_key_v2_convert_id (isakmp_sa->id_i, isakmp_sa->id_i_len,
				    &sidlen, &sidtype);
      else
	did = pf_key_v2_convert_id (isakmp_sa->id_i, isakmp_sa->id_i_len,
				    &didlen, &didtype);
    }

  if (isakmp_sa->id_r)
    {
      if (isakmp_sa->initiator)
	did = pf_key_v2_convert_id (isakmp_sa->id_r, isakmp_sa->id_r_len,
				    &didlen, &didtype);
      else
	sid = pf_key_v2_convert_id (isakmp_sa->id_r, isakmp_sa->id_r_len,
				    &sidlen, &sidtype);
    }
#endif /* SADB_X_EXT_FLOW_TYPE */

  error = pf_key_v2_flow (isa->src_net, isa->src_mask, isa->dst_net,
			  isa->dst_mask, isa->tproto, isa->sport, isa->dport,
			  proto->spi[0], proto->proto, dst, src, 0, 0,
			  sidtype, sid, sidlen, didtype, did, didlen);
  if (error)
    goto cleanup;

#ifndef SADB_X_EXT_FLOW_TYPE
  /* Set hostmask to '-1'. */
  switch (dst->sa_family)
    {
    case AF_INET:
      ((struct sockaddr_in *)hostmask)->sin_family = AF_INET;
      ((struct sockaddr_in *)hostmask)->sin_len = sizeof (struct in_addr);
      memset (&((struct sockaddr_in *)hostmask)->sin_addr.s_addr, 0xff,
	      sizeof (struct in_addr));
      break;
    case AF_INET6:
      ((struct sockaddr_in6 *)hostmask)->sin6_family = AF_INET6;
      ((struct sockaddr_in6 *)hostmask)->sin6_len = sizeof (struct in6_addr);
      memset (&((struct sockaddr_in6 *)hostmask)->sin6_addr.s6_addr, 0xff,
	      sizeof (struct in6_addr));
      break;
    }

  /* Ingress flows, handling SA bundles. */
  while (TAILQ_NEXT (proto, link))
    {
      error = pf_key_v2_flow (dst, hostmask, src, hostmask, 0, 0, 0,
			      proto->spi[1], proto->proto, src, dst,
			      0, 1, 0, 0, 0, 0, 0, 0);
      if (error)
	goto cleanup;
      proto = TAILQ_NEXT (proto, link);
    }
#endif /* SADB_X_EXT_FLOW_TYPE */

  error = pf_key_v2_flow (isa->dst_net, isa->dst_mask, isa->src_net,
			  isa->src_mask, isa->tproto, isa->dport, isa->sport,
			  proto->spi[1], proto->proto, src, dst, 0, 1,
			  sidtype, sid, sidlen, didtype, did, didlen);

 cleanup:
#ifdef SADB_X_EXT_FLOW_TYPE
  if (sid)
    free (sid);
  if (did)
    free (did);
#endif /* SADB_X_EXT_FLOW_TYPE */

  return error;
}

#ifdef SADB_X_ASKPOLICY
/* Increase reference count of refcounted sections. */
static int
pf_key_v2_conf_refinc (int af, char *section)
{
    unsigned char conn[22];
    int num;

    if (!section)
      return 0;

    num = conf_get_num (section, "Refcount", 0);
    if (num == 0)
      return 0;

    sprintf (conn, "%d", num + 1);
    conf_set (af, section, "Refcount", conn, 1, 0);
    return 0;
}
#endif

/*
 * Return 0 if the section didn't exist or was removed, non-zero otherwise.
 * Don't touch non-refcounted (statically defined) sections.
 */
static int
pf_key_v2_conf_refhandle (int af, char *section)
{
    unsigned char conn[22];
    int num;

    if (!section)
      return 0;

    num = conf_get_num (section, "Refcount", 0);
    if (num == 1)
      {
	conf_remove_section (af, section);
	num--;
      }
    else
      if (num != 0)
        {
	  sprintf (conn, "%d", num - 1);
	  conf_set (af, section, "Refcount", conn, 1, 0);
	}

    return num;
}

/* Remove all dynamically-established configuration entries.  */
static int
pf_key_v2_remove_conf (char *section)
{
    char *ikepeer, *localid, *remoteid, *configname;
    struct conf_list_node *attr;
    struct conf_list *attrs;
    int af;

    if (!section)
      return 0;

    if (!conf_get_str (section, "Phase"))
      return 0;

    /* Only remove dynamically-established entries. */
    attrs = conf_get_list (section, "Flags");
    if (attrs)
      {
	for (attr = TAILQ_FIRST (&attrs->fields); attr;
	     attr = TAILQ_NEXT (attr, link))
	  if (!strcasecmp (attr->field, "__ondemand"))
	    goto passed;

	conf_free_list (attrs);
      }

    return 0;

 passed:
    conf_free_list (attrs);

    af = conf_begin ();

    configname = conf_get_str (section, "Configuration");
    conf_remove_section (af, configname);

    /* These are the Phase 2 Local/Remote IDs. */
    localid = conf_get_str (section, "Local-ID");
    pf_key_v2_conf_refhandle (af, localid);

    remoteid = conf_get_str (section, "Remote-ID");
    pf_key_v2_conf_refhandle (af, remoteid);

    ikepeer = conf_get_str (section, "ISAKMP-peer");

    pf_key_v2_conf_refhandle (af, section);

    if (ikepeer)
      {
	remoteid = conf_get_str (ikepeer, "Remote-ID");
	localid = conf_get_str (ikepeer, "ID");
	configname = conf_get_str (ikepeer, "Configuration");

	pf_key_v2_conf_refhandle (af, ikepeer);
	pf_key_v2_conf_refhandle (af, configname);

	/* Phase 1 IDs */
	pf_key_v2_conf_refhandle (af, localid);
	pf_key_v2_conf_refhandle (af, remoteid);
      }

    conf_end (af, 1);
    return 0;
}

/* Disable a flow given a SA.  */
static int
pf_key_v2_disable_sa (struct sa *sa, int incoming)
{
  struct ipsec_sa *isa = sa->data;
  struct sockaddr *dst, *src;
  struct proto *proto = TAILQ_FIRST (&sa->protos);
#ifndef SADB_X_EXT_FLOW_TYPE
  struct sockaddr_storage hostmask_storage;
  struct sockaddr *hostmask = (struct sockaddr *)&hostmask_storage;
  int error;
#endif /* SADB_X_EXT_FLOW_TYPE */

  sa->transport->vtbl->get_dst (sa->transport, &dst);
  sa->transport->vtbl->get_src (sa->transport, &src);

  if (!incoming)
    return pf_key_v2_flow (isa->src_net, isa->src_mask, isa->dst_net,
			   isa->dst_mask, isa->tproto, isa->sport, isa->dport,
			   proto->spi[0], proto->proto, src, dst, 1, 0,
			   0, 0, 0, 0, 0, 0);
  else
    {
#ifndef SADB_X_EXT_FLOW_TYPE
      /* Set hostmask to '-1'. */
      switch (dst->sa_family)
	{
	case AF_INET:
	  ((struct sockaddr_in *)hostmask)->sin_family = AF_INET;
	  ((struct sockaddr_in *)hostmask)->sin_len = sizeof (struct in_addr);
	  memset (&((struct sockaddr_in *)hostmask)->sin_addr.s_addr, 0xff,
		  sizeof (struct in_addr));
	  break;
	case AF_INET6:
	  ((struct sockaddr_in6 *)hostmask)->sin6_family = AF_INET6;
	  ((struct sockaddr_in6 *)hostmask)->sin6_len =
	    sizeof (struct in6_addr);
	  memset (&((struct sockaddr_in6 *)hostmask)->sin6_addr.s6_addr, 0xff,
		  sizeof (struct in6_addr));
	  break;
	}

      /* Ingress flow --- SA bundles */
      while (TAILQ_NEXT (proto, link))
	{
          error = pf_key_v2_flow (dst, hostmask, src, hostmask, 0, 0, 0,
				  proto->spi[1], proto->proto, src, dst,
				  1, 1, 0, 0, 0, 0, 0, 0);
          if (error)
	    return error;
          proto = TAILQ_NEXT (proto, link);
	}
#endif /* SADB_X_EXT_FLOW_TYPE */

      return pf_key_v2_flow (isa->dst_net, isa->dst_mask, isa->src_net,
			     isa->src_mask, isa->tproto, isa->dport,
			     isa->sport, proto->spi[1], proto->proto,
			     src, dst, 1, 1, 0, 0, 0, 0, 0, 0);
    }
}

/*
 * Delete the IPsec SA represented by the INCOMING direction in protocol PROTO
 * of the IKE security association SA.  Also delete potential flows tied to it.
 */
int
pf_key_v2_delete_spi (struct sa *sa, struct proto *proto, int incoming)
{
  struct sadb_msg msg;
  struct sadb_sa ssa;
  struct sadb_address *addr = 0;
  struct sockaddr *saddr;
  int len, err;
  struct pf_key_v2_msg *delete = 0, *ret = 0;
#ifdef KAME
  struct sadb_x_sa2 ssa2;
#endif

  /* If it's not an established SA, don't proceed. */
  if (!(sa->flags & SA_FLAG_READY))
    return 0;

  /*
   * If the SA was not replaced and was not one acquired through the
   * kernel (ACQUIRE message), remove the flow associated with it.
   * We ignore any errors from the disabling of the flow.
   */
  if (!(sa->flags & SA_FLAG_REPLACED)
      && !(sa->flags & SA_FLAG_ONDEMAND))
    pf_key_v2_disable_sa (sa, incoming);

  if (sa->name && !(sa->flags & SA_FLAG_REPLACED))
    {
      LOG_DBG ((LOG_SYSDEP, 50,
		"pf_key_v2_delete_spi: removing configuration %s",
		sa->name));
      pf_key_v2_remove_conf (sa->name);
    }

  msg.sadb_msg_type = SADB_DELETE;
  switch (proto->proto)
    {
    case IPSEC_PROTO_IPSEC_ESP:
      msg.sadb_msg_satype = SADB_SATYPE_ESP;
      break;
    case IPSEC_PROTO_IPSEC_AH:
      msg.sadb_msg_satype = SADB_SATYPE_AH;
      break;
#ifdef SADB_X_SATYPE_IPCOMP
    case IPSEC_PROTO_IPCOMP:
      msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
      break;
#endif
    default:
      log_print ("pf_key_v2_delete_spi: invalid proto %d", proto->proto);
      goto cleanup;
    }
  msg.sadb_msg_seq = 0;
  delete = pf_key_v2_msg_new (&msg, 0);
  if (!delete)
    goto cleanup;

  /* Setup the SA extension.  */
  ssa.sadb_sa_exttype = SADB_EXT_SA;
  ssa.sadb_sa_len = sizeof ssa / PF_KEY_V2_CHUNK;
  memcpy (&ssa.sadb_sa_spi, proto->spi[incoming], sizeof ssa.sadb_sa_spi);
  ssa.sadb_sa_replay = 0;
  ssa.sadb_sa_state = 0;
  ssa.sadb_sa_auth = 0;
  ssa.sadb_sa_encrypt = 0;
  ssa.sadb_sa_flags = 0;
  if (pf_key_v2_msg_add (delete, (struct sadb_ext *)&ssa, 0) == -1)
    goto cleanup;

#ifdef KAME
  memset (&ssa2, 0, sizeof ssa2);
  ssa2.sadb_x_sa2_exttype = SADB_X_EXT_SA2;
  ssa2.sadb_x_sa2_len = sizeof ssa2 / PF_KEY_V2_CHUNK;
  ssa2.sadb_x_sa2_mode = 0;
  if (pf_key_v2_msg_add (delete, (struct sadb_ext *)&ssa2, 0) == -1)
    goto cleanup;
#endif

  /*
   * Setup the ADDRESS extensions.
   */
  if (incoming)
    sa->transport->vtbl->get_dst (sa->transport, &saddr);
  else
    sa->transport->vtbl->get_src (sa->transport, &saddr);
  len = sizeof *addr + PF_KEY_V2_ROUND (saddr->sa_len);
  addr = calloc (1, len);
  if (!addr)
    goto cleanup;
  addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
  addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
#ifndef __OpenBSD__
  addr->sadb_address_proto = 0;
  addr->sadb_address_prefixlen = 0;
#endif
  addr->sadb_address_reserved = 0;
  memcpy (addr + 1, saddr, saddr->sa_len);
  switch (saddr->sa_family)
    {
    case AF_INET:
      ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
      break;
    case AF_INET6:
      ((struct sockaddr_in6 *)(addr + 1))->sin6_port = 0;
      break;
    }
  if (pf_key_v2_msg_add (delete, (struct sadb_ext *)addr,
			 PF_KEY_V2_NODE_MALLOCED) == -1)
    goto cleanup;
  addr = 0;

  if (incoming)
    sa->transport->vtbl->get_src (sa->transport, &saddr);
  else
    sa->transport->vtbl->get_dst (sa->transport, &saddr);
  len = sizeof *addr + PF_KEY_V2_ROUND (saddr->sa_len);
  addr = calloc (1, len);
  if (!addr)
    goto cleanup;
  addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
  addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
#ifndef __OpenBSD__
  addr->sadb_address_proto = 0;
  addr->sadb_address_prefixlen = 0;
#endif
  addr->sadb_address_reserved = 0;
  memcpy (addr + 1, saddr, saddr->sa_len);
  switch (saddr->sa_family)
    {
    case AF_INET:
      ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
      break;
    case AF_INET6:
      ((struct sockaddr_in6 *)(addr + 1))->sin6_port = 0;
      break;
    }
  if (pf_key_v2_msg_add (delete, (struct sadb_ext *)addr,
			 PF_KEY_V2_NODE_MALLOCED) == -1)
    goto cleanup;
  addr = 0;

  ret = pf_key_v2_call (delete);
  pf_key_v2_msg_free (delete);
  delete = 0;
  if (!ret)
    goto cleanup;
  err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
  if (err)
    {
      LOG_DBG ((LOG_SYSDEP, 10, "pf_key_v2_delete_spi: DELETE: %s",
		strerror (err)));
      goto cleanup;
    }
  pf_key_v2_msg_free (ret);

  LOG_DBG ((LOG_SYSDEP, 50, "pf_key_v2_delete_spi: done"));

  return 0;

 cleanup:
  if (addr)
    free (addr);
  if (delete)
    pf_key_v2_msg_free (delete);
  if (ret)
    pf_key_v2_msg_free (ret);
  return -1;
}

static void
pf_key_v2_stayalive (struct exchange *exchange, void *vconn, int fail)
{
  char *conn = vconn;
  struct sa *sa;

  /* XXX What if it is phase 1 ? */
  sa = sa_lookup_by_name (conn, 2);
  if (sa)
    sa->flags |= SA_FLAG_STAYALIVE;

  /*
   * Remove failed configuration entry -- call twice because it is
   * created with a Refcount of 2.
   */
  if (fail && (!exchange || exchange->name))
    {
      pf_key_v2_remove_conf (conn);
      pf_key_v2_remove_conf (conn);
    }
}

/* Check if a connection CONN exists, otherwise establish it.  */
void
pf_key_v2_connection_check (char *conn)
{
  if (!sa_lookup_by_name (conn, 2))
    {
      LOG_DBG ((LOG_SYSDEP, 70,
		"pf_key_v2_connection_check: SA for %s missing", conn));
      exchange_establish (conn, pf_key_v2_stayalive, conn);
    }
  else
    LOG_DBG ((LOG_SYSDEP, 70, "pf_key_v2_connection_check: SA for %s exists",
	      conn));
}

/* Handle a PF_KEY lifetime expiration message PMSG.  */
static void
pf_key_v2_expire (struct pf_key_v2_msg *pmsg)
{
  struct sadb_msg *msg;
  struct sadb_sa *ssa;
  struct sadb_address *dst;
  struct sockaddr *dstaddr;
  struct sadb_lifetime *life, *lifecurrent;
  struct sa *sa;
  struct pf_key_v2_node *lifenode, *ext;
  char *dst_str;

  msg = (struct sadb_msg *)TAILQ_FIRST (pmsg)->seg;
  ext = pf_key_v2_find_ext (pmsg, SADB_EXT_SA);
  if (!ext)
    {
      log_print ("pf_key_v2_expire: no SA extension found");
      return;
    }
  ssa = ext->seg;
  ext = pf_key_v2_find_ext (pmsg, SADB_EXT_ADDRESS_DST);
  if (!ext)
    {
      log_print ("pf_key_v2_expire: no destination address extension found");
      return;
    }
  dst = ext->seg;
  dstaddr = (struct sockaddr *)(dst + 1);
  lifenode = pf_key_v2_find_ext (pmsg, SADB_EXT_LIFETIME_HARD);
  if (!lifenode)
    lifenode = pf_key_v2_find_ext (pmsg, SADB_EXT_LIFETIME_SOFT);
  if (!lifenode)
    {
      log_print ("pf_key_v2_expire: no lifetime extension found");
      return;
    }
  life = lifenode->seg;

  lifenode = pf_key_v2_find_ext (pmsg, SADB_EXT_LIFETIME_CURRENT);
  if (!lifenode)
    {
      log_print ("pf_key_v2_expire: no current lifetime extension found");
      return;
    }
  lifecurrent = lifenode->seg;

#ifdef USE_DEBUG

  if (sockaddr2text (dstaddr, &dst_str, 0))
    dst_str = 0;

  LOG_DBG ((LOG_SYSDEP, 20, "pf_key_v2_expire: %s dst %s SPI %x sproto %d",
	    life->sadb_lifetime_exttype == SADB_EXT_LIFETIME_SOFT ? "SOFT"
	    : "HARD", dst_str ? dst_str : "<unknown>",
	    ntohl (ssa->sadb_sa_spi), msg->sadb_msg_satype));

  if (dst_str)
    free (dst_str);

#endif /* USE_DEBUG */

  /*
   * Find the IPsec SA.  The IPsec stack has two SAs for every IKE SA,
   * one outgoing and one incoming, we regard expirations for any of
   * them as an expiration of the full IKE SA.  Likewise, in
   * protection suites consisting of more than one protocol, any
   * expired individual IPsec stack SA will be seen as an expiration
   * of the full suite.
   */
  switch (msg->sadb_msg_satype)
    {
    case SADB_SATYPE_ESP:
      sa = ipsec_sa_lookup (dstaddr, ssa->sadb_sa_spi, IPSEC_PROTO_IPSEC_ESP);
      break;

    case SADB_SATYPE_AH:
      sa = ipsec_sa_lookup (dstaddr, ssa->sadb_sa_spi, IPSEC_PROTO_IPSEC_AH);
      break;

#ifdef SADB_X_SATYPE_IPCOMP
    case SADB_X_SATYPE_IPCOMP:
      sa = ipsec_sa_lookup (dstaddr, ssa->sadb_sa_spi, IPSEC_PROTO_IPCOMP);
      break;
#endif

    default:
      /* XXX Log? */
      sa = 0;
      break;
    }

  /* If the SA is already gone, don't do anything.  */
  if (!sa)
    return;

  /*
   * If we got a notification, try to renegotiate the SA -- unless of
   * course it has already been replaced by another.
   * Also, ignore SAs that were not dynamically established, or that
   * did not see any use.
   */
  if (!(sa->flags & SA_FLAG_REPLACED) && (sa->flags & SA_FLAG_ONDEMAND) &&
      lifecurrent->sadb_lifetime_bytes)
    exchange_establish (sa->name, 0, 0);

  if (life->sadb_lifetime_exttype == SADB_EXT_LIFETIME_HARD)
    {
      /* Remove the old SA, it isn't useful anymore.  */
      sa_free (sa);
    }
}

/* Handle a PF_KEY SA ACQUIRE message PMSG.  */
static void
pf_key_v2_acquire (struct pf_key_v2_msg *pmsg)
{
#ifndef SADB_X_ASKPOLICY
  return;
#else
  struct sadb_msg *msg, askpolicy_msg;
  struct pf_key_v2_msg *askpolicy = 0, *ret = 0;
  struct sadb_x_policy policy;
  struct sadb_address *dst = 0, *src = 0;
  struct sockaddr *dstaddr, *srcaddr = 0;
  struct sadb_comb *scmb = 0;
  struct sadb_prop *sprp = 0;
  struct sadb_ident *srcident = 0, *dstident = 0;
  char dstbuf[ADDRESS_MAX], srcbuf[ADDRESS_MAX], *peer = 0, *conn = 0;
  char confname[120];
  char *srcid = 0, *dstid = 0, *prefstring = 0;
  int slen, af, afamily, masklen;
  struct sockaddr *smask, *sflow, *dmask, *dflow;
  struct sadb_protocol *sproto;
  char ssflow[ADDRESS_MAX], sdflow[ADDRESS_MAX];
  char sdmask[ADDRESS_MAX], ssmask[ADDRESS_MAX];
  char lname[100], dname[100], configname[30];
  int shostflag = 0, dhostflag = 0;
  struct pf_key_v2_node *ext;
  struct passwd *pwd = 0;
  u_int16_t sport = 0, dport = 0;
  u_int8_t tproto = 0;
  char tmbuf[sizeof sport * 3 + 1];
#ifdef SADB_X_CREDTYPE_NONE
  struct sadb_x_cred *cred = 0, *sauth = 0;
#endif

  /* This needs to be dynamically allocated. */
  conn = malloc (22);
  if (!conn)
    {
      log_error ("pf_key_v2_acquire: malloc (22) failed");
      return;
    }

  msg = (struct sadb_msg *)TAILQ_FIRST (pmsg)->seg;

  ext = pf_key_v2_find_ext (pmsg, SADB_EXT_ADDRESS_DST);
  if (!ext)
    {
      log_print ("pf_key_v2_acquire: no destination address specified");
      return;
    }
  dst = ext->seg;

  ext = pf_key_v2_find_ext (pmsg, SADB_EXT_ADDRESS_SRC);
  if (ext)
    src = ext->seg;

  ext = pf_key_v2_find_ext (pmsg, SADB_EXT_PROPOSAL);
  if (ext)
    {
      sprp = ext->seg;
      scmb = (struct sadb_comb *)(sprp + 1);
    }

  ext = pf_key_v2_find_ext (pmsg, SADB_EXT_IDENTITY_SRC);
  if (ext)
    srcident = ext->seg;

  ext = pf_key_v2_find_ext (pmsg, SADB_EXT_IDENTITY_DST);
  if (ext)
    dstident = ext->seg;

  /* Ask the kernel for the matching policy. */
  bzero (&askpolicy_msg, sizeof askpolicy_msg);
  askpolicy_msg.sadb_msg_type = SADB_X_ASKPOLICY;
  askpolicy = pf_key_v2_msg_new (&askpolicy_msg, 0);
  if (!askpolicy)
    goto fail;

  policy.sadb_x_policy_exttype = SADB_X_EXT_POLICY;
  policy.sadb_x_policy_len = sizeof policy / PF_KEY_V2_CHUNK;
  policy.sadb_x_policy_seq = msg->sadb_msg_seq;
  if (pf_key_v2_msg_add (askpolicy, (struct sadb_ext *)&policy, 0) == -1)
    goto fail;

  ret = pf_key_v2_call (askpolicy);
  if (!ret)
    goto fail;

  /* Now we have all the information needed. */

  ext = pf_key_v2_find_ext (ret, SADB_X_EXT_SRC_FLOW);
  if (!ext)
    {
      log_print ("pf_key_v2_acquire: no source flow extension found");
      goto fail;
    }
  sflow = (struct sockaddr *)(((struct sadb_address *)ext->seg) + 1);

  ext = pf_key_v2_find_ext (ret, SADB_X_EXT_DST_FLOW);
  if (!ext)
    {
      log_print ("pf_key_v2_acquire: no destination flow extension found");
      goto fail;
    }
  dflow = (struct sockaddr *)(((struct sadb_address *)ext->seg) + 1);
  ext = pf_key_v2_find_ext (ret, SADB_X_EXT_SRC_MASK);
  if (!ext)
    {
      log_print ("pf_key_v2_acquire: no source mask extension found");
      goto fail;
    }
  smask = (struct sockaddr *)(((struct sadb_address *)ext->seg) + 1);

  ext = pf_key_v2_find_ext (ret, SADB_X_EXT_DST_MASK);
  if (!ext)
    {
      log_print ("pf_key_v2_acquire: no destination mask extension found");
      goto fail;
    }
  dmask = (struct sockaddr *)(((struct sadb_address *)ext->seg) + 1);

  ext = pf_key_v2_find_ext (ret, SADB_X_EXT_FLOW_TYPE);
  if (!ext)
    {
      log_print ("pf_key_v2_acquire: no flow type extension found");
      goto fail;
    }
  sproto = ext->seg;
  tproto = sproto->sadb_protocol_proto;

#ifdef SADB_X_EXT_LOCAL_CREDENTIALS
  cred
    = (struct sadb_x_cred *)pf_key_v2_find_ext (ret,
						SADB_X_EXT_LOCAL_CREDENTIALS);
#endif

#ifdef SADB_X_EXT_LOCAL_AUTH
  sauth = (struct sadb_x_cred *)pf_key_v2_find_ext (ret,
						    SADB_X_EXT_LOCAL_AUTH);
#endif

  bzero (ssflow, sizeof ssflow);
  bzero (sdflow, sizeof sdflow);
  bzero (ssmask, sizeof ssmask);
  bzero (sdmask, sizeof sdmask);

  switch (sflow->sa_family)
    {
    case AF_INET:
      if (inet_ntop (AF_INET, &((struct sockaddr_in *)sflow)->sin_addr, ssflow,
		     ADDRESS_MAX) == NULL)
	{
	  log_print ("pf_key_v2_acquire: inet_ntop failed");
	  goto fail;
	}
      sport = ((struct sockaddr_in *)sflow)->sin_port;
      if (inet_ntop (AF_INET, &((struct sockaddr_in *)dflow)->sin_addr, sdflow,
		     ADDRESS_MAX) == NULL)
	{
	  log_print ("pf_key_v2_acquire: inet_ntop failed");
	  goto fail;
	}
      dport = ((struct sockaddr_in *)dflow)->sin_port;
      if (inet_ntop (AF_INET, &((struct sockaddr_in *)smask)->sin_addr, ssmask,
		     ADDRESS_MAX) == NULL)
	{
	  log_print ("pf_key_v2_acquire: inet_ntop failed");
	  goto fail;
	}
      if (inet_ntop (AF_INET, &((struct sockaddr_in *)dmask)->sin_addr, sdmask,
		     ADDRESS_MAX) == NULL)
	{
	  log_print ("pf_key_v2_acquire: inet_ntop failed");
	  goto fail;
	}
      if (((struct sockaddr_in *)smask)->sin_addr.s_addr == INADDR_BROADCAST)
	shostflag = 1;
      if (((struct sockaddr_in *)dmask)->sin_addr.s_addr == INADDR_BROADCAST)
	dhostflag = 1;
      break;

    case AF_INET6:
      if (inet_ntop (AF_INET6, &((struct sockaddr_in6 *)sflow)->sin6_addr,
		     ssflow, ADDRESS_MAX) == NULL)
	{
	  log_print ("pf_key_v2_acquire: inet_ntop failed");
	  goto fail;
	}
      sport = ((struct sockaddr_in6 *)sflow)->sin6_port;
      if (inet_ntop (AF_INET6, &((struct sockaddr_in6 *)dflow)->sin6_addr,
		     sdflow, ADDRESS_MAX) == NULL)
	{
	  log_print ("pf_key_v2_acquire: inet_ntop failed");
	  goto fail;
	}
      dport = ((struct sockaddr_in6 *)dflow)->sin6_port;
      if (inet_ntop (AF_INET6, &((struct sockaddr_in6 *)smask)->sin6_addr,
		     ssmask, ADDRESS_MAX) == NULL)
	{
	  log_print ("pf_key_v2_acquire: inet_ntop failed");
	  goto fail;
	}
      if (inet_ntop (AF_INET6, &((struct sockaddr_in6 *)dmask)->sin6_addr,
		     sdmask, ADDRESS_MAX) == NULL)
	{
	  log_print ("pf_key_v2_acquire: inet_ntop failed");
	  goto fail;
	}
      if (IN6_IS_ADDR_FULL (&((struct sockaddr_in6 *)smask)->sin6_addr))
	shostflag = 1;
      if (IN6_IS_ADDR_FULL (&((struct sockaddr_in6 *)dmask)->sin6_addr))
	dhostflag = 1;
      break;
    }

  dstaddr = (struct sockaddr *)(dst + 1);
  bzero (dstbuf, sizeof dstbuf);
  bzero (srcbuf, sizeof srcbuf);

  switch (dstaddr->sa_family)
    {
    case AF_INET:
      if (inet_ntop (AF_INET, &((struct sockaddr_in *)dstaddr)->sin_addr,
		     dstbuf, ADDRESS_MAX) == NULL)
	{
	  log_print ("pf_key_v2_acquire: inet_ntop failed");
	  goto fail;
	}
      LOG_DBG ((LOG_SYSDEP, 20, "pf_key_v2_acquire: dst=%s sproto %d", dstbuf,
		msg->sadb_msg_satype));
      break;

    case AF_INET6:
      if (inet_ntop (AF_INET6, &((struct sockaddr_in6 *)dstaddr)->sin6_addr,
		     dstbuf, ADDRESS_MAX) == NULL)
	{
	  log_print ("pf_key_v2_acquire: inet_ntop failed");
	  goto fail;
	}
      LOG_DBG ((LOG_SYSDEP, 20, "pf_key_v2_acquire: dst=%s sproto %d", dstbuf,
		msg->sadb_msg_satype));
      break;
    }

  if (src)
    {
      srcaddr = (struct sockaddr *)(src + 1);

      switch (srcaddr->sa_family)
        {
	case AF_INET:
	  if (inet_ntop (AF_INET, &((struct sockaddr_in *)srcaddr)->sin_addr,
			 srcbuf, ADDRESS_MAX) == NULL)
	    {
	      log_print ("pf_key_v2_acquire: inet_ntop failed");
	      goto fail;
	    }
	  break;

	case AF_INET6:
	  if (inet_ntop (AF_INET6,
			 &((struct sockaddr_in6 *)srcaddr)->sin6_addr, srcbuf,
			 ADDRESS_MAX) == NULL)
	    {
	      log_print ("pf_key_v2_acquire: inet_ntop failed");
	      goto fail;
	    }
	  break;
	}
    }

  /* Insert source ID. */
  if (srcident)
    {
      slen = (srcident->sadb_ident_len * sizeof (u_int64_t))
	- sizeof (struct sadb_ident);
      if (((unsigned char *)(srcident + 1))[slen - 1] != '\0')
	{
	  log_print ("pf_key_v2_acquire: source identity not NUL-terminated");
	  goto fail;
	}

      /* Check for valid type. */
      switch (srcident->sadb_ident_type)
        {
#ifdef SADB_X_IDENTTYPE_CONNECTION
	case SADB_X_IDENTTYPE_CONNECTION:
	  /* XXX */
	  break;
#endif

	case SADB_IDENTTYPE_PREFIX:
	  /* Determine what the address family is. */
	  srcid = memchr (srcident + 1, ':', slen);
	  if (srcid)
	    afamily = AF_INET6;
	  else
	    afamily = AF_INET;

	  srcid = memchr (srcident + 1, '/', slen);
	  if (!srcid)
	    {
	      log_print ("pf_key_v2_acquire: badly formatted PREFIX identity");
	      goto fail;
	    }

	  masklen = atoi (srcid + 1);

	  /* XXX We only support host addresses. */
	  if ((afamily == AF_INET6 && masklen != 128)
	      || (afamily == AF_INET && masklen != 32))
	    {
	      log_print ("pf_key_v2_acquire: non-host address specified in "
			 "source identity (mask length %d), ignoring request",
			 masklen);
	      goto fail;
	    }

	  /* NUL-terminate the PREFIX string at the separator, then dup. */
	  *srcid = '\0';
	  slen = strlen ((char *)(srcident + 1)) + sizeof "ID:Address/";
	  srcid = malloc (slen);
	  if (!srcid)
	    {
	      log_error ("pf_key_v2_acquire: malloc (%d) failed", slen);
	      goto fail;
	    }

	  sprintf (srcid, "ID:Address/%s", (char *)(srcident + 1));

	  /* Set the section if it doesn't already exist. */
	  af = conf_begin ();
	  if (!conf_get_str (srcid, "ID-type"))
	    {
	      if (conf_set (af, srcid, "ID-type",
			    afamily == AF_INET ? "IPV4_ADDR" : "IPV6_ADDR",
			    1, 0)
		  || conf_set (af, srcid, "Refcount", "1", 1, 0)
		  || conf_set (af, srcid, "Address", (char *)(srcident + 1),
			       1, 0))
		{
		  conf_end (af, 0);
		  goto fail;
		}
	    }
	  else
	    pf_key_v2_conf_refinc (af, srcid);
	  conf_end (af, 1);
	  break;

	case SADB_IDENTTYPE_FQDN:
	  prefstring = "FQDN";
	  /* Fall through */
	case SADB_IDENTTYPE_USERFQDN:
	  if (!prefstring)
	    {
	      prefstring = "USER_FQDN";

	      /*
	       * Check whether there is a string following the header;
	       * if no, that there is a user ID (and acquire the login
	       * name). If there is both a string and a user ID, check
	       * that they match.
	       */
	      if ((slen == 0) && (srcident->sadb_ident_id == 0))
	        {
		  log_print ("pf_key_v2_acquire: no user FQDN or ID provided");
		  goto fail;
		}

	      if (srcident->sadb_ident_id)
	        {
		  pwd = getpwuid (srcident->sadb_ident_id);
		  if (!pwd)
		    {
		      log_error ("pf_key_v2_acquire: could not acquire "
				 "username from provided ID %d",
				 srcident->sadb_ident_id);
		      goto fail;
		    }

		  if (slen != 0)
		    if (strcmp (pwd->pw_name, (char *)(srcident + 1)) != 0)
		      {
			log_print ("pf_key_v2_acquire: provided user name and "
				   "ID do not match (%s != %s)",
				   (char *)(srcident + 1), pwd->pw_name);
			/* String has precedence, per RFC 2367. */
		      }
		}
	    }

	  srcid = malloc ((slen ? slen : strlen (pwd->pw_name))
			  + strlen (prefstring) + sizeof "ID:/");
	  if (!srcid)
	    {
	      log_error ("pf_key_v2_acquire: malloc (%d) failed",
			 slen ? slen : strlen (pwd->pw_name)
			 + strlen (prefstring) + sizeof "ID:/");
	      goto fail;
	    }

	  sprintf (srcid, "ID:%s/", prefstring);
	  if (slen != 0)
	    strlcat (srcid + sizeof "ID:/" - 1 + strlen (prefstring),
		     (char *)(srcident + 1),
		     slen + strlen (prefstring) + sizeof "ID:/");
	  else
	    strlcat (srcid + sizeof "ID:/" - 1 + strlen (prefstring),
		     pwd->pw_name, strlen (prefstring) + sizeof "ID:/");
	  pwd = 0;

	  /* Set the section if it doesn't already exist. */
	  af = conf_begin ();
	  if (!conf_get_str (srcid, "ID-type"))
	    {
	      if (conf_set (af, srcid, "ID-type", prefstring, 1, 0)
		  || conf_set (af, srcid, "Refcount", "1", 1, 0)
		  || conf_set (af, srcid, "Name",
			       srcid + sizeof "ID:/" - 1 + strlen (prefstring),
			       1, 0))
		{
		  conf_end (af, 0);
		  goto fail;
		}
	    }
	  else
	    pf_key_v2_conf_refinc (af, srcid);
	  conf_end (af, 1);
	  break;

	default:
	  LOG_DBG ((LOG_SYSDEP, 20,
		    "pf_key_v2_acquire: invalid source ID type %d",
		    srcident->sadb_ident_type));
	  goto fail;
	}

      LOG_DBG ((LOG_SYSDEP, 50,
		"pf_key_v2_acquire: constructed source ID \"%s\"", srcid));
      prefstring = 0;
    }

  /* Insert destination ID. */
  if (dstident)
    {
      slen = (dstident->sadb_ident_len * sizeof (u_int64_t))
	- sizeof (struct sadb_ident);

      /* Check for valid type. */
      switch (dstident->sadb_ident_type)
        {
#ifdef SADB_X_IDENTTYPE_CONNECTION
	case SADB_X_IDENTTYPE_CONNECTION:
	  /* XXX */
	  break;
#endif

	case SADB_IDENTTYPE_PREFIX:
	  /* Determine what the address family is. */
	  dstid = memchr (dstident + 1, ':', slen);
	  if (dstid)
	    afamily = AF_INET6;
	  else
	    afamily = AF_INET;

	  dstid = memchr (dstident + 1, '/', slen);
	  if (!dstid)
	    {
	      log_print ("pf_key_v2_acquire: badly formatted PREFIX identity");
	      goto fail;
	    }

	  masklen = atoi (dstid + 1);

	  /* XXX We only support host addresses. */
	  if ((afamily == AF_INET6 && masklen != 128)
	      || (afamily == AF_INET && masklen != 32))
	    {
	      log_print ("pf_key_v2_acquire: non-host address specified in "
			 "destination identity (mask length %d), ignoring "
			 "request",
			 masklen);
	      goto fail;
	    }

	  /* NUL-terminate the PREFIX string at the separator, then dup. */
	  *dstid = '\0';
	  slen = strlen ((char *)(dstident + 1)) + sizeof "ID:Address/";
	  dstid = malloc (slen);
	  if (!dstid)
	    {
	      log_error ("pf_key_v2_acquire: malloc (%d) failed", slen);
	      goto fail;
	    }

	  sprintf (dstid, "ID:Address/%s", (char *)(dstident + 1));

	  /* Set the section if it doesn't already exist. */
	  af = conf_begin ();
	  if (!conf_get_str (dstid, "ID-type"))
	    {
	      if (conf_set (af, dstid, "ID-type",
			    afamily == AF_INET ? "IPV4_ADDR" : "IPV6_ADDR",
			    1, 0)
		  || conf_set (af, dstid, "Refcount", "1", 1, 0)
		  || conf_set (af, dstid, "Address", (char *)(dstident + 1),
			       1, 0))
		{
		  conf_end (af, 0);
		  goto fail;
		}
	    }
	  else
	    pf_key_v2_conf_refinc (af, dstid);
	  conf_end (af, 1);
	  break;

	case SADB_IDENTTYPE_FQDN:
	  prefstring = "FQDN";
	  /* Fall through */

	case SADB_IDENTTYPE_USERFQDN:
	  if (!prefstring)
	    {
	      prefstring = "USER_FQDN";

	      /*
	       * Check whether there is a string following the header;
	       * if no, that there is a user ID (and acquire the login
	       * name). If there is both a string and a user ID, check
	       * that they match.
	       */
	      if (slen == 0 && dstident->sadb_ident_id == 0)
	        {
		  log_print ("pf_key_v2_acquire: no user FQDN or ID provided");
		  goto fail;
		}

	      if (dstident->sadb_ident_id)
	        {
		  pwd = getpwuid (dstident->sadb_ident_id);
		  if (!pwd)
		    {
		      log_error ("pf_key_v2_acquire: could not acquire "
				 "username from provided ID %d",
				 dstident->sadb_ident_id);
		      goto fail;
		    }

		  if (slen != 0)
		    if (strcmp (pwd->pw_name, (char *)(dstident + 1)) != 0)
		      {
			log_print ("pf_key_v2_acquire: provided user name and "
				   "ID do not match (%s != %s)",
				   (char *)(dstident + 1), pwd->pw_name);
			/* String has precedence, per RF 2367. */
		      }
		}
	    }

	  dstid = malloc ((slen ? slen : strlen (pwd->pw_name))
			  + strlen (prefstring) + sizeof "ID:/");
	  if (!dstid)
	    {
	      log_error ("pf_key_v2_acquire: malloc (%d) failed",
			 slen ? slen : strlen (pwd->pw_name)
			 + strlen (prefstring) + sizeof "ID:/");
	      goto fail;
	    }

	  sprintf (dstid, "ID:%s/", prefstring);
	  if (slen != 0)
	    strlcat (dstid + sizeof "ID:/" - 1 + strlen (prefstring),
		     (char *)(dstident + 1),
		     slen + strlen (prefstring) + sizeof "ID:/");
	  else
	    strlcat (dstid + sizeof "ID:/" - 1 + strlen (prefstring),
		     pwd->pw_name,
		     strlen (prefstring) + sizeof "ID:/");
	  pwd = 0;

	  /* Set the section if it doesn't already exist. */
	  af = conf_begin ();
	  if (!conf_get_str (dstid, "ID-type"))
	    {
	      if (conf_set (af, dstid, "ID-type", prefstring, 1, 0)
		  || conf_set (af, dstid, "Refcount", "1", 1, 0)
		  || conf_set (af, dstid, "Name",
			       dstid + sizeof "ID:/" - 1 + strlen (prefstring),
			       1, 0))
		{
		  conf_end (af, 0);
		  goto fail;
		}
	    }
	  else
	    pf_key_v2_conf_refinc (af, dstid);
	  conf_end (af, 1);
	  break;

	default:
	  LOG_DBG ((LOG_SYSDEP, 20,
		    "pf_key_v2_acquire: invalid destination ID type %d",
		    dstident->sadb_ident_type));
	  goto fail;
	}

      LOG_DBG ((LOG_SYSDEP, 50,
		"pf_key_v2_acquire: constructed destination ID \"%s\"",
		dstid));
    }

  /* Now we've placed the necessary IDs in the configuration space. */

  /* Get a new connection sequence number. */
  for (;; connection_seq++)
    {
      sprintf (conn, "Connection-%u", connection_seq);
      sprintf (configname, "Config-Phase2-%u", connection_seq);

      /* Does it exist ? */
      if (!conf_get_str (conn, "Phase")
	  && !conf_get_str (configname, "Suites"))
	break;
    }

  /*
   * Set the IPsec connection entry. In particular, the following fields:
   * - Phase
   * - ISAKMP-peer
   * - Local-ID/Remote-ID (if provided)
   * - Acquire-ID (sequence number of kernel message, e.g., PF_KEYv2)
   * - Configuration
   *
   * Also set the following section:
   *    [Peer-dstaddr(/srcaddr)(-srcid)(/dstid)]
   * with these fields:
   * - Phase
   * - ID (if provided)
   * - Remote-ID (if provided)
   * - Local-address (if provided)
   * - Address
   * - Configuration (if an entry "ISAKMP-configuration-dstaddr(/srcaddr)"
   *                  exists -- otherwise use the defaults)
   */

  peer = malloc (strlen (dstbuf) + strlen (srcbuf)
                 + (srcid ? strlen (srcid) : 0)
		 + (dstid ? strlen (dstid) : 0) + sizeof "Peer-/-/");
  if (!peer)
    goto fail;

  /*
   * The various cases:
   * - Peer-dstaddr
   * - Peer-dstaddr/srcaddr
   * - Peer-dstaddr/srcaddr-srcid
   * - Peer-dstaddr/srcaddr-srcid/dstid
   * - Peer-dstaddr/srcaddr-/dstid
   * - Peer-dstaddr-srcid/dstid
   * - Peer-dstaddr-/dstid
   * - Peer-dstaddr-srcid
   */
  sprintf (peer, "Peer-%s%s%s%s%s%s%s", dstbuf, srcaddr ? "/" : "",
	   srcaddr ? srcbuf : "", srcid ? "-" : "", srcid ? srcid : "",
	   dstid ? (srcid ? "/" : "-/") : "", dstid ? dstid : "");

  /*
   * Set the IPsec connection section. Refcount is set to 2, because
   * it will be linked both to the incoming and the outgoing SA.
   */
  af = conf_begin ();
  if (conf_set (af, conn, "Phase", "2", 0, 0)
      || conf_set (af, conn, "Flags", "__ondemand", 0 , 0)
      || conf_set (af, conn, "Refcount", "2", 0 , 0)
      || conf_set (af, conn, "ISAKMP-peer", peer, 0, 0))
    {
      conf_end (af, 0);
      goto fail;
    }

  /* Set the sequence number. */
  sprintf (lname, "%u", msg->sadb_msg_seq);
  if (conf_set (af, conn, "Acquire-ID", lname, 0, 0))
    {
      conf_end (af, 0);
      goto fail;
    }

  /* Set Phase 2 IDs -- this is the Local-ID section. */
  sprintf (lname, "Phase2-ID:%s/%s/%u/%u", ssflow, ssmask, tproto, sport);
  if (conf_set (af, conn, "Local-ID", lname, 0, 0))
    {
      conf_end (af, 0);
      goto fail;
    }

  if (!conf_get_str (lname, "ID-type"))
    {
      if (conf_set (af, lname, "Refcount", "1", 0, 0))
	{
	  conf_end (af, 0);
	  goto fail;
	}

      if (shostflag)
        {
	  if (conf_set (af, lname, "ID-type", "IPV4_ADDR", 0, 0)
	      || conf_set (af, lname, "Address", ssflow, 0, 0))
	    {
	      conf_end (af, 0);
	      goto fail;
	    }
	}
      else
        {
	  if (conf_set (af, lname, "ID-type", "IPV4_ADDR_SUBNET", 0, 0)
	      || conf_set (af, lname, "Network", ssflow, 0, 0)
	      || conf_set (af, lname, "Netmask", ssmask, 0, 0))
	    {
	      conf_end (af, 0);
	      goto fail;
	    }
	}
      if (tproto)
        {
	  sprintf (tmbuf, "%u", tproto);
	  if (conf_set (af, lname, "Protocol", tmbuf, 0, 0))
	    {
	      conf_end (af, 0);
	      goto fail;
	    }

	  if (sport)
	    {
	      sprintf (tmbuf, "%u", ntohs (sport));
	      if (conf_set (af, lname, "Port", tmbuf, 0, 0))
	        {
		  conf_end (af, 0);
		  goto fail;
		}
	    }
	}
    }
  else
    pf_key_v2_conf_refinc (af, lname);

  /* Set Remote-ID section. */
  sprintf (dname, "Phase2-ID:%s/%s/%u/%u", sdflow, sdmask, tproto, dport);
  if (conf_set (af, conn, "Remote-ID", dname, 0, 0))
    {
      conf_end (af, 0);
      goto fail;
    }

  if (!conf_get_str (dname, "ID-type"))
    {
      if (conf_set (af, dname, "Refcount", "1", 0, 0))
	{
	  conf_end (af, 0);
	  goto fail;
	}

      if (dhostflag)
        {
	  if (conf_set (af, dname, "ID-type", "IPV4_ADDR", 0, 0)
	      || conf_set (af, dname, "Address", sdflow, 0, 0))
	    {
	      conf_end (af, 0);
	      goto fail;
	    }
	}
      else
        {
	  if (conf_set (af, dname, "ID-type", "IPV4_ADDR_SUBNET", 0, 0)
	      || conf_set (af, dname, "Network", sdflow, 0, 0)
	      || conf_set (af, dname, "Netmask", sdmask, 0, 0))
	    {
	      conf_end (af, 0);
	      goto fail;
	    }
	}

      if (tproto)
        {
	  sprintf (tmbuf, "%u", tproto);
	  if (conf_set (af, dname, "Protocol", tmbuf, 0, 0))
	    {
	      conf_end (af, 0);
	      goto fail;
	    }

	  if (dport)
	    {
	      sprintf (tmbuf, "%u", ntohs (dport));
	      if (conf_set (af, dname, "Port", tmbuf, 0, 0))
	        {
		  conf_end (af, 0);
		  goto fail;
		}
	    }
	}
    }
  else
    pf_key_v2_conf_refinc (af, dname);

  /*
   * XXX
   * We should be using information from the proposal to set this up.
   * At least, we should make this selectable.
   */

  /* Phase 2 configuration. */
  if (conf_set (af, conn, "Configuration", configname, 0, 0))
    {
      conf_end (af, 0);
      goto fail;
    }

  if (conf_set (af, configname, "Exchange_type", "Quick_mode", 0, 0)
      || conf_set (af, configname, "DOI", "IPSEC", 0, 0))
    {
      conf_end (af, 0);
      goto fail;
    }

  if (conf_get_str ("General", "Default-Phase-2-Suites"))
    {
      if (conf_set (af, configname, "Suites",
		    conf_get_str ("General", "Default-Phase-2-Suites"), 0, 0))
        {
	  conf_end (af, 0);
	  goto fail;
	}
    }
  else
    {
      if (conf_set (af, configname, "Suites",
		    "QM-ESP-3DES-SHA-PFS-SUITE", 0, 0))
        {
	  conf_end (af, 0);
	  goto fail;
	}
    }

  /* Set the ISAKMP-peer section. */
  if (!conf_get_str (peer, "Phase"))
    {
      if (conf_set (af, peer, "Phase", "1", 0, 0)
	  || conf_set (af, peer, "Refcount", "1", 0, 0)
	  || conf_set (af, peer, "Address", dstbuf, 0, 0))
        {
	  conf_end (af, 0);
	  goto fail;
        }

      if (srcaddr && conf_set (af, peer, "Local-address", srcbuf, 0, 0))
	{
	  conf_end (af, 0);
	  goto fail;
	}

      sprintf (confname, "ISAKMP-Configuration-%s", peer);
      if (conf_set (af, peer, "Configuration", confname, 0, 0))
        {
	  conf_end (af, 0);
	  goto fail;
	}

#ifdef SADB_X_CREDTYPE_NONE
      /* Store any credentials passed to us. */
      if (cred)
	{
	  struct cert_handler *handler = 0;
	  void *cert;
	  char num[10], *certprint;

	  /* Convert to bytes in-place. */
	  cred->sadb_x_cred_len *= PF_KEY_V2_CHUNK;

	  if (cred->sadb_x_cred_len <= sizeof *cred)
	    {
	      log_print ("pf_key_v2_set_spi: zero-length credentials, "
			 "aborting SA acquisition");
	      conf_end (af, 0);
	      goto fail;
	    }

	  switch (cred->sadb_x_cred_type)
	    {
	    case SADB_X_CREDTYPE_X509:
	      sprintf (num, "%d", ISAKMP_CERTENC_X509_SIG);
	      handler = cert_get (ISAKMP_CERTENC_X509_SIG);
	      break;
	    case SADB_X_CREDTYPE_KEYNOTE:
	      sprintf (num, "%d", ISAKMP_CERTENC_KEYNOTE);
	      handler = cert_get (ISAKMP_CERTENC_KEYNOTE);
	      break;
	    default:
	      log_print ("pf_key_v2_set_spi: unknown credential type %d",
			 cred->sadb_x_cred_type);
	      conf_end (af, 0);
	      goto fail;
	    }

	  if (!handler)
	    {
	      log_print ("pf_key_v2_set_spi: cert_get (%s) failed", num);
	      conf_end (af, 0);
	      goto fail;
	    }

	  /* Set the credential type as a number. */
	  if (conf_set (af, peer, "Credential_type", num, 0, 0))
	    {
	      conf_end (af, 0);
	      goto fail;
	    }

	  /* Get the certificate. */
	  cert = handler->cert_get ((u_int8_t *)(cred + 1),
				    cred->sadb_x_cred_len - sizeof *cred);

	  /* Now convert to printable format. */
	  certprint = handler->cert_printable (cert);
	  handler->cert_free (cert);
	  if (!certprint
	      || conf_set (af, peer, "Credentials", certprint, 0, 0))
	    {
	      if (certprint)
		free (certprint);
	      conf_end (af, 0);
	      goto fail;
	    }
	  free (certprint);
	}
#endif /* SADB_X_CREDTYPE_NONE */

      /* Phase 1 configuration. */
      if (!conf_get_str (confname, "exchange_type"))
        {
#ifdef SADB_X_CREDTYPE_NONE
	  /* We may have been provided with authentication material. */
	  if (sauth)
	    {
	      u_int8_t *authm;

	      /* Convert to bytes in-place. */
	      sauth->sadb_x_cred_len *= PF_KEY_V2_CHUNK;

	      switch (sauth->sadb_x_cred_type)
		{
		case SADB_X_AUTHTYPE_PASSPHRASE:
		  if (conf_set (af, confname, "Transforms", "3DES-SHA", 0, 0))
		    {
		      conf_end (af, 0);
		      goto fail;
		    }

		  if (sauth->sadb_x_cred_len <= sizeof *sauth)
		    {
		      log_print ("pf_key_v2_set_spi: zero-length passphrase, "
				 "aborting SA acquisition");
		      conf_end (af, 0);
		      goto fail;
		    }

		  authm = malloc (sauth->sadb_x_cred_len - sizeof *sauth + 1);
		  if (!authm)
		    {
		      log_error ("pf_key_v2_set_spi: malloc (%d) failed",
				 sauth->sadb_x_cred_len - sizeof *sauth + 1);
		      conf_end (af, 0);
		      goto fail;
		    }
		  memcpy (authm, sauth + 1,
			  sauth->sadb_x_cred_len - sizeof *sauth + 1);

		  /* Set the passphrase in the peer. */
		  if (conf_set (af, peer, "Authentication", authm, 0, 0))
		    {
		      free (authm);
		      conf_end (af, 0);
		      goto fail;
		    }
		  free (authm);
		  break;

		case SADB_X_AUTHTYPE_RSA:
		  if (conf_set (af, confname, "Transforms", "3DES-SHA-RSA_SIG",
				0, 0))
		    {
		      conf_end (af, 0);
		      goto fail;
		    }

		  if (sauth->sadb_x_cred_len <= sizeof *sauth)
		    {
		      log_print ("pf_key_v2_set_spi: zero-length RSA key, "
				 "aborting SA acquisition");
		      conf_end (af, 0);
		      goto fail;
		    }

		  authm = key_printable (ISAKMP_KEY_RSA,
					 ISAKMP_KEYTYPE_PRIVATE,
					 (u_int8_t *) sauth + 1,
					 sauth->sadb_x_cred_len
					 - sizeof *sauth);
		  if (!authm)
		    {
		      log_print ("pf_key_v2_set_spi: failed to convert "
				 "private key to printable format (size %d)",
				 sauth->sadb_x_cred_len - sizeof *sauth);
		      conf_end (af, 0);
		      goto fail;
		    }

		  /*
		   * Set the key in the peer. We don't use "Authentication"
		   * to avoid potential conflicts with file-based
		   * configurations that use public key authentication
		   * but still specify an "Authentication" tag (typically
		   * as a remnant of passphrase-based testing).
		   */
		  if (conf_set (af, peer, "PKAuthentication", authm, 0, 0))
		    {
		      free (authm);
		      conf_end (af, 0);
		      goto fail;
		    }
		  free (authm);
		  break;

		default:
		  log_print ("pf_key_v2_set_spi: unknown authentication "
			     "material type %d received from kernel",
			     sauth->sadb_x_cred_type);
		  conf_end (af, 0);
		  goto fail;
		}
	    }
	  else /* Fall through */
#endif /* SADB_X_CREDTYPE_NONE */
	  /* XXX Default transform set should be settable. */
	  if (conf_set (af, confname, "Transforms", "3DES-SHA-RSA_SIG", 0, 0))
	    {
	      conf_end (af, 0);
	      goto fail;
	    }

	  if (conf_set (af, confname, "Exchange_Type", "ID_PROT", 0, 0)
	      || conf_set (af, confname, "DOI", "IPSEC", 0, 0)
	      || conf_set (af, confname, "Refcount", "1", 0, 0))
	    {
	      conf_end (af, 0);
	      goto fail;
	    }
	}
      else
	pf_key_v2_conf_refinc (af, confname);

      /* The ID we should use in Phase 1. */
      if (srcid && conf_set (af, peer, "ID", srcid, 0, 0))
	  {
	    conf_end (af, 0);
	    goto fail;
	  }

      /* The ID the other side should use in Phase 1. */
      if (dstid && conf_set (af, peer, "Remote-ID", dstid, 0, 0))
	{
	  conf_end (af, 0);
	  goto fail;
	}
    }
  else
    pf_key_v2_conf_refinc (af, peer);

  /* All done. */
  conf_end (af, 1);

  /* Let's rock 'n roll. */
  pf_key_v2_connection_check (conn);
  conn = 0;

  /* Fall-through to cleanup. */
 fail:
  if (ret)
    pf_key_v2_msg_free (ret);
  if (askpolicy)
    pf_key_v2_msg_free (askpolicy);
  if (srcid)
    free (srcid);
  if (dstid)
    free (dstid);
  if (peer)
    free (peer);
  if (conn)
    free (conn);
  return;
#endif
}

static void
pf_key_v2_notify (struct pf_key_v2_msg *msg)
{
  switch (((struct sadb_msg *)TAILQ_FIRST (msg)->seg)->sadb_msg_type)
    {
    case SADB_EXPIRE:
      pf_key_v2_expire (msg);
      break;

    case SADB_ACQUIRE:
      pf_key_v2_acquire (msg);
      break;

    default:
      log_print ("pf_key_v2_notify: unexpected message type (%d)",
		 ((struct sadb_msg *)TAILQ_FIRST (msg)->seg)->sadb_msg_type);
    }
  pf_key_v2_msg_free (msg);
}

void
pf_key_v2_handler (int fd)
{
  struct pf_key_v2_msg *msg;
  int n;

  /*
   * As synchronous read/writes to the socket can have taken place between
   * the select(2) call of the main loop and this handler, we need to recheck
   * the readability.
   */
  if (ioctl (pf_key_v2_socket, FIONREAD, &n) == -1)
    {
      log_error ("pf_key_v2_handler: ioctl (%d, FIONREAD, &n) failed",
		 pf_key_v2_socket);
      return;
    }
  if (!n)
    return;

  msg = pf_key_v2_read (0);
  if (msg)
    pf_key_v2_notify (msg);
}

/*
 * Group 2 IPsec SAs given by the PROTO1 and PROTO2 protocols of the SA IKE
 * security association in a chain.
 * XXX Assumes OpenBSD GRPSPIS extension.  Should probably be moved to sysdep.c
 */
int
pf_key_v2_group_spis (struct sa *sa, struct proto *proto1,
		      struct proto *proto2, int incoming)
{
#ifdef SADB_X_GRPSPIS
  struct sadb_msg msg;
  struct sadb_sa sa1, sa2;
  struct sadb_address *addr = 0;
  struct sadb_protocol protocol;
  struct pf_key_v2_msg *grpspis = 0, *ret = 0;
  struct sockaddr *saddr;
  int err;
  size_t len;
#ifdef KAME
  struct sadb_x_sa2 kamesa2;
#endif

  msg.sadb_msg_type = SADB_X_GRPSPIS;
  switch (proto1->proto)
    {
    case IPSEC_PROTO_IPSEC_ESP:
      msg.sadb_msg_satype = SADB_SATYPE_ESP;
      break;
    case IPSEC_PROTO_IPSEC_AH:
      msg.sadb_msg_satype = SADB_SATYPE_AH;
      break;
#ifdef SADB_X_SATYPE_IPCOMP
    case IPSEC_PROTO_IPCOMP:
      msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
      break;
#endif
    default:
      log_print ("pf_key_v2_group_spis: invalid proto %d", proto1->proto);
      goto cleanup;
    }
  msg.sadb_msg_seq = 0;
  grpspis = pf_key_v2_msg_new (&msg, 0);
  if (!grpspis)
    goto cleanup;

  /* Setup the SA extensions.  */
  sa1.sadb_sa_exttype = SADB_EXT_SA;
  sa1.sadb_sa_len = sizeof sa1 / PF_KEY_V2_CHUNK;
  memcpy (&sa1.sadb_sa_spi, proto1->spi[incoming], sizeof sa1.sadb_sa_spi);
  sa1.sadb_sa_replay = 0;
  sa1.sadb_sa_state = 0;
  sa1.sadb_sa_auth = 0;
  sa1.sadb_sa_encrypt = 0;
  sa1.sadb_sa_flags = 0;
  if (pf_key_v2_msg_add (grpspis, (struct sadb_ext *)&sa1, 0) == -1)
    goto cleanup;

#ifndef KAME
  sa2.sadb_sa_exttype = SADB_X_EXT_SA2;
  sa2.sadb_sa_len = sizeof sa2 / PF_KEY_V2_CHUNK;
  memcpy (&sa2.sadb_sa_spi, proto2->spi[incoming], sizeof sa2.sadb_sa_spi);
  sa2.sadb_sa_replay = 0;
  sa2.sadb_sa_state = 0;
  sa2.sadb_sa_auth = 0;
  sa2.sadb_sa_encrypt = 0;
  sa2.sadb_sa_flags = 0;
  if (pf_key_v2_msg_add (grpspis, (struct sadb_ext *)&sa2, 0) == -1)
    goto cleanup;
#else
  memset (&kamesa2, 0, sizeof kamesa2);
  kamesa2.sadb_x_sa2_exttype = SADB_X_EXT_SA2;
  kamesa2.sadb_x_sa2_len = sizeof kamesa2 / PF_KEY_V2_CHUNK;
  kamesa2.sadb_x_sa2_mode = 0;
  if (pf_key_v2_msg_add (grpspis, (struct sadb_ext *)&kamesa2, 0) == -1)
    goto cleanup;
#endif

  /*
   * Setup the ADDRESS extensions.
   */
  if (incoming)
    sa->transport->vtbl->get_src (sa->transport, &saddr);
  else
    sa->transport->vtbl->get_dst (sa->transport, &saddr);
  len = sizeof *addr + PF_KEY_V2_ROUND (saddr->sa_len);
  addr = calloc (1, len);
  if (!addr)
    goto cleanup;
  addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
  addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
#ifndef __OpenBSD__
  addr->sadb_address_proto = 0;
  addr->sadb_address_prefixlen = 0;
#endif
  addr->sadb_address_reserved = 0;
  memcpy (addr + 1, saddr, saddr->sa_len);
  ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
  if (pf_key_v2_msg_add (grpspis, (struct sadb_ext *)addr,
			 PF_KEY_V2_NODE_MALLOCED) == -1)
    goto cleanup;
  addr = 0;

  addr = calloc (1, len);
  if (!addr)
    goto cleanup;
  addr->sadb_address_exttype = SADB_X_EXT_DST2;
  addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
#ifndef __OpenBSD__
  addr->sadb_address_proto = 0;
  addr->sadb_address_prefixlen = 0;
#endif
  addr->sadb_address_reserved = 0;
  memcpy (addr + 1, saddr, saddr->sa_len);
  ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
  if (pf_key_v2_msg_add (grpspis, (struct sadb_ext *)addr,
			 PF_KEY_V2_NODE_MALLOCED) == -1)
    goto cleanup;
  addr = 0;

  /* Setup the PROTOCOL extension.  */
  protocol.sadb_protocol_exttype = SADB_X_EXT_PROTOCOL;
  protocol.sadb_protocol_len = sizeof protocol / PF_KEY_V2_CHUNK;
  switch (proto2->proto)
    {
    case IPSEC_PROTO_IPSEC_ESP:
      protocol.sadb_protocol_proto = SADB_SATYPE_ESP;
      break;
    case IPSEC_PROTO_IPSEC_AH:
      protocol.sadb_protocol_proto = SADB_SATYPE_AH;
      break;
#ifdef SADB_X_SATYPE_IPCOMP
    case IPSEC_PROTO_IPCOMP:
      protocol.sadb_protocol_proto = SADB_X_SATYPE_IPCOMP;
      break;
#endif
    default:
      log_print ("pf_key_v2_group_spis: invalid proto %d", proto2->proto);
      goto cleanup;
    }
  protocol.sadb_protocol_reserved2 = 0;
  if (pf_key_v2_msg_add (grpspis, (struct sadb_ext *)&protocol, 0) == -1)
    goto cleanup;

  ret = pf_key_v2_call (grpspis);
  pf_key_v2_msg_free (grpspis);
  grpspis = 0;
  if (!ret)
    goto cleanup;
  err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
  if (err)
    {
      log_print ("pf_key_v2_group_spis: GRPSPIS: %s", strerror (err));
      goto cleanup;
    }
  pf_key_v2_msg_free (ret);

  LOG_DBG ((LOG_SYSDEP, 50, "pf_key_v2_group_spis: done"));

  return 0;

 cleanup:
  if (addr)
     free (addr);
  if (grpspis)
    pf_key_v2_msg_free (grpspis);
  if (ret)
    pf_key_v2_msg_free (ret);
  return -1;

#else
  log_print ("pf_key_v2_group_spis: not supported in pure PF_KEYv2");
  return -1;
#endif
}