File: connections.c

package info (click to toggle)
libreswan 5.2-2.3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 81,644 kB
  • sloc: ansic: 129,988; sh: 32,018; xml: 20,646; python: 10,303; makefile: 3,022; javascript: 1,506; sed: 574; yacc: 511; perl: 264; awk: 52
file content (5456 lines) | stat: -rw-r--r-- 158,004 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
/* information about connections between hosts and clients
 *
 * Copyright (C) 1998-2002,2010,2013,2018 D. Hugh Redelmeier <hugh@mimosa.com>
 * Copyright (C) 2003-2008 Michael Richardson <mcr@xelerance.com>
 * Copyright (C) 2003-2011 Paul Wouters <paul@xelerance.com>
 * Copyright (C) 2008-2009 David McCullough <david_mccullough@securecomputing.com>
 * Copyright (C) 2009-2011 Avesh Agarwal <avagarwa@redhat.com>
 * Copyright (C) 2010 Bart Trojanowski <bart@jukie.net>
 * Copyright (C) 2010 Shinichi Furuso <Shinichi.Furuso@jp.sony.com>
 * Copyright (C) 2010,2013 Tuomo Soini <tis@foobar.fi>
 * Copyright (C) 2012-2017 Paul Wouters <paul@libreswan.org>
 * Copyright (C) 2012 Philippe Vouters <Philippe.Vouters@laposte.net>
 * Copyright (C) 2012 Bram <bram-bcrafjna-erqzvar@spam.wizbit.be>
 * Copyright (C) 2013 Kim B. Heino <b@bbbs.net>
 * Copyright (C) 2013,2017 Antony Antony <antony@phenome.org>
 * Copyright (C) 2013,2018 Matt Rogers <mrogers@redhat.com>
 * Copyright (C) 2013 Florian Weimer <fweimer@redhat.com>
 * Copyright (C) 2015-2020 Paul Wouters <pwouters@redhat.com>
 * Copyright (C) 2016-2020 Andrew Cagney <cagney@gnu.org>
 * Copyright (C) 2017 Mayank Totale <mtotale@gmail.com>
 * Copyright (C) 20212-2022 Paul Wouters <paul.wouters@aiven.io>
 * Copyright (C) 2020 Nupur Agrawal <nupur202000@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.  See <https://www.gnu.org/licenses/gpl2.txt>.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 */

#include <string.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <resolv.h>
#include <errno.h>
#include <limits.h>

#include "sysdep.h"
#include "constants.h"
#include "lswalloc.h"
#include "lswconf.h"
#include "id.h"
#include "x509.h"
#include "certs.h"
#include "secrets.h"
#include "lswnss.h"
#include "authby.h"

#include "kernel_info.h"
#include "defs.h"
#include "connections.h" /* needs id.h */
#include "connection_db.h"
#include "spd_db.h"
#include "pending.h"
#include "foodgroups.h"
#include "demux.h" /* needs packet.h */
#include "state.h"
#include "timer.h"
#include "ipsec_doi.h" /* needs demux.h and state.h */
#include "server.h"
#include "kernel.h" /* needs connections.h */
#include "log.h"
#include "keys.h"
#include "whack.h"
#include "ike_alg.h"
#include "kernel_alg.h"
#include "plutoalg.h"
#include "ikev1_xauth.h"
#include "addresspool.h"
#include "nat_traversal.h"
#include "pluto_x509.h"
#include "nss_cert_verify.h" /* for cert_VerifySubjectAltName() */
#include "nss_cert_load.h"
#include "ikev2.h"
#include "virtual_ip.h"	/* needs connections.h */
#include "fips_mode.h"
#include "crypto.h"
#include "kernel_xfrm.h"
#include "ip_address.h"
#include "ip_info.h"
#include "keyhi.h" /* for SECKEY_DestroyPublicKey */
#include "state_db.h"		/* for state_db_rehash_connection_serialno */
#include "ipsec_interface.h"
#include "iface.h"
#include "ip_selector.h"
#include "labeled_ipsec.h"		/* for vet_seclabel() */
#include "orient.h"
#include "ikev2_proposals.h"
#include "lswnss.h"
#include "show.h"
#include "routing.h"
#include "timescale.h"
#include "connection_event.h"
#include "ike_alg_dh.h"		/* for ike_alg_dh_none; */
#include "sparse_names.h"
#include "ikev2_ike_session_resume.h"	/* for pfree_session() */

static void discard_connection(struct connection **cp, bool connection_valid, where_t where);

void vdbg_connection(const struct connection *c,
		     struct verbose verbose, where_t where,
		     const char *message, ...)
{
	if (LDBGP(DBG_BASE, c->logger)) {
		return;
	}
	verbose.rc_flags = DEBUG_STREAM;
	/* MESSAGE ... */
	LLOG_JAMBUF(verbose.rc_flags, verbose.logger, buf) {
		jam(buf, PRI_VERBOSE, pri_verbose);
		va_list ap;
		va_start(ap, message);
		jam_va_list(buf, message, ap);
		va_end(ap);
		jam_string(buf, " ");
		jam_where(buf, where);
	}
	verbose.level++;
	/* connection ... */
	LLOG_JAMBUF(verbose.rc_flags, verbose.logger, buf) {
		jam(buf, PRI_VERBOSE, pri_verbose);
		jam_string(buf, "connection ");
		jam_connection_co(buf, c);
		if (c->clonedfrom != 0) {
			jam_string(buf, " clonedfrom ");
			jam_connection_co(buf, c->clonedfrom);
		}
		jam_string(buf, ": ");
		jam_connection(buf, c);
	}
	verbose.level++;
	/* host local->remote */
	LLOG_JAMBUF(verbose.rc_flags, verbose.logger, buf) {
		jam(buf, PRI_VERBOSE, pri_verbose);
		jam_string(buf, "host: ");
		jam_address(buf, &c->local->host.addr);
		jam_string(buf, "->");
		jam_address(buf, &c->remote->host.addr);
	}
	/* host id */
	LLOG_JAMBUF(verbose.rc_flags, verbose.logger, buf) {
		jam(buf, PRI_VERBOSE, pri_verbose);
		jam_string(buf, "id: ");
		jam_id(buf, &c->local->host.id);
		jam_string(buf, " -> ");
		jam_id(buf, &c->remote->host.id);
	}
	/* routing+kind ... */
	LLOG_JAMBUF(verbose.rc_flags, verbose.logger, buf) {
		jam(buf, PRI_VERBOSE, pri_verbose);
		jam_string(buf, "routing+kind: ");
		jam_enum_short(buf, &routing_names, c->routing.state);
		jam_string(buf, " ");
		jam_enum_short(buf, &connection_kind_names, c->local->kind);
	}
	/* selectors local->remote */
	LLOG_JAMBUF(verbose.rc_flags, verbose.logger, buf) {
		jam(buf, PRI_VERBOSE, pri_verbose);
		jam_string(buf, "selectors:");
		FOR_EACH_THING(end, &c->local->child, &c->remote->child) {
			FOR_EACH_ITEM(selector, &end->selectors.proposed) {
				jam_string(buf, " ");
				jam_selector(buf, selector);
			}
			jam_string(buf, " ->");
		}
		jam_string(buf, "; lease:");
		FOR_EACH_THING(end, &c->local->child, &c->remote->child) {
			FOR_EACH_ELEMENT(lease, end->lease) {
				if (lease->is_set) {
					jam_string(buf, " ");
					jam_address(buf, lease);
				}
			}
			jam_string(buf, " ->");
		}
	}
	/* SPDs local->remote */
	LLOG_JAMBUF(verbose.rc_flags, verbose.logger, buf) {
		jam(buf, PRI_VERBOSE, pri_verbose);
		jam_string(buf, "spds:");
		FOR_EACH_ITEM(spd, &c->child.spds) {
			jam_string(buf, " ");
			jam_selector_pair(buf, &spd->local->client, &spd->remote->client);
		}
	}
	/* policy */
	LLOG_JAMBUF(verbose.rc_flags, verbose.logger, buf) {
		jam(buf, PRI_VERBOSE, pri_verbose);
		jam_string(buf, "policy: ");
		jam_connection_policies(buf, c);
	}
	/* sec-label */
	if (c->config->sec_label.len > 0) {
		LLOG_JAMBUF(verbose.rc_flags, verbose.logger, buf) {
			jam(buf, PRI_VERBOSE, pri_verbose);
			jam_string(buf, "sec_label: ");
			if (c->child.sec_label.len > 0) {
				jam(buf, PRI_SHUNK, pri_shunk(c->child.sec_label));
				jam_string(buf, " <= ");
			}
			jam(buf, PRI_SHUNK, pri_shunk(c->config->sec_label));
		}
	}
}

static bool never_negotiate_wm(const struct whack_message *wm)
{
	/* with no never-negotiate shunt, things must negotiate */
	return (wm->never_negotiate_shunt != SHUNT_UNSET);
}

static bool is_opportunistic_wm_end(const struct whack_end *end)
{
	return (end->host_type == KH_OPPO ||
		end->host_type == KH_OPPOGROUP);
}

static bool is_opportunistic_wm(const struct whack_message *wm)
{
	return (is_opportunistic_wm_end(&wm->end[LEFT_END]) ||
		is_opportunistic_wm_end(&wm->end[RIGHT_END]));
}

static bool is_group_wm_end(const struct whack_end *end)
{
	return (end->host_type == KH_GROUP ||
		end->host_type == KH_OPPOGROUP);
}

static bool is_group_wm(const struct whack_message *wm)
{
	return (is_group_wm_end(&wm->end[LEFT_END]) ||
		is_group_wm_end(&wm->end[RIGHT_END]));
}

/*
 * Is there an existing connection with NAME?
 */

bool connection_with_name_exists(const char *name)
{
	struct connection_filter cq = {
		.name = name,
		.search = {
			.order = NEW2OLD,
			.verbose.logger = &global_logger,
			.where = HERE,
		},
	};
	while (next_connection(&cq)) {
		return true;
	}
	return false;
}

/* Delete a connection */
static void discard_spd_end_content(struct spd_end *e)
{
	virtual_ip_delref(&e->virt);
}

static void discard_spd_content(struct spd *spd)
{
	spd_db_del(spd);
	FOR_EACH_THING(end, LEFT_END, RIGHT_END) {
		discard_spd_end_content(&spd->end[end]);
	}
}

void discard_connection_spds(struct connection *c)
{
	FOR_EACH_ITEM(spd, &c->child.spds) {
		discard_spd_content(spd);
	}
	pfree_list(&c->child.spds);
	c->spd = NULL;
	c->child.spds = (struct spds) {0};
}


/*
 * delete_connection -- removes a connection by pointer
 *
 * @c - the connection pointer
 * @relations - whether to delete any instances as well.
 * @connection_valid - apply sanity checks
 *
 * Compat hack for code that thinks it knows the connection is
 * finished with - it passerts() that it is delref()ing the last
 * reference.
 */

static void llog_delete_connection_when_instance(const struct connection *c)
{
	if (is_labeled_parent(c)) {
		/* XXX: pointless log? */
		address_buf b;
		llog(RC_LOG, c->logger,
		     "deleting labeled parent connection with peer %s sec_label:"PRI_SHUNK,
		     str_address_sensitive(&c->remote->host.addr, &b),
		     pri_shunk(c->config->sec_label));
	} else if (is_labeled_child(c)) {
		/* XXX: pointless log? */
		address_buf b;
		llog(RC_LOG, c->logger,
		     "deleting labeled child connection with peer %s sec_label:"PRI_SHUNK,
		     str_address_sensitive(&c->remote->host.addr, &b),
		     pri_shunk(c->child.sec_label));
	} else if (is_instance(c)) {
		/* XXX: pointless check? */
		if (!is_opportunistic(c)) {
			/* XXX: pointless log? */
			address_buf b;
			llog(RC_LOG, c->logger,
			     "deleting connection instance with peer %s",
			     str_address_sensitive(&c->remote->host.addr, &b));
		}
	}
}

void delete_connection_where(struct connection **cp, where_t where)
{
	struct connection *c = *cp;
	llog_delete_connection_when_instance(c);
	delref_where(cp, c->logger, where); /* should leave 0 references */
	discard_connection(&c, true/*connection_valid*/, where);
}

struct connection *connection_addref_where(struct connection *c, const struct logger *owner, where_t where)
{
	return laddref_where(c, owner, where);
}

void connection_delref_where(struct connection **cp, const struct logger *owner, where_t where)
{
	struct connection *c = ldelref_where(cp, owner, where);
	if (c == NULL) {
		return;
	}
	llog_delete_connection_when_instance(c);
	discard_connection(&c, true/*connection_valid*/, where);
}

static bool connection_ok_to_delete(struct connection *c, where_t where)
{
	bool ok_to_delete = true;
	struct logger *logger = c->logger;

	unsigned refcnt = refcnt_peek(c, logger);
	if (refcnt != 0) {
		llog_pexpect(logger, where,
			     "connection "PRI_CO" [%p] still has %u references",
			     pri_connection_co(c), c, refcnt);
		ok_to_delete = false;
	}

	/*
	 * Must not be pending (i.e., not on a queue waiting for an
	 * IKE SA to establish).
	 */
	if (connection_is_pending(c)) {
		llog_pexpect(logger, where,
			     "connection "PRI_CO" [%p] is still pending",
			     pri_connection_co(c), c);
		ok_to_delete = false;
	}

	/*
	 * Must have all routing and all owners cleared.
	 */
	if (!pexpect_connection_is_unrouted(c, logger, where)) {
		ok_to_delete = false;
	}
	if (!pexpect_connection_is_disowned(c, logger, where)) {
		ok_to_delete = false;
	}

	/*
	 * Must not have instances (i.e., all instantiations are gone).
	 */
	struct connection_filter instance = {
		.clonedfrom = c,
		.ike_version = c->config->ike_version,
		.search = {
			.order = OLD2NEW,
			.verbose.logger = logger,
			.where = HERE,
		},
	};
	while (next_connection(&instance)) {
		connection_buf cb;
		llog_pexpect(logger, where,
			     "connection "PRI_CO" [%p] still instantiated as "PRI_CONNECTION" [%p]",
			     pri_connection_co(c), c,
			     pri_connection(instance.c, &cb),
			     instance.c);
		connection_ok_to_delete(instance.c, where);
		ok_to_delete = false;
	}

	/*
	 * Must not have states (i.e., no states are referring to this
	 * connection).
	 */
	struct state_filter state = {
		.connection_serialno = c->serialno,
		.search = {
			.order = NEW2OLD,
			.verbose.logger = &global_logger,
			.where = HERE,
		},
	};
	while (next_state(&state)) {
		state_buf sb;
		llog_pexpect(logger, where,
			     "connection "PRI_CO" [%p] is still being used by %s "PRI_STATE,
			     pri_connection_co(c), c,
			     state_sa_name(state.st),
			     pri_state(state.st, &sb));
		ok_to_delete = false;
	}

	/*
	 * There can't be any outstanding events.
	 */
	if (connection_event_is_scheduled(c, CONNECTION_REVIVAL)) {
		llog_pexpect(logger, where,
			     "connection "PRI_CO" [%p] has REVVIAL pending",
			     pri_connection_co(c), c);
		ok_to_delete = false;
	}

	return ok_to_delete;
}

static void discard_connection(struct connection **cp, bool connection_valid, where_t where)
{
	struct connection *c = *cp;
	*cp = NULL;

	/*
	 * Preserve the original logger's text.  Things like
	 * delref(.clonedfrom) affect the prefix.
	 */
	struct logger *logger = clone_logger(c->logger, where);  /* must free */

	/*
	 * XXX: don't use "@%p".  The refcnt tracker will see it and
	 * report a use-after-free (since refcnt loggs the pointer as
	 * free before calling this code).
	 */
	ldbg(logger, "%s() %s "PRI_CO" [%p] cloned from "PRI_CO,
	     __func__, c->name,
	     pri_connection_co(c), c,
	     pri_connection_co(c->clonedfrom));

	if (!connection_ok_to_delete(c, where)) {
		llog_passert(logger, where,
			     "connection "PRI_CO" [%p] still in use",
			     pri_connection_co(c), c);
	}

	/*
	 * Finally start cleanup.
	 */

	FOR_EACH_ELEMENT(afi, ip_families) {
		if (c->pool[afi->ip_index] != NULL) {
			free_that_address_lease(c, afi, c->logger);
			addresspool_delref(&c->pool[afi->ip_index], c->logger);
		}
	}

	/* find and delete c from the host pair list */
#if 0
	PEXPECT(c->logger, !oriented(c));
#endif
	disorient(c);

	/*
	 * Disorienting should have released .ipsec_interface, and
	 * unrouting should have released the
	 * .ipsec_interface_address.
	 */
	PEXPECT(c->logger, c->ipsec_interface == NULL);
	PEXPECT(c->logger, c->ipsec_interface_address == NULL);

	remove_from_group(c);

	if (connection_valid) {
		connection_db_del(c);
	}
	discard_connection_spds(c);

	/*
	 * Freeing .clonedfrom breaks the logger's message.
	 */

	free_logger(&c->logger, where);

	FOR_EACH_ELEMENT(end, c->end) {
		free_id_content(&end->host.id);
		pfree_list(&end->child.selectors.accepted);
	}

	connection_delref(&c->clonedfrom, logger);

	iface_endpoint_delref(&c->revival.local);

	free_chunk_content(&c->child.sec_label);

	pfree_session(&c->session);

	/*
	 * Only free config when the root connection.  Non-root
	 * connections have .root_config==NULL.
	 */
	struct config *config = c->root_config;
	if (config != NULL) {
		passert(c->clonedfrom == NULL); /*i.e., root */
		pfreeany(config->vti.interface);
		free_chunk_content(&config->sec_label);
		free_proposals(&config->ike_proposals.p);
		free_proposals(&config->child_sa.proposals.p);
		free_ikev2_proposals(&config->v2_ike_proposals);
		free_ikev2_proposals(&config->child_sa.v2_ike_auth_proposals);
		pfreeany(config->connalias);
		pfreeany(config->dnshostname);
		pfree_list(&config->modecfg.dns);
		pfreeany(config->modecfg.domains);
		pfreeany(config->modecfg.banner);
		pfreeany(config->ppk_ids);
		if (config->ppk_ids_shunks != NULL) {
			pfree(config->ppk_ids_shunks);
		}
		pfreeany(config->redirect.to);
		pfreeany(config->redirect.accept_to);
		FOR_EACH_ELEMENT(end, config->end) {
			if (end->host.cert.nss_cert != NULL) {
				CERT_DestroyCertificate(end->host.cert.nss_cert);
			}
			/* ike/host */
			free_chunk_content(&end->host.ca);
			pfreeany(end->host.ckaid);
			pfreeany(end->host.xauth.username);
			pfreeany(end->host.addr_name);
			free_id_content(&end->host.id);
			/* child */
			pfreeany(end->child.updown);
			pfree_list(&end->child.selectors);
			pfree_list(&end->child.sourceip);
			virtual_ip_delref(&end->child.virt);
			pfree_list(&end->child.addresspools);
			FOR_EACH_ELEMENT(pool, end->child.addresspool) {
				addresspool_delref(pool, logger);
			}
		}
		pfree(c->root_config);
	}

	/* connection's final gasp; need's c->name */
	pfreeany(c->name);
	pfreeany(c->prefix);
	free_logger(&logger, where);
	pfree(c);
}

ip_port end_host_port(const struct host_end *this, const struct host_end *that)
{
	unsigned port;
	if (this->config->ikeport != 0) {
		/*
		 * The END's IKEPORT was specified in the config file.
		 * Use that.
		 */
		port = this->config->ikeport;
	} else if (that->config->ikeport != 0) {
		/*
		 * The other end's IKEPORT was specified in the config
		 * file.  Since specifying an IKEPORT implies ESP
		 * encapsulation (i.e. IKE packets must include the
		 * ESP=0 prefix), send packets from the encapsulating
		 * NAT_IKE_UDP_PORT.
		 */
		port = NAT_IKE_UDP_PORT;
	} else if (that->encap) {
		/*
		 * See above.  Presumably an instance which previously
		 * had a natted port and is being revived.
		 */
		port = NAT_IKE_UDP_PORT;
	} else if (this->config->iketcp == IKE_TCP_ONLY) {
		/*
		 * RFC 8229: Implementations MUST support TCP
		 * encapsulation on TCP port 4500, which is reserved
		 * for IPsec NAT traversal.
		*/
		port = NAT_IKE_UDP_PORT;
	} else {
		port = IKE_UDP_PORT;
	}
	return ip_hport(port);
}

ip_port local_host_port(const struct connection *c)
{
	return end_host_port(&c->local->host, &c->remote->host);
}

void update_hosts_from_end_host_addr(struct connection *c,
				     enum end end,
				     ip_address host_addr,
				     where_t where)
{
	struct host_end *host = &c->end[end].host;
	struct host_end *other_host = &c->end[!end].host;

	address_buf hab;
	ldbg(c->logger, "updating host ends from %s.host.addr %s",
	     host->config->leftright, str_address(&host_addr, &hab));

	/* could be %any but can't be an address */
	PASSERT_WHERE(c->logger, where, !address_is_specified(host->addr));

	/* can't be unset; but could be %any[46] */
	const struct ip_info *afi = address_info(host_addr);
	PASSERT_WHERE(c->logger, where, afi != NULL); /* since specified */

	host->addr = host_addr;
	host->first_addr = host_addr;

	/*
	 * Update the %any ID to HOST_ADDR, but only when it set to a
	 * proper address, i.e., is set and not %any aka 0.0.0 --
	 * WildCard.
	 */
	if (address_is_specified(host_addr) &&
	    host->id.kind == ID_NONE) {
		struct id id = {
			.kind = afi->id_ip_addr,
			.ip_addr = host->addr,
		};
		id_buf hid, cid, nid;
		dbg("  updated %s.id from %s (config=%s) to %s",
		    host->config->leftright,
		    str_id(&host->id, &hid),
		    str_id(&host->config->id, &cid),
		    str_id(&id, &nid));
		host->id = id;
	}

	/*
	 * If END has an IKEPORT (which means messages are ESP=0
	 * prefixed), then END must send from either IKEPORT or the
	 * NAT port (and also ESP=0 prefix messages).
	 */
	if (address_is_specified(host_addr)) {
		unsigned host_port = hport(end_host_port(host, other_host));
		dbg("  updated %s.host_port from %u to %u",
		    host->config->leftright,
		    host->port, host_port);
		host->port = host_port;
	}

	/*
	 * Set the other end's NEXTHOP.
	 *
	 * When not specified by the config, use this end's HOST_ADDR,
	 * as in:
	 *
	 *   other_host.ADDR -> other_host.NEXTHOP -> ADDR.
	 */
	other_host->nexthop = other_host->config->nexthop;
	if (address_is_specified(host_addr) &&
	    !address_is_specified(other_host->nexthop)) {
		other_host->nexthop = host_addr;
	}
	address_buf old, new;
	dbg("  updated %s.host_nexthop from %s to %s",
	    other_host->config->leftright,
	    str_address(&other_host->config->nexthop, &old),
	    str_address(&other_host->nexthop, &new));
}

/*
 * Figure out the host / client address family.
 *
 * Returns diag() when there's a conflict.  leaves *AFI NULL if could
 * not be determined.
 */

#define EXTRACT_AFI(NAME, FIELD)					\
	{								\
		const struct ip_info *wfi = address_info(FIELD);	\
		if (*afi == NULL) {					\
			*afi = wfi;					\
			leftright = w->leftright;			\
			name = NAME;					\
			struct jambuf buf = ARRAY_AS_JAMBUF(value);	\
			jam_address(&buf, &FIELD);			\
		} else if (wfi != NULL && wfi != *afi) {		\
			address_buf tb;					\
			return diag("host address family %s from %s%s=%s conflicts with %s%s=%s", \
				    (*afi)->ip_name, leftright, name, value, \
				    w->leftright, NAME, str_address(&FIELD, &tb)); \
		}							\
	}

static diag_t extract_host_afi(const struct whack_message *wm,
			       const struct ip_info **afi)
{
	*afi = NULL;
	const char *leftright;
	const char *name;
	char value[sizeof(selector_buf)];
	FOR_EACH_THING(w, &wm->end[LEFT_END], &wm->end[RIGHT_END]) {
		EXTRACT_AFI(""/*left""=,right""=*/, w->host_addr);
		EXTRACT_AFI("nexthop", w->nexthop);
	}
	return NULL;
}

/* assume 0 is unset */

static unsigned extract_sparse(const char *leftright, const char *name,
			       unsigned value, unsigned unset, unsigned never,
			       const struct sparse_names *names,
			       const struct whack_message *wm,
			       struct logger *logger)
{
	if (never_negotiate_wm(wm)) {
		if (value != 0) {
			sparse_buf sb;
			llog(RC_LOG, logger,
			     "warning: %s%s=%s ignored for never-negotiate connection",
			     leftright, name, str_sparse(names, value, &sb));
		}
		return never;
	} else if (value == 0) {
		return unset;
	} else {
		return value;
	}
}

static bool extract_yn(const char *leftright, const char *name,
		       enum yn_options value, bool unset,
		       const struct whack_message *wm, struct logger *logger)
{
	/* note that 0 gets mapped to YN_UNSET(0) and then UNSET */
	enum yn_options yn = extract_sparse(leftright, name, value,
					    /*unset*/YN_UNSET, /*never*/YN_NO,
					    &yn_option_names, wm, logger);
	switch (yn) {
	case YN_NO: return false;
	case YN_YES: return true;
	case YN_UNSET: return unset;
	}
	bad_sparse(logger, &yn_option_names, yn);
}

/*
 * YN option that is only used when P is enabled.  Whe P is disabled a
 * warning is issued but the value is saved regardless:
 *
 * This is to stop:
 *   iptfs=no; iptfs-fragmentation=no
 * showing as:
 *   iptfs: no; fragmentation: no;
 */

static bool extract_yn_p(const char *leftright, const char *name, enum yn_options yn,
			 bool unset, const struct whack_message *wm, struct logger *logger,
			 const char *p_leftright, const char *p_name, enum yn_options p)
{
	const struct sparse_names *names = &yn_option_names;

	if (yn == YN_UNSET) {
		return unset;
	}

	bool value = false;
	switch (yn) {
	case YN_NO: value = false; break;
	case YN_YES: value = true; break;
	default:
		bad_sparse(logger, &yn_option_names, yn);
	}

	/* complain? */
	if (never_negotiate_wm(wm)) {
		name_buf sb;
		llog(RC_LOG, logger,
		     "warning: %s%s=%s ignored for never-negotiate connection",
		     leftright, name, str_sparse(names, value, &sb));
	} else if (p == YN_UNSET) {
		name_buf sb;
		llog(RC_LOG, logger,
		     "warning: %s%s=%s ignored without %s%s=yes",
		     leftright, name, str_sparse(names, value, &sb),
		     p_leftright, p_name);
	} else if (p == YN_NO) {
		name_buf sb;
		llog(RC_LOG, logger,
		     "warning: %s%s=%s ignored when %s%s=no",
		     leftright, name, str_sparse(names, value, &sb),
		     p_leftright, p_name);
	}

	return value;
}

static enum yna_options extract_yna(const char *leftright, const char *name,
				    enum yna_options yna,
				    enum yna_options unset,
				    enum yna_options never,
				    const struct whack_message *wm,
				    struct logger *logger)
{
	return extract_sparse(leftright, name, yna,
			      unset, never,
			      &yna_option_names, wm, logger);
}

/* terrible name */

static bool can_extract_str(const char *leftright,
			    const char *name,
			    const char *value,
			    const struct whack_message *wm,
			    struct logger *logger)
{
	if (value == NULL) {
		return false;
	}

	if (never_negotiate_wm(wm)) {
		llog(RC_LOG, logger,
		     "warning: %s%s=%s ignored for never-negotiate connection",
		     leftright, name, value);
		return false;
	}

	return true;
}

static char *extract_str(const char *leftright, const char *name,
			 const char *str,
			 const struct whack_message *wm,
			 struct logger *logger)
{
	if (can_extract_str(leftright, name, str, wm, logger)) {
		return clone_str(str, name);
	}

	return NULL;
}

static diag_t extract_host_ckaid(struct host_end_config *host_config,
				 const struct whack_end *src,
				 bool *same_ca,
				 struct logger *logger/*connection "..."*/)
{
	const char *leftright = src->leftright;
	ckaid_t ckaid;
	err_t err = string_to_ckaid(src->ckaid, &ckaid);
	if (err != NULL) {
		return diag("%s-ckaid='%s' invalid: %s",
			    leftright, src->ckaid, err);
	}

	/*
	 * Always save the CKAID so that a delayed load of the private
	 * key can work.
	 */
	host_config->ckaid = clone_thing(ckaid, "end ckaid");

	/*
	 * See if there's a certificate matching the CKAID, if not
	 * assume things will later find the private key (or cert on a
	 * later attempt).
	 */
	CERTCertificate *cert = get_cert_by_ckaid_from_nss(&ckaid, logger);
	if (cert != NULL) {
		diag_t diag = add_end_cert_and_preload_private_key(cert, host_config,
								   *same_ca/*preserve_ca*/,
								   logger);
		if (diag != NULL) {
			CERT_DestroyCertificate(cert);
			return diag;
		}
		return NULL;
	}

	ldbg(logger, "%s-ckaid=%s did not match a certificate in the NSS database",
	     leftright, src->ckaid);

	/* try to pre-load the private key */
	bool load_needed;
	err = preload_private_key_by_ckaid(&ckaid, &load_needed, logger);
	if (err != NULL) {
		ckaid_buf ckb;
		ldbg(logger, "no private key matching %s-ckaid=%s: %s",
		     leftright, str_ckaid(host_config->ckaid, &ckb), err);
		return NULL;
	}

	ckaid_buf ckb;
	llog(LOG_STREAM/*not-whack-for-now*/, logger,
	     "loaded private key matching %s-ckaid=%s",
	     leftright,
	     str_ckaid(host_config->ckaid, &ckb));
	return NULL;
}


static diag_t extract_host_end(struct host_end *host,
			       struct host_end_config *host_config,
			       struct host_end_config *other_host_config,
			       const struct whack_message *wm,
			       const struct whack_end *src,
			       const struct whack_end *other_src,
			       bool *same_ca,
			       struct logger *logger/*connection "..."*/)
{
	err_t err;
	const char *leftright = host_config->leftright;

	/*
	 * Save the whack value, update_hosts_from_end_host_addr()
	 * will set the actual .nexthop value for the connection.
	 * Either now, during extraction, or later, during
	 * instantiation.
	 */
	host_config->nexthop = src->nexthop;

	/*
	 * Decode id, if any.
	 *
	 * For %fromcert, the load_end_cert*() call will update it.
	 *
	 * For unset, update_hosts_from_end_host_addr(), will fill it
	 * on from the HOST address (assuming it can be resolved).
	 *
	 * Else it remains unset and acts like a wildcard.
	 */
	pexpect(host_config->id.kind == ID_NONE);
	if (src->id != NULL) { /*can_extract_str()*/
		/*
		 * Treat any atoid() failure as fatal.  One wart is
		 * something like id=foo.  ttoaddress_dns() fails
		 * when, perhaps, the code should instead return FQDN?
		 *
		 * In 4.x the error was ignored and ID=<HOST_IP> was
		 * used.
		 */
		err_t e = atoid(src->id, &host_config->id);
		if (e != NULL) {
			return diag("%sid=%s invalid: %s",
				    leftright, src->id, e);
		}
	}

	/* decode CA distinguished name, if any */
	host_config->ca = empty_chunk;
	if (src->ca != NULL) {
		if (streq(src->ca, "%same")) {
			*same_ca = true;
		} else if (!streq(src->ca, "%any")) {
			err_t ugh;

			/* convert the CA into a DN blob */
			ugh = atodn(src->ca, &host_config->ca);
			if (ugh != NULL) {
				llog(RC_LOG, logger,
				     "bad %s CA string '%s': %s (ignored)",
				     leftright, src->ca, ugh);
			} else {
				/* now try converting it back; isn't failing this a bug? */
				ugh = parse_dn(ASN1(host_config->ca));
				if (ugh != NULL) {
					llog(RC_LOG, logger,
					     "error parsing %s CA converted to DN: %s",
					     leftright, ugh);
					DBG_dump_hunk(NULL, host_config->ca);
				}
			}

		}
	}

	/*
	 * Try to find the cert / private key.
	 *
	 * XXX: Be lazy and simply warn about combinations such as
	 * cert+ckaid.
	 *
	 * Should this instead cross check?
	 */
	if (src->cert != NULL) {
		if (src->ckaid != NULL) {
			llog(RC_LOG, logger,
				    "warning: ignoring %s ckaid '%s' and using %s certificate '%s'",
				    leftright, src->cert,
				    leftright, src->cert);
		}
		if (src->pubkey != NULL) {
			enum_buf pkb;
			llog(RC_LOG, logger,
			     "warning: ignoring %s %s '%s' and using %s certificate '%s'",
			     leftright,
			     str_enum(&ipseckey_algorithm_config_names, src->pubkey_alg, &pkb),
			     src->pubkey,
			     leftright, src->cert);
		}
		CERTCertificate *cert = get_cert_by_nickname_from_nss(src->cert, logger);
		if (cert == NULL) {
			return diag("%s certificate '%s' not found in the NSS database",
				    leftright, src->cert);
		}
		diag_t diag = add_end_cert_and_preload_private_key(cert, host_config,
								   *same_ca/*preserve_ca*/,
								   logger);
		if (diag != NULL) {
			CERT_DestroyCertificate(cert);
			return diag;
		}
	} else if (src->pubkey != NULL) {

		/*
		 * XXX: hack: whack will load the actual key in a
		 * second message, this code just extracts the ckaid.
		 */

		if (src->ckaid != NULL) {
			enum_buf pkb;
			llog(RC_LOG, logger,
			     "warning: ignoring %sckaid=%s and using %s%s",
			     leftright, src->ckaid,
			     leftright, str_enum(&ipseckey_algorithm_config_names, src->pubkey_alg, &pkb));
		}

		chunk_t keyspace = NULL_HUNK; /* must free */
		struct pubkey_content pkc;
		if (src->pubkey_alg == IPSECKEY_ALGORITHM_X_PUBKEY) {
			/* XXX: lifted from starter_whack_add_pubkey() */
			err = ttochunk(shunk1(src->pubkey), 64/*damit*/, &keyspace);
			if (err != NULL) {
				enum_buf pkb;
				return diag("%s%s invalid: %s",
					    leftright, str_enum(&ipseckey_algorithm_config_names, src->pubkey_alg, &pkb),
					    err);
			}
			diag_t d = pubkey_der_to_pubkey_content(HUNK_AS_SHUNK(keyspace), &pkc);
			if (d != NULL) {
				free_chunk_content(&keyspace);
				enum_buf pkb;
				return diag_diag(&d, "%s%s invalid, ",
						 leftright, str_enum(&ipseckey_algorithm_config_names, src->pubkey_alg, &pkb));
			}
		} else {
			/* XXX: lifted from starter_whack_add_pubkey() */
			err = ttochunk(shunk1(src->pubkey), 0/*figure-it-out*/, &keyspace);
			if (err != NULL) {
				enum_buf pkb;
				return diag("%s%s invalid: %s",
					    leftright, str_enum(&ipseckey_algorithm_config_names, src->pubkey_alg, &pkb),
					    err);
			}
			const struct pubkey_type *type;
			switch (src->pubkey_alg) {
			case IPSECKEY_ALGORITHM_RSA:
				type = &pubkey_type_rsa;
				break;
			case IPSECKEY_ALGORITHM_ECDSA:
				type = &pubkey_type_ecdsa;
				break;
			default:
				bad_case(src->pubkey_alg);
			}

			diag_t d = type->ipseckey_rdata_to_pubkey_content(HUNK_AS_SHUNK(keyspace), &pkc);
			if (d != NULL) {
				free_chunk_content(&keyspace);
				enum_buf pkb;
				return diag_diag(&d, "%s%s invalid, ",
						 leftright, str_enum(&ipseckey_algorithm_config_names, src->pubkey_alg, &pkb));
			}
		}

		passert(pkc.type != NULL);

		ckaid_buf ckb;
		enum_buf pkb;
		dbg("saving CKAID %s extracted from %s%s",
		    str_ckaid(&pkc.ckaid, &ckb),
		    leftright, str_enum(&ipseckey_algorithm_config_names, src->pubkey_alg, &pkb));
		host_config->ckaid = clone_const_thing(pkc.ckaid, "raw pubkey's ckaid");
		free_chunk_content(&keyspace);
		pkc.type->free_pubkey_content(&pkc);

		/* try to pre-load the private key */
		bool load_needed;
		err = preload_private_key_by_ckaid(host_config->ckaid, &load_needed, logger);
		if (err != NULL) {
			ckaid_buf ckb;
			dbg("no private key matching %s CKAID %s: %s",
			    leftright, str_ckaid(host_config->ckaid, &ckb), err);
		} else if (load_needed) {
			ckaid_buf ckb;
			enum_buf pkb;
			llog(LOG_STREAM/*not-whack-for-now*/, logger,
			     "loaded private key matching %s%s CKAID %s",
			     leftright, str_enum(&ipseckey_algorithm_config_names, src->pubkey_alg, &pkb),
			     str_ckaid(host_config->ckaid, &ckb));
		}

	} else if (src->ckaid != NULL) {
		diag_t d = extract_host_ckaid(host_config, src, same_ca, logger);
		if (d != NULL) {
			return d;
		}
	}

	if (host_config->id.kind == ID_FROMCERT &&
	    host_config->cert.nss_cert != NULL) {
		host->id = id_from_cert(&host_config->cert);
		id_buf idb;
		ldbg(logger, "setting %s-id to '%s' as host->config->id=%%fromcert",
		     leftright, str_id(&host->id, &idb));
	} else {
		id_buf idb;
		ldbg(logger, "setting %s-id to '%s' as host->config->id)",
		     leftright, str_id(&host_config->id, &idb));
		host->id = clone_id(&host_config->id, __func__);
	}

	/* the rest is simple copying of corresponding fields */
	host_config->type = src->host_type;
	host_config->addr_name = clone_str(src->host_addr_name, "host ip");
	host_config->xauth.server = src->xauth_server;
	host_config->xauth.client = src->xauth_client;
	host_config->xauth.username = clone_str(src->xauth_username, "xauth username");
	host_config->eap = src->eap;

	if (src->eap == IKE_EAP_NONE && src->auth == AUTH_EAPONLY) {
		return diag("leftauth/rightauth can only be 'eaponly' when using leftautheap/rightautheap is not 'none'");
	}

	/*
	 * Determine the authentication from auth= and authby=.
	 */

	if (never_negotiate_wm(wm) && src->auth != AUTH_UNSET && src->auth != AUTH_NEVER) {
		/* AUTH_UNSET is updated below */
		enum_buf ab;
		return diag("%sauth=%s option is invalid for type=passthrough connection",
			    leftright, str_enum_short(&keyword_auth_names, src->auth, &ab));
	}

	/*
	 * Note: this checks the whack message (WM), and not the
	 * connection (C) being construct - it could be done before
	 * extract_end(), but do it here.
	 *
	 * XXX: why not allow this?
	 */
	if ((src->auth == AUTH_UNSET) != (other_src->auth == AUTH_UNSET)) {
		return diag("leftauth= and rightauth= must both be set or both be unset");
	}

	/* value starting points */
	struct authby authby = (never_negotiate_wm(wm) ? AUTHBY_NEVER :
				!authby_is_set(wm->authby) ? AUTHBY_DEFAULTS :
				wm->authby);
	enum keyword_auth auth = src->auth;

	/*
	 * IKEv1 determines AUTH from authby= (it ignores auth= and
	 * bonus bits in authby=foo,bar).
	 *
	 * This logic still applies when NEVER_NEGOTIATE() - it turns
	 * above AUTHBY_NEVER into AUTH_NEVER.
	 */
	if (wm->ike_version == IKEv1) {
		/* override auth= using above authby= */
		if (auth != AUTH_UNSET) {
			return diag("%sauth= is not supported by IKEv1", leftright);
		}
		auth = auth_from_authby(authby);
		/* Force authby= to be consistent with selected AUTH */
		authby = authby_from_auth(auth);
		authby.ecdsa = false;
		authby.rsasig_v1_5 = false;
		if (!authby_is_set(authby)) {
			/* just striped ECDSA say */
			authby_buf ab;
			return diag("authby=%s is invalid for IKEv1",
				    str_authby(wm->authby, &ab));
		}
		/* ignore bonus wm->authby (not authby) bits */
		struct authby exclude = authby_not(authby);
		struct authby supplied = wm->authby;
		supplied.rsasig_v1_5 = false;
		supplied.ecdsa = false;
		struct authby unexpected = authby_and(supplied, exclude);
		if (authby_is_set(unexpected)) {
			authby_buf wb, ub;
			return diag("additional %s in authby=%s is not supported by IKEv1",
				    str_authby(unexpected, &ub),
				    str_authby(supplied, &wb));
		}
	}

	struct authby authby_mask = {0};
	switch (auth) {
	case AUTH_RSASIG:
		authby_mask = AUTHBY_RSASIG;
		break;
	case AUTH_ECDSA:
		authby_mask = AUTHBY_ECDSA;
		break;
	case AUTH_PSK:
		/* force only bit (not on by default) */
		authby = (struct authby) { .psk = true, };
		break;
	case AUTH_NULL:
		/* force only bit (not on by default) */
		authby = (struct authby) { .null = true, };
		break;
	case AUTH_UNSET:
		auth = auth_from_authby(authby);
		break;
	case AUTH_EAPONLY:
		break;
	case AUTH_NEVER:
		break;
	}

	if (authby_is_set(authby_mask)) {
		authby = authby_and(authby, authby_mask);
		if (!authby_is_set(authby)) {
			enum_buf ab;
			authby_buf pb;
			return diag("%sauth=%s expects authby=%s",
				    leftright,
				    str_enum_short(&keyword_auth_names, auth, &ab),
				    str_authby(authby_mask, &pb));
		}
	}

	enum_buf eab;
	authby_buf wabb;
	authby_buf eabb;
	dbg("fake %sauth=%s %sauthby=%s from whack authby %s",
	    src->leftright, str_enum_short(&keyword_auth_names, auth, &eab),
	    src->leftright, str_authby(authby, &eabb),
	    str_authby(wm->authby, &wabb));
	host_config->auth = auth;
	host_config->authby = authby;

	if (src->id != NULL && streq(src->id, "%fromcert")) {
		if (auth == AUTH_PSK || auth == AUTH_NULL) {
			return diag("ID cannot be specified as %%fromcert if PSK or AUTH-NULL is used");
		}
	}

	if (src->groundhog != NULL) {
		err_t e = ttobool(src->groundhog, &host_config->groundhog);
		if (e != NULL) {
			return diag("%sgroundhog=%s, %s", leftright, src->groundhog, e);
		}
		if (host_config->groundhog && is_fips_mode()) {
			return diag("%sgroundhog=%s is invalid in FIPS mode",
				    leftright, src->groundhog);
		}
		groundhogday |= host_config->groundhog;
		llog(RC_LOG, logger,
		     "WARNING: %s is a groundhog", leftright);
	}
	host_config->key_from_DNS_on_demand = src->key_from_DNS_on_demand;
	host_config->sendcert = src->sendcert == 0 ? CERT_SENDIFASKED : src->sendcert;
	host_config->ikeport = src->host_ikeport;
	if (src->host_ikeport > 65535) {
		llog(RC_BADID, logger,
			    "%sikeport=%u must be between 1..65535, ignored",
			    leftright, src->host_ikeport);
		host_config->ikeport = 0;
	}

	/*
	 * Check for consistency between modecfgclient=,
	 * modecfgserver=, cat= and addresspool=.
	 *
	 * Danger:
	 *
	 * Since OE configurations can be both the client and the
	 * server they allow contradictions such as both
	 * leftmodecfgclient=yes leftmodecfgserver=yes.
	 *
	 * Danger:
	 *
	 * It's common practice to specify leftmodecfgclient=yes
	 * rightmodecfgserver=yes even though "right" isn't properly
	 * configured (for instance expecting leftaddresspool).
	 */

	if (src->modecfgserver == YN_YES && src->modecfgclient == YN_YES) {
		diag_t d = diag("both %smodecfgserver=yes and %smodecfgclient=yes defined",
				leftright, leftright);
		if (!is_opportunistic_wm(wm)) {
			return d;
		}
		llog(RC_LOG, logger, "opportunistic: %s", str_diag(d));
		pfree_diag(&d);
	}

	if (src->modecfgserver == YN_YES && src->cat == YN_YES) {
		diag_t d = diag("both %smodecfgserver=yes and %scat=yes defined",
				leftright, leftright);
		if (!is_opportunistic_wm(wm)) {
			return d;
		}
		llog(RC_LOG, logger, "opportunistic: %s", str_diag(d));
		pfree_diag(&d);
	}

	if (src->modecfgclient == YN_YES && other_src->cat == YN_YES) {
		diag_t d = diag("both %smodecfgclient=yes and %scat=yes defined",
				leftright, other_src->leftright);
		if (!is_opportunistic_wm(wm)) {
			return d;
		}
		llog(RC_LOG, logger, "opportunistic: %s", str_diag(d));
		pfree_diag(&d);
	}

	if (src->modecfgserver == YN_YES && src->addresspool != NULL) {
		diag_t d = diag("%smodecfgserver=yes does not expect %saddresspool=",
				leftright, src->leftright);
		if (!is_opportunistic_wm(wm)) {
			return d;
		}
		llog(RC_LOG, logger, "opportunistic: %s", str_diag(d));
		pfree_diag(&d);
	}

	/*
	 * XXX: this can't be rejected.  For instance, in
	 * ikev1-psk-dual-behind-nat-01, road has
	 * <east>modecfgserver=yes, but doesn't specify the address
	 * pool.  Arguably modecfgserver= should be ignored?
	 */
#if 0
	if (src->modecfgserver == YN_YES && other_src->addresspool == NULL) {
		diag_t d = diag("%smodecfgserver=yes expects %saddresspool=",
				leftright, other_src->leftright);
		if (!is_opportunistic_wm(wm)) {
			return d;
		}
		llog(RC_LOG, logger, "opportunistic: %s", str_diag(d));
		pfree_diag(&d);
	}
#endif

	if (src->modecfgclient == YN_YES && other_src->addresspool != NULL) {
		diag_t d = diag("%smodecfgclient=yes does not expect %saddresspool=",
				leftright, other_src->leftright);
		if (!is_opportunistic_wm(wm)) {
			return d;
		}
		llog(RC_LOG, logger, "opportunistic: %s", str_diag(d));
		pfree_diag(&d);
	}

	if (src->cat == YN_YES && other_src->addresspool != NULL) {
		diag_t d = diag("both %scat=yes and %saddresspool= defined",
				leftright, other_src->leftright);
		if (!is_opportunistic_wm(wm)) {
			return d;
		}
		llog(RC_LOG, logger, "opportunistic: %s", str_diag(d));
		pfree_diag(&d);
	}

	/*
	 * Update client/server based on config and addresspool
	 *
	 * The update uses OR so that the truth is blended with both
	 * the ADDRESSPOOL code's truth (see further down) and the
	 * reverse calls sense of truth.
	 *
	 * Unfortunately, no!
	 *
	 * This end having an addresspool should imply that this host
	 * is the client and the other host is the server.  Right?
	 *
	 * OE configurations have leftmodecfgclient=yes
	 * rightaddresspool= which creates a the connection that is
	 * both a client and a server.
	 */

	host_config->modecfg.server |= (src->modecfgserver == YN_YES);
	host_config->modecfg.client |= (src->modecfgclient == YN_YES);

	if (src->addresspool != NULL) {
		other_host_config->modecfg.server = true;
		host_config->modecfg.client = true;
		dbg("forced %s modecfg client=%s %s modecfg server=%s",
		    host_config->leftright, bool_str(host_config->modecfg.client),
		    other_host_config->leftright, bool_str(other_host_config->modecfg.server));
	}

	return NULL;
}

static diag_t extract_child_end_config(const struct whack_message *wm,
				       const struct whack_end *src,
				       struct connection *c,
				       struct child_end_config *child_config,
				       struct logger *logger)
{
	const char *leftright = src->leftright;

	switch (wm->ike_version) {
	case IKEv2:
#ifdef USE_CAT
		child_config->has_client_address_translation = (src->cat == YN_YES);
#endif
		break;
	case IKEv1:
		if (src->cat != YN_UNSET) {
			name_buf nb;
			llog(RC_LOG, logger,
			     "warning: IKEv1, ignoring %scat=%s (client address translation)",
			     leftright, str_sparse(&yn_option_names, src->cat, &nb));
		}
		break;
	default:
		bad_case(wm->ike_version);
	}

	child_config->host_vtiip = src->host_vtiip;

	if (never_negotiate_wm(wm)) {
		if (src->interface_ip != NULL) {
			llog(RC_LOG, logger,
			     "warning: %sinterface-ip=%s ignored when never negotiate",
			     leftright, src->interface_ip);
		}
	} else if (src->interface_ip != NULL) {
		err_t oops = ttocidr_num(shunk1(src->interface_ip), NULL,
					 &child_config->ipsec_interface_ip);
		if (oops != NULL) {
			return diag("%sinterface-ip=%s invalid, %s",
				    leftright, src->interface_ip, oops);
		}
		oops = cidr_check(child_config->ipsec_interface_ip);
		if (oops != NULL) {
			return diag("bad addr %sinterface-ip=%s, %s",
				    leftright, src->interface_ip, oops);
		}
	}

	/* save some defaults */
	child_config->protoport = src->protoport;

	/*
	 * Support for skipping updown, eg leftupdown="" or %disabled.
	 *
	 * Useful on busy servers that do not need to use updown for
	 * anything.
	 */
	if (never_negotiate_wm(wm)) {
		if (src->updown != NULL) {
			llog(RC_LOG, logger,
			     "warning: %supdown=%s ignored when never negotiate",
			     leftright, src->updown);
		}
	} else {
		/* Note: "" disables updown; but no updown gets default */
		child_config->updown =
			(src->updown == NULL ? clone_str(DEFAULT_UPDOWN, "default_updown") :
			 streq(src->updown, UPDOWN_DISABLED) ? NULL :
			 streq(src->updown, "") ? NULL :
			 clone_str(src->updown, "child_config.updown"));
	}


	ip_selectors *child_selectors = &child_config->selectors;

	/*
	 * Figure out the end's child selectors.
	 */
	if (src->addresspool != NULL) {

		/*
		 * Both ends can't add an address pool (cross
		 * checked).
		 */
		FOR_EACH_ELEMENT(pool, c->pool) {
			PASSERT(logger, (*pool) == NULL);
		}

		if (src->subnets != NULL) {
			/* XXX: why? */
			return diag("cannot specify both %saddresspool= and %ssubnets=",
				    leftright, leftright);
		}

		if (src->subnet != NULL) {
			/* XXX: why? */
			return diag("cannot specify both %saddresspool= and %ssubnet=",
				    leftright, leftright);
		}

		diag_t d = ttoranges_num(shunk1(src->addresspool), ", ", NULL,
					 &child_config->addresspools);
		if (d != NULL) {
			return diag_diag(&d, "%saddresspool=%s invalid, ", leftright, src->addresspool);
		}

		FOR_EACH_ITEM(range, &child_config->addresspools) {

			const struct ip_info *afi = range_type(range);

			if (wm->ike_version == IKEv1 && afi == &ipv6_info) {
				return diag("%saddresspool=%s invalid, IKEv1 does not support IPv6 address pool",
					    leftright, src->addresspool);
			}

			if (afi == &ipv6_info && !range_is_cidr((*range))) {
				range_buf rb;
				return diag("%saddresspool=%s invalid, IPv6 range %s is not a subnet",
					    leftright, src->addresspool,
					    str_range(range, &rb));
			}

			/*
			 * Create the address pool regardless of
			 * orientation.  Orienting will then add a
			 * reference as needed.
			 *
			 * This way, conflicting addresspools are
			 * detected early (OTOH, they may be detected
			 * when they don't matter).
			 *
			 * This also detetects and rejects multiple
			 * pools with the same address family.
			 */
			diag_t d = install_addresspool((*range), child_config->addresspool, logger);
			if (d != NULL) {
				return diag_diag(&d, "%saddresspool=%s invalid, ",
						 leftright, src->addresspool);
			}

		}

	} else if (src->subnet != NULL && (wm->ike_version == IKEv1 ||
					   src->protoport.is_set)) {

		/*
		 * Legacy syntax:
		 *
		 * - IKEv1
		 * - when protoport= was also specified
		 *
		 * Merge protoport into the selector.
		 */
		ip_subnet subnet;
		ip_address nonzero_host;
		err_t e = ttosubnet_num(shunk1(src->subnet), NULL,
					&subnet, &nonzero_host);
		if (nonzero_host.is_set) {
			address_buf hb;
			llog(RC_LOG, logger, "zeroing non-zero host identifier %s in %ssubnet=%s",
			     leftright, str_address(&nonzero_host, &hb), src->subnet);
		}
		if (e != NULL) {
			return diag("%ssubnet=%s invalid, %s",
				    leftright, src->subnet, e);
		}
		ldbg(logger, "%s child selectors from %ssubnet + %sprotoport; %s.config.has_client=true",
		     leftright, leftright, leftright, leftright);
		child_selectors->len = 1;
		child_selectors->list = alloc_things(ip_selector, 1, "subnet-selectors");
		child_selectors->list[0] =
			selector_from_subnet_protoport(subnet, src->protoport);
		const struct ip_info *afi = subnet_info(subnet);
		child_selectors->ip[afi->ip_index].len = 1;
		child_selectors->ip[afi->ip_index].list = child_selectors->list;

	} else if (src->subnet != NULL) {

		/*
		 * Parse new syntax (protoport= is not used).
		 *
		 * Of course if NARROWING is allowed, this can be
		 * refined regardless of .has_client.
		 */
		ldbg(logger, "%s child selectors from %ssubnet (selector); %s.config.has_client=true",
		     leftright, leftright, leftright);
		passert(wm->ike_version == IKEv2);
		ip_address nonzero_host;
		diag_t d = ttoselectors_num(shunk1(src->subnet), ", ", NULL,
					    &child_config->selectors, &nonzero_host);
		if (d != NULL) {
			return diag_diag(&d, "%ssubnet=%s invalid, ",
					 leftright, src->subnet);
		}
		if (nonzero_host.is_set) {
			address_buf hb;
			llog(RC_LOG, logger,
			     "zeroing non-sero address identifier %s in %ssubnet=%s",
			     str_address(&nonzero_host, &hb), leftright, src->subnet);
		}
	} else {
		ldbg(logger, "%s child selectors unknown; probably derived from host?!?",
		     leftright);
	}

	/*
	 * Also extract .virt.
	 *
	 * While subnet= can only specify .virt XOR .client, the end
	 * result can be that both .virt and .client are set.
	 *
	 * XXX: don't set .has_client as update_child_ends*() will see
	 * it and skip updating the client address from the host.
	 */
	if (src->virt != NULL) {
		if (wm->ike_version > IKEv1) {
			return diag("IKEv%d does not support virtual subnets",
				    wm->ike_version);
		}
		dbg("%s %s child has a virt-end", wm->name, leftright);
		diag_t d = create_virtual(leftright, src->virt,
					  &child_config->virt);
		if (d != NULL) {
			return d;
		}
	}

	/*
	 * Get the SOURCEIPs and check that they all fit within at
	 * least one selector determined above (remember, when the
	 * selector isn't specified (i.e., subnet=), the selector is
	 * set to the .host_addr).
	 */

	if (src->sourceip != NULL) {
		if (src->interface_ip != NULL) {
			return diag("cannot specify %sinterface-ip=%s and %sssourceip=%s",
				    leftright, src->interface_ip,
				    leftright, src->sourceip);
		}

		diag_t d = ttoaddresses_num(shunk1(src->sourceip), ", ",
					    NULL/*UNSPEC*/, &child_config->sourceip);
		if (d != NULL) {
			return diag_diag(&d, "%ssourceip=%s invalid, ",
					 src->leftright, src->sourceip);
		}
		/* valid? */
		ip_address seen[IP_INDEX_ROOF] = {0};
		FOR_EACH_ITEM(sourceip, &child_config->sourceip) {

			/* i.e., not :: and not 0.0.0.0 */
			if (!address_is_specified(*sourceip)) {
				return diag("%ssourceip=%s invalid, must be a valid address",
					    leftright, src->sourceip);
			}

			/* i.e., not 1::1,1::2 */
			const struct ip_info *afi = address_type(sourceip);
			PASSERT(logger, afi != NULL); /* since specified */
			if (seen[afi->ip_index].is_set) {
				address_buf sb, ipb;
				return diag("%ssourceip=%s invalid, multiple %s addresses (%s and %s) specified",
					    leftright, src->sourceip, afi->ip_name,
					    str_address(&seen[afi->ip_index], &sb),
					    str_address(sourceip, &ipb));
			}
			seen[afi->ip_index] = (*sourceip);

			if (child_config->selectors.len > 0) {
				/* skip aliases; they hide the selectors list */
				if (wm->connalias != NULL) {
					continue;
				}
				bool within = false;
				FOR_EACH_ITEM(sel, &child_config->selectors) {
					/*
					 * Only compare the address
					 * against the selector's
					 * address range (not the
					 * /protocol/port).
					 *
					 * For instance when the
					 * selector is:
					 *
					 *   1::/128/tcp/22
					 *
					 * the sourceip=1:: is still
					 * ok.
					 */
					if (address_in_selector_range(*sourceip, *sel)) {
						within = true;
						break;
					}
				}
				if (!within) {
					address_buf sipb;
					return diag("%ssourceip=%s invalid, address %s is not within %ssubnet=%s",
						    leftright, src->sourceip,
						    str_address(sourceip, &sipb),
						    leftright, src->subnet);
				}
			} else if (src->host_addr.is_set) {
				if (!address_eq_address(*sourceip, src->host_addr)) {
					address_buf sipb;
					address_buf hab;
					return diag("%ssourceip=%s invalid, address %s does not match %s=%s and %ssubnet= was not specified",
						    leftright, src->sourceip,
						    str_address(sourceip, &sipb),
						    leftright, str_address(&src->host_addr, &hab),
						    leftright);
				}
			} else {
				return diag("%ssourceip=%s invalid, %ssubnet= unspecified and %s IP address unknown",
					    leftright, src->sourceip,
					    leftright/*subnet=*/, leftright/*host=*/);
			}
		}
	}
	return NULL;
}

diag_t add_end_cert_and_preload_private_key(CERTCertificate *cert,
					    struct host_end_config *host_end_config,
					    bool preserve_ca,
					    struct logger *logger)
{
	passert(cert != NULL);
	const char *nickname = cert->nickname;
	const char *leftright = host_end_config->leftright;

	/*
	 * A copy of this code lives in nss_cert_verify.c :/
	 * Currently only a check for RSA is needed, as the only ECDSA
	 * key size not allowed in FIPS mode (p192 curve), is not implemented
	 * by NSS.
	 * See also RSA_secret_sane() and ECDSA_secret_sane()
	 */
	if (is_fips_mode()) {
		SECKEYPublicKey *pk = CERT_ExtractPublicKey(cert);
		passert(pk != NULL);
		if (pk->keyType == rsaKey &&
		    ((pk->u.rsa.modulus.len * BITS_IN_BYTE) < FIPS_MIN_RSA_KEY_SIZE)) {
			SECKEY_DestroyPublicKey(pk);
			return diag("FIPS: rejecting %s certificate '%s' with key size %d which is under %d",
				    leftright, nickname,
				    pk->u.rsa.modulus.len * BITS_IN_BYTE,
				    FIPS_MIN_RSA_KEY_SIZE);
		}
		/* TODO FORCE MINIMUM SIZE ECDSA KEY */
		SECKEY_DestroyPublicKey(pk);
	}

	/* check validity of cert */
	if (CERT_CheckCertValidTimes(cert, PR_Now(), false) != secCertTimeValid) {
		return diag("%s certificate '%s' is expired or not yet valid",
			    leftright, nickname);
	}

	/*
	 * Note: this is passing in the pre-%fromcert updated ID.
	 *
	 * add_pubkey_from_nss_cert() adds pubkeys under: the cert's
	 * subject name, and cert's subject alt names (SAN).  It then,
	 * when ID isn't %fromcert, or DN (i.e., subject name making
	 * it redundant), adds a further pubkey under the ID's name
	 * (for instance @east?).
	 *
	 * Hence, using the non-updated ID from config is fine.
	 */
	ldbg(logger, "adding %s certificate \'%s\' pubkey", leftright, cert->nickname);
	if (!add_pubkey_from_nss_cert(&pluto_pubkeys, &host_end_config->id, cert, logger)) {
		/* XXX: push diag_t into add_pubkey_from_nss_cert()? */
		return diag("%s certificate \'%s\' pubkey could not be loaded", leftright, cert->nickname);
	}

	host_end_config->cert.nss_cert = cert;

	/*
	 * If no CA is defined, use issuer as default; but only when
	 * update is ok (when reloading certs it is never ok).
	 */
	if (preserve_ca || host_end_config->ca.ptr != NULL) {
		dbg("preserving existing %s ca", leftright);
	} else {
		host_end_config->ca = clone_secitem_as_chunk(cert->derIssuer, "issuer ca");
	}

	/*
	 * Try to pre-load the certificate's secret (private key) into
	 * the local cache (see keys.c).
	 *
	 * This can fail.  For instance, this end may only have the
	 * peer's certificate
	 *
	 * This could also fail because a needed secret is missing.
	 * That case is handled by refine_host_connection /
	 * get_psk.
	 */
	dbg("preload cert/secret for connection: %s", cert->nickname);
	bool load_needed;
	err_t ugh = preload_private_key_by_cert(&host_end_config->cert, &load_needed, logger);
	if (ugh != NULL) {
		dbg("no private key matching %s certificate %s: %s",
		    leftright, nickname, ugh);
	} else if (load_needed) {
		llog(LOG_STREAM/*not-whack-for-now*/, logger,
		     "loaded private key matching %s certificate '%s'",
		     leftright, nickname);
	}
	return NULL;
}

/* only used by add_connection() */
static void mark_parse(/*const*/ char *wmmark,
		       struct sa_mark *sa_mark,
		       struct logger *logger/*connection "...":*/)
{
	/*const*/ char *val_end;

	sa_mark->unique = false;
	sa_mark->val = 0xffffffff;
	sa_mark->mask = 0xffffffff;
	if (streq(wmmark, "-1") || startswith(wmmark, "-1/")) {
		sa_mark->unique = true;
		val_end = wmmark + strlen("-1");
	} else {
		errno = 0;
		unsigned long v = strtoul(wmmark, &val_end, 0);
		if (errno != 0 || v > 0xffffffff ||
		    (*val_end != '\0' && *val_end != '/'))
		{
			/* ??? should be detected and reported by confread and whack */
			/* XXX: don't trust whack */
			llog(RC_LOG, logger,
				    "bad mark value \"%s\"", wmmark);
		} else {
			sa_mark->val = v;
		}
	}

	if (*val_end == '/') {
		/*const*/ char *mask_end;
		errno = 0;
		unsigned long v = strtoul(val_end+1, &mask_end, 0);
		if (errno != 0 || v > 0xffffffff || *mask_end != '\0') {
			/* ??? should be detected and reported by confread and whack */
			/* XXX: don't trust whack */
			llog(RC_LOG, logger,
				   "bad mark mask \"%s\"", mask_end);
		} else {
			sa_mark->mask = v;
		}
	}
	if ((sa_mark->val & ~sa_mark->mask) != 0) {
		/* ??? should be detected and reported by confread and whack */
		/* XXX: don't trust whack */
		llog(RC_LOG, logger,
			    "mark value %#08" PRIx32 " has bits outside mask %#08" PRIx32,
			    sa_mark->val, sa_mark->mask);
	}
}

/*
 * Turn the config selectors / addresspool / host-addr into proposals.
 */

void add_proposals(struct connection *d, const struct ip_info *host_afi,
		   struct verbose verbose)
{
	vdbg("%s() host-afi=%s", __func__, (host_afi == NULL ? "N/A" : host_afi->ip_name));
	verbose.level++;

	FOR_EACH_ELEMENT(end, d->end) {
		const char *leftright = end->config->leftright;

		vassert(end->child.selectors.proposed.list == NULL);
		vassert(end->child.selectors.proposed.len == 0);
		vexpect(end->child.has_client == false);

		/* {left,right}subnet=... */
		if (end->child.config->selectors.len > 0) {
			vdbg("%s selectors from %d child.selectors",
			     leftright, end->child.config->selectors.len);
			end->child.selectors.proposed = end->child.config->selectors;
			/*
			 * This is important, but why?
			 *
			 * IKEv1: the initiator should send the client
			 * ID during quick mode.
			 */
			set_end_child_has_client(d, end->config->index, true);
			continue;
		}

		/* {left,right}addresspool= */
		if (end->child.config->addresspools.len > 0) {
			/*
			 * Set the selectors to the pool range:
			 *
			 * IKEv2: addresspool implies narrowing so
			 * peer sending ::/0 will be allowed to narrow
			 * down to the addresspool range.
			 *
			 * IKEv1: peer is expected to send the lease
			 * it obtained earlier (either during
			 * MODE_CFG, or hard-wired in the config
			 * file).
			 */
			FOR_EACH_ITEM(range, &end->child.config->addresspools) {
				ip_selector selector = selector_from_range((*range));
				selector_buf sb;
				vdbg("%s selector formed from address pool %s",
				     leftright, str_selector(&selector, &sb));
				append_end_selector(end, selector_info(selector), selector, verbose.logger, HERE);
			}
			continue;
		}

		/* {left,right}= */
		if (address_is_specified(end->host.addr)) {
			/*
			 * Default the end's child selector (client)
			 * to a subnet containing only the end's host
			 * address.
			 *
			 * If the other end has multiple child
			 * selectors then the combination becomes a
			 * list.
			 */
			address_buf ab;
			protoport_buf pb;
			vdbg("%s selector proposals from host address+protoport %s %s",
			     leftright,
			     str_address(&end->host.addr, &ab),
			     str_protoport(&end->child.config->protoport, &pb));
			ip_selector selector =
				selector_from_address_protoport(end->host.addr,
								end->child.config->protoport);
			append_end_selector(end, selector_info(selector), selector, verbose.logger, HERE);
			continue;
		}

		/*
		 * to-be-determined from the host (for instance,
		 * waiting on DNS) or the opportunistic group (needs
		 * to be expanded).
		 *
		 * Make space regardless so that loops have something
		 * to iterate over.
		 */
		if (vbad(host_afi == NULL)) {
			return;
		}

		vexpect(is_permanent(d) || is_group(d) || is_template(d));
		vdbg("%s selector proposals from unset host family %s",
		     leftright, host_afi->ip_name);
		append_end_selector(end, host_afi, unset_selector, verbose.logger, HERE);
	}
}

void init_connection_spd(struct connection *c, struct spd *spd)
{
	/* back link */
	spd->connection = c;
	/* local link */
	spd->local = &spd->end[c->local->config->index];	/*clone must update*/
	spd->remote = &spd->end[c->remote->config->index];	/*clone must update*/
	FOR_EACH_THING(end, LEFT_END, RIGHT_END) {
		spd->end[end].config = c->end[end].config;
		spd->end[end].host = &c->end[end].host;		/*clone must update*/
		spd->end[end].child = &c->end[end].child;	/*clone must update*/
	}
	/* db; will be updated */
	spd_db_init_spd(spd);
}

void alloc_connection_spds(struct connection *c, unsigned nr_spds)
{
	PASSERT(c->logger, c->child.spds.len == 0);
	ldbg(c->logger, "allocating %u SPDs", nr_spds);
	c->child.spds = (struct spds) {
		.len = nr_spds,
		.list = alloc_things(struct spd, nr_spds, "spds"),
	};
	c->spd = c->child.spds.list;
	FOR_EACH_ITEM(spd, &c->child.spds) {
		init_connection_spd(c, spd);
	}
}

void add_connection_spds(struct connection *c)
{
	unsigned indent = 0;
	ldbg(c->logger, "%*sadding connection spds using proposed", indent, "");

	indent = 1;
	const ip_selectors *left = &c->end[LEFT_END].child.selectors.proposed;
	const ip_selectors *right = &c->end[RIGHT_END].child.selectors.proposed;
	ldbg(c->logger, "%*sleft=%u right=%u",
	     indent, "", left->len, right->len);

	/* Calculate the total number of SPDs. */
	unsigned nr_spds = 0;
	FOR_EACH_ELEMENT(afi, ip_families) {
		const ip_selectors *left = &c->end[LEFT_END].child.selectors.proposed;
		const ip_selectors *right = &c->end[RIGHT_END].child.selectors.proposed;
		ldbg(c->logger, "%*sleft[%s]=%u right[%s]=%u",
		     indent+1, "",
		     afi->ip_name, left->ip[afi->ip_index].len,
		     afi->ip_name, right->ip[afi->ip_index].len);
		nr_spds += (left->ip[afi->ip_index].len * right->ip[afi->ip_index].len);
	}

	/* Allocate the SPDs. */
	alloc_connection_spds(c, nr_spds);

	/* Now fill them in. */
	unsigned spds = 0;
	FOR_EACH_ELEMENT(afi, ip_families) {
		enum ip_index ip = afi->ip_index;
		const ip_selectors *left_selectors = &c->end[LEFT_END].child.selectors.proposed;
		FOR_EACH_ITEM(left_selector, &left_selectors->ip[ip]) {
			const ip_selectors *right_selectors = &c->end[RIGHT_END].child.selectors.proposed;
			FOR_EACH_ITEM(right_selector, &right_selectors->ip[ip]) {
				indent = 2;
				selector_pair_buf spb;
				ldbg(c->logger, "%*s%s", indent, "",
				     str_selector_pair(left_selector, right_selector, &spb));
				indent = 3;
				struct spd *spd = &c->child.spds.list[spds++];
				PASSERT(c->logger, spd < c->child.spds.list + c->child.spds.len);
				ip_selector *selectors[] = {
					[LEFT_END] = left_selector,
					[RIGHT_END] = right_selector,
				};
				FOR_EACH_THING(end, LEFT_END, RIGHT_END) {
					const ip_selector *selector = selectors[end];
					const struct child_end_config *child_end = &c->end[end].config->child;
					struct spd_end *spd_end = &spd->end[end];
					const char *leftright = child_end->leftright;
					spd_end->client = *selector;
					spd_end->virt = virtual_ip_addref(child_end->virt);
					selector_buf sb;
					ldbg(c->logger,
					     "%*s%s child spd from selector %s %s.spd.has_client=%s virt=%s",
					     indent, "", spd_end->config->leftright,
					     str_selector(&spd_end->client, &sb),
					     leftright,
					     bool_str(spd_end->child->has_client),
					     bool_str(spd_end->virt != NULL));
				}
				spd_db_add(spd);
			}
		}
	}
}

/*
 * Extract the connection detail from the whack message WM and store
 * them in the connection C.
 *
 * This code is responsible for cloning strings and other structures
 * so that they out live the whack message.  When things go wrong,
 * return false, the caller will then use discard_connection() to free
 * the partially constructed connection.
 *
 * Checks from confread/whack should be moved here so it is similar
 * for all methods of loading a connection.
 *
 * XXX: at one point this code was populating the connection with
 * pointer's to the whack message's strings and then trying to use
 * unshare_connection() to create local copies.  Bad idea.  For
 * instance, it duplicated the proposal pointers yet here the pointer
 * was freshy allocated so no duplication should be needed (or at
 * least shouldn't be) (look for strange free() vs delref() sequence).
 */

static diag_t extract_lifetime(deltatime_t *lifetime,
			       const char *lifetime_name,
			       deltatime_t whack_lifetime,
			       deltatime_t default_lifetime,
			       deltatime_t lifetime_max,
			       deltatime_t lifetime_fips,
			       deltatime_t rekeymargin,
			       struct logger *logger,
			       const struct whack_message *wm)
{
	const char *source;
	if (whack_lifetime.is_set) {
		source = "whack";
		*lifetime = whack_lifetime;
	} else {
		source = "default";
		*lifetime = default_lifetime;
	}

	/*
	 * Determine the MAX lifetime
	 *
	 * http://csrc.nist.gov/publications/nistpubs/800-77/sp800-77.pdf
	 */
	const char *fips;
	deltatime_t max_lifetime;
	if (is_fips_mode()) {
		fips = "FIPS: ";
		max_lifetime = lifetime_fips;
	} else {
		fips = "";
		max_lifetime = lifetime_max;
	}

	if (impair.lifetime) {
		llog(RC_LOG, logger, "IMPAIR: skipping %s=%jd checks",
		     lifetime_name, deltasecs(*lifetime));
		return NULL;
	}

	/*
	 * Determine the minimum lifetime.  Use:
	 *
	 *    rekeymargin*(100+rekeyfuzz)/100
	 *
	 * which is the maximum possible rekey margin.  INT_MAX is
	 * arbitrary as an upper bound - anything to stop overflow.
	 */
	if (wm->sa_rekeyfuzz_percent > INT_MAX - 100) {
		return diag("rekeyfuzz=%jd%% is so large it causes overflow",
			    wm->sa_rekeyfuzz_percent);
	}

	deltatime_t min_lifetime = deltatime_scale(rekeymargin,
						   100 + wm->sa_rekeyfuzz_percent,
						   100);

	if (deltatime_cmp(max_lifetime, <, min_lifetime)) {
		return diag("%s%s=%jd must be greater than rekeymargin=%jus + rekeyfuzz=%jd%% yet less than the maximum allowed %ju",
			    fips, 
			    lifetime_name, deltasecs(*lifetime),
			    deltasecs(rekeymargin), wm->sa_rekeyfuzz_percent,
			    deltasecs(min_lifetime));
	}

	if (deltatime_cmp(*lifetime, >, max_lifetime)) {
		llog(RC_LOG, logger,
		     "%s%s=%ju seconds exceeds maximum of %ju seconds, setting to the maximum allowed",
		     fips,
		     lifetime_name, deltasecs(*lifetime),
		     deltasecs(max_lifetime));
		source = "max";
		*lifetime = max_lifetime;
	} else if (deltatime_cmp(*lifetime, <, min_lifetime)) {
		llog(RC_LOG, logger,
		     "%s=%jd must be greater than rekeymargin=%jus + rekeyfuzz=%jd%%, setting to %jd seconds",
		     lifetime_name, deltasecs(*lifetime),
		     deltasecs(wm->rekeymargin),
		     wm->sa_rekeyfuzz_percent,
		     deltasecs(min_lifetime));
		source = "min";
		*lifetime = min_lifetime;
	}

	deltatime_buf db;
	ldbg(logger, "%s=%s (%s)", lifetime_name, source, str_deltatime(*lifetime, &db));
	return NULL;
}

static enum connection_kind extract_connection_end_kind(const struct whack_message *wm,
							const struct whack_end *this,
							const struct whack_end *that,
							struct logger *logger)
{
	if (is_group_wm(wm)) {
		ldbg(logger, "%s connection is CK_GROUP: by is_group_wm()",
		     this->leftright);
		return CK_GROUP;
	}
	if (wm->sec_label != NULL) {
		ldbg(logger, "%s connection is CK_LABELED_TEMPLATE: has security label: %s",
		     this->leftright, wm->sec_label);
		return CK_LABELED_TEMPLATE;
	}
	if(wm->narrowing == YN_YES) {
		ldbg(logger, "%s connection is CK_TEMPLATE: narrowing=yes",
		     this->leftright);
		return CK_TEMPLATE;
	}
	if (that->virt != NULL) {
		/*
		 * A peer with subnet=vnet:.. needs instantiation so
		 * we can accept multiple subnets from that peer.
		 */
		ldbg(logger, "%s connection is CK_TEMPLATE: %s has vnets at play",
		     this->leftright, that->leftright);
		return CK_TEMPLATE;
	}
	if (that->addresspool != NULL) {
		ldbg(logger, "%s connection is CK_TEMPLATE: %s has an address pool",
		     this->leftright, that->leftright);
		return CK_TEMPLATE;
	}
	if (that->protoport.is_set /*technically-redundant*/ &&
	    that->protoport.has_port_wildcard) {
		ldbg(logger, "%s connection is CK_TEMPLATE: %s child has protoport wildcard port",
		     this->leftright, that->leftright);
		return CK_TEMPLATE;
	}
	FOR_EACH_THING(we, this, that) {
		if (!never_negotiate_wm(wm) &&
		    !address_is_specified(we->host_addr) &&
		    we->host_type != KH_IPHOSTNAME) {
			ldbg(logger, "%s connection is CK_TEMPLATE: unspecified %s address yet policy negotiate",
			     this->leftright, we->leftright);
			return CK_TEMPLATE;
		}
	}
	ldbg(logger, "%s connection is CK_PERMANENT: by default",
	     this->leftright);
	return CK_PERMANENT;
}

static bool shunt_ok(enum shunt_kind shunt_kind, enum shunt_policy shunt_policy)
{
	static const bool ok[SHUNT_KIND_ROOF][SHUNT_POLICY_ROOF] = {
		[SHUNT_KIND_NONE] = {
			[SHUNT_UNSET] = true,
		},
		[SHUNT_KIND_NEVER_NEGOTIATE] = {
			[SHUNT_UNSET] = true,
			[SHUNT_NONE] = false, [SHUNT_HOLD] = false, [SHUNT_TRAP] = false, [SHUNT_PASS] = true,  [SHUNT_DROP] = true,  [SHUNT_REJECT] = true,
		},
		[SHUNT_KIND_NEGOTIATION] = {
			[SHUNT_NONE] = false, [SHUNT_HOLD] = true,  [SHUNT_TRAP] = false, [SHUNT_PASS] = true,  [SHUNT_DROP] = false, [SHUNT_REJECT] = false,
		},
		[SHUNT_KIND_FAILURE] = {
			[SHUNT_NONE] = true,  [SHUNT_HOLD] = false, [SHUNT_TRAP] = false, [SHUNT_PASS] = true,  [SHUNT_DROP] = true,  [SHUNT_REJECT] = true,
		},
		/* hard-wired */
		[SHUNT_KIND_IPSEC] = { [SHUNT_IPSEC] = true, },
		[SHUNT_KIND_BLOCK] = { [SHUNT_DROP] = true, },
		[SHUNT_KIND_ONDEMAND] = { [SHUNT_TRAP] = true, },
	};
	return ok[shunt_kind][shunt_policy];
}

static diag_t extract_shunt(struct config *config,
			    const struct whack_message *wm,
			    enum shunt_kind shunt_kind,
			    enum shunt_policy unset_shunt)
{
	enum shunt_policy shunt_policy = wm->shunt[shunt_kind];
	if (shunt_policy == SHUNT_UNSET) {
		shunt_policy = unset_shunt;
	}
	if (!shunt_ok(shunt_kind, shunt_policy)) {
		JAMBUF(buf) {
			jam_enum_human(buf, &shunt_kind_names, shunt_kind);
			jam_string(buf, "shunt=");
			jam_enum_human(buf, &shunt_policy_names, shunt_policy);
			jam_string(buf, " invalid");
			return diag_jambuf(buf);
		}
	}
	config->shunt[shunt_kind] = shunt_policy;
	return NULL;
}

static char *alloc_connection_prefix(const char *name, const struct connection *t/*could be NULL*/)
{
	if (t == NULL || t->next_instance_serial == 0) {
		/* permanent; group; ... */
		return alloc_printf("\"%s\"", name);
	}

	/*
	 * Form new prefix by appending next serial to existing
	 * prefix.
	 */
	return alloc_printf("%s[%lu]", t->prefix, t->next_instance_serial);
}

static struct config *alloc_config(enum ike_version ike_version)
{
	struct config *config = alloc_thing(struct config, "root config");
	/* stuff that can't fail! */
	config->ike_version = ike_version;
	FOR_EACH_THING(lr, LEFT_END, RIGHT_END) {
		/* "left" or "right" */
		const char *leftright =
			(lr == LEFT_END ? "left" :
			 lr == RIGHT_END ? "right" :
			 NULL);
		passert(leftright != NULL);
		struct config_end *end_config = &config->end[lr];
		end_config->leftright = leftright;
		end_config->index = lr;
		end_config->host.leftright = leftright;
		end_config->child.leftright = leftright;
	}
	return config;
}

struct connection *alloc_connection(const char *name,
				    struct connection *t,
				    const struct config *config,
				    lset_t debugging,
				    struct logger *logger,
				    where_t where)
{
	struct connection *c = refcnt_alloc(struct connection, where);

	/* before alloc_logger(); can't use C */
	c->name = clone_str(name, __func__);

	/* before alloc_logger(); can't use C */
	c->prefix = alloc_connection_prefix(name, t);

	/* after .name and .name_prefix are set; needed by logger */
	c->logger = alloc_logger(c, &logger_connection_vec,
				 debugging, where);

	/* after alloc_logger(); connection's first gasp */
	connection_attach(c, logger);

	/*
	 *  Update the .instance_serial.
	 */
	if (t != NULL && t->next_instance_serial > 0) {
		/* restart count in instance */
		c->next_instance_serial = 1;
		c->instance_serial = t->next_instance_serial;
		t->next_instance_serial++;
		pdbg(t->logger, "template .instance_serial_next updated to %lu; instance %lu",
		     t->next_instance_serial,
		     c->instance_serial);
	}

	/*
	 * Determine left/right vs local/remote.
	 *
	 * When there's no template, LOCAL and REMOTE are disoriented
	 * so the decision is arbitrary.  Keep with the historic
	 * convention:
	 *
	 *    LEFT == LOCAL / THIS
	 *    RIGHT == REMOTE / THAT
	 *
	 * Needed by the hash table code that expects .that->host.id
	 * to work.
	 */

	enum end local = (t == NULL ? LEFT_END : t->local->config->index);
	enum end remote = (t == NULL ? RIGHT_END : t->remote->config->index);

	c->local = &c->end[local];	/* this; clone must update */
	c->remote = &c->end[remote];	/* that; clone must update */

	/*
	 * Point connection's end's config at corresponding entries in
	 * config.
	 *
	 * Needed by the connection_db code when it tries to log.
	 */
	c->config = config;
	FOR_EACH_THING(lr, LEFT_END, RIGHT_END) {
		/* "left" or "right" */
		struct connection_end *end = &c->end[lr];
		const struct config_end *end_config = &c->config->end[lr];
		end->config = end_config;
		end->host.config = &end_config->host;
		end->child.config = &end_config->child;
	}

	/* somewhat oriented can start hashing */
	connection_db_init_connection(c);

	connection_routing_init(c);

	/*
	 * Update counter, set serialno and add to serialno list.
	 *
	 * The connection will be hashed after the caller has finished
	 * populating it.
	 */
	static co_serial_t connection_serialno;
	connection_serialno++;
	passert(connection_serialno > 0); /* can't overflow */
	c->serialno = connection_serialno;
	c->clonedfrom = connection_addref(t, c->logger);

	return c;
}

const struct ike_info ikev1_info = {
	.version = IKEv1,
	.version_name = "IKEv1",
	.parent_name = "ISAKMP",
	.child_name = "IPsec",
	.parent_sa_name = "ISAKMP SA",
	.child_sa_name = "IPsec SA",
	.expire_event[SA_HARD_EXPIRED] = EVENT_v1_EXPIRE,
	.expire_event[SA_SOFT_EXPIRED] = EVENT_v1_REPLACE,
	.replace_event = EVENT_v1_REPLACE,
	.retransmit_event = EVENT_v1_RETRANSMIT,
};

const struct ike_info ikev2_info = {
	.version = IKEv2,
	.version_name = "IKEv2",
	.parent_name = "IKE",
	.child_name = "Child",
	.parent_sa_name = "IKE SA",
	.child_sa_name = "Child SA",
	.expire_event[SA_HARD_EXPIRED] = EVENT_v2_EXPIRE,
	.expire_event[SA_SOFT_EXPIRED] = EVENT_v2_REKEY,
	.replace_event = EVENT_v2_REPLACE,
	.retransmit_event = EVENT_v2_RETRANSMIT,
};

static const struct ike_info *const ike_info[] = {
	[IKEv1] = &ikev1_info,
	[IKEv2] = &ikev2_info,
};

static diag_t extract_connection(const struct whack_message *wm,
				 struct connection *c,
				 struct config *config)
{
	diag_t d;

	const struct whack_end *whack_ends[] = {
		[LEFT_END] = &wm->end[LEFT_END],
		[RIGHT_END] = &wm->end[RIGHT_END],
	};

	/*
	 * Determine the Host's address family.
	 */
	const struct ip_info *host_afi = NULL;
	d = extract_host_afi(wm, &host_afi);
	if (d != NULL) {
		return d;
	}

	if (host_afi == NULL) {
		return diag("host address family unknown");
	}

	/*
	 * Determine the host topology.
	 *
	 * Needs two passes: first pass extracts tentative
	 * host/nexthop; scecond propagates that to other dependent
	 * fields.
	 *
	 * XXX: the host lookup is blocking; should instead do it
	 * asynchronously using unbound.
	 */
	ip_address host_addr[END_ROOF];
	FOR_EACH_THING(end, LEFT_END, RIGHT_END) {
		const struct whack_end *we = whack_ends[end];
		host_addr[end] = host_afi->address.unspec;
		if (address_is_specified(we->host_addr)) {
			host_addr[end] = we->host_addr;
		} else if (we->host_type == KH_IPHOSTNAME) {
			ip_address addr;
			err_t er = ttoaddress_dns(shunk1(we->host_addr_name),
						  host_afi, &addr);
			if (er != NULL) {
				llog(RC_LOG, c->logger,
				     "failed to resolve '%s=%s' at load time: %s",
				     we->leftright, we->host_addr_name, er);
			} else {
				host_addr[end] = addr;
			}
		}
	}

	/*
	 * Unpack and verify the ends.
	 */

	bool same_ca[END_ROOF] = { false, };

	FOR_EACH_THING(this, LEFT_END, RIGHT_END) {
		diag_t d;
		int that = (this + 1) % END_ROOF;
		d = extract_host_end(&c->end[this].host,
				     &config->end[this].host,
				     &config->end[that].host,
				     wm,
				     whack_ends[this],
				     whack_ends[that],
				     &same_ca[this],
				     c->logger);
		if (d != NULL) {
			return d;
		}
	}

	/*
	 * Determine the connection KIND from the wm.
	 *
	 * Save it in a local variable so code can use that (and be
	 * forced to only use value after it's been determined).  Yea,
	 * hack.
	 */
	FOR_EACH_THING(this, LEFT_END, RIGHT_END) {
		enum end that = (this + 1) % END_ROOF;
		c->end[this].kind =
			extract_connection_end_kind(wm,
						    whack_ends[this],
						    whack_ends[that],
						    c->logger);
	}

	passert(c->name != NULL); /* see alloc_connection() */

	/*
	 * Extract policy bits.
	 */

	bool pfs = extract_yn("", "pfs", wm->pfs, true, wm, c->logger);
	config->child_sa.pfs = pfs;

	bool compress = extract_yn("", "compress", wm->compress, false, wm, c->logger);
	config->child_sa.ipcomp = compress;

	/* sanity check?  done below */
	enum encap_proto encap_proto;
	if (never_negotiate_wm(wm)) {
		if (wm->phase2 != ENCAP_PROTO_UNSET) {
			enum_buf sb;
			llog(RC_LOG, c->logger,
			     "warning: phase2=%s ignored for never-negotiate connection",
			     str_enum(&encap_proto_story, wm->phase2, &sb));
		}
		encap_proto = ENCAP_PROTO_UNSET;
	} else {
		encap_proto = (wm->phase2 == ENCAP_PROTO_UNSET ? ENCAP_PROTO_ESP :
			       wm->phase2);
	}
	config->child_sa.encap_proto = encap_proto;

	enum encap_mode encap_mode;
	if (wm->type == KS_UNSET) {
		encap_mode = ENCAP_MODE_TUNNEL;
	} else if (wm->type == KS_TUNNEL) {
		encap_mode = ENCAP_MODE_TUNNEL;
	} else if (wm->type == KS_TRANSPORT) {
		encap_mode = ENCAP_MODE_TRANSPORT;
	} else {
		if (!never_negotiate_wm(wm)) {
			sparse_buf sb;
			llog_pexpect(c->logger, HERE,
				     "type=%s should be never-negotiate",
				     str_sparse(&type_option_names, wm->type, &sb));
		}
		encap_mode = ENCAP_MODE_UNSET;
	}
	config->child_sa.encap_mode = encap_mode;

	if (encap_mode == ENCAP_MODE_TRANSPORT) {
		if (wm->vti_interface != NULL) {
			return diag("VTI requires tunnel mode but connection specifies type=transport");
		}
	}

	if (wm->authby.never) {
		if (wm->never_negotiate_shunt == SHUNT_UNSET) {
			return diag("connection with authby=never must specify shunt type via type=");
		}
	}
	if (wm->never_negotiate_shunt != SHUNT_UNSET) {
		if (!authby_eq(wm->authby, AUTHBY_NONE) &&
		    !authby_eq(wm->authby, AUTHBY_NEVER)) {
			authby_buf ab;
			enum_buf sb;
			return diag("kind=%s shunt connection cannot have authby=%s authentication",
				    str_enum_short(&shunt_policy_names, wm->never_negotiate_shunt, &sb),
				    str_authby(wm->authby, &ab));
		}
	}

	if (wm->ike_version == IKEv1) {
#ifdef USE_IKEv1
		if (pluto_ikev1_pol != GLOBAL_IKEv1_ACCEPT) {
			return diag("global ikev1-policy does not allow IKEv1 connections");
		}
#else
		return diag("IKEv1 support not compiled in");
#endif
	}

	if ((wm->ike_version == IKEv1 && wm->ikev2 == YN_YES) ||
	    (wm->ike_version == IKEv2 && wm->ikev2 == YN_NO)) {
		enum_buf vn;
		llog(RC_LOG, c->logger,
		     "ignoring ikev2=%s which conflicts with keyexchange=%s",
		     (wm->ikev2 == YN_YES ? "yes" :
		      wm->ikev2 == YN_NO ? "no" :
		      "???"),
		     str_enum(&ike_version_names, wm->ike_version, &vn));
	} else if (wm->ikev2 != 0) {
		llog(RC_LOG, c->logger,
		     "ikev2=%s has been replaced by keyexchange=%s",
		     (wm->ikev2 == YN_YES ? "yes" :
		      wm->ikev2 == YN_NO ? "no" :
		      "???"),
		     (wm->ikev2 == YN_YES ? "ikev2" :
		      wm->ikev2 == YN_NO ? "ikev1" :
		      "???"));
	}

	config->ike_version = wm->ike_version;
	PASSERT(c->logger, wm->ike_version < elemsof(ike_info));
	PASSERT(c->logger, ike_info[wm->ike_version] != NULL);
	config->ike_info = ike_info[wm->ike_version];
	PASSERT(c->logger, config->ike_info->version > 0);

#if 0
	PASSERT(c->logger,
		is_opportunistic_wm(wm) == ((wm->policy & POLICY_OPPORTUNISTIC) != LEMPTY));
	PASSERT(c->logger, is_group_wm(wm) == wm->is_connection_group);
#endif

	if (is_opportunistic_wm(wm) && c->config->ike_version < IKEv2) {
		return diag("opportunistic connection MUST have IKEv2");
	}
	config->opportunistic = is_opportunistic_wm(wm);

#if 0
	if (is_opportunistic_wm(wm)) {
		if (wm->authby.psk) {
			return diag("PSK is not supported for opportunism");
		}
		if (!authby_has_digsig(wm->authby)) {
			return diag("only Digital Signatures are supported for opportunism");
		}
		if (!pfs) {
			return diag("PFS required for opportunism");
		}
	}
#endif

	config->intermediate = extract_yn("", "intermediate", wm->intermediate,
					  /*default*/false, wm, c->logger);
	if (config->intermediate) {
		if (wm->ike_version < IKEv2) {
			return diag("intermediate requires IKEv2");
		}
	}

	config->session_resumption = extract_yn("", "session_resumption", wm->session_resumption,
						/*default*/false, wm, c->logger);
	if (config->session_resumption) {
		if (wm->ike_version < IKEv2) {
			return diag("session resumption requires IKEv2");
		}
	}

	config->sha2_truncbug = extract_yn("", "sha2-truncbug", wm->sha2_truncbug,
					   /*default*/false, wm, c->logger);
	config->overlapip = extract_yn("", "overlapip", wm->overlapip,
				       /*default*/false, wm, c->logger);

	bool ms_dh_downgrade = extract_yn("", "ms-dh-downgrade", wm->ms_dh_downgrade,
					  /*default*/false, wm, c->logger);
	bool pfs_rekey_workaround = extract_yn("", "pfs-rekey-workaround", wm->pfs_rekey_workaround,
					       /*default*/false, wm, c->logger);
	if (ms_dh_downgrade && pfs_rekey_workaround) {
		return diag("cannot specify both ms-dh-downgrade=yes and pfs-rekey-workaround=yes");
	}
	config->ms_dh_downgrade = ms_dh_downgrade;
	config->pfs_rekey_workaround = pfs_rekey_workaround;

	config->dns_match_id = extract_yn("", "dns-match-id", wm->dns_match_id,
					  /*default*/false, wm, c->logger);
	/* IKEv2 only; IKEv1 uses xauth=pam */
	config->ikev2_pam_authorize = extract_yn("", "pam-authorize", wm->pam_authorize,
						 /*default*/false, wm, c->logger);

	if (wm->ike_version >= IKEv2) {
		if (wm->ikepad != YNA_UNSET) {
			name_buf vn, pn;
			llog(RC_LOG, c->logger, "warning: %s connection ignores ikepad=%s",
			     str_enum(&ike_version_names, wm->ike_version, &vn),
			     str_sparse(&yna_option_names, wm->ikepad, &pn));
		}
		/* default */
		config->v1_ikepad.message = true;
		config->v1_ikepad.modecfg = false;
	} else {
		config->v1_ikepad.modecfg = (wm->ikepad == YNA_YES);
		config->v1_ikepad.message = (wm->ikepad != YNA_NO);
	}

	config->require_id_on_certificate = extract_yn("", "require-id-on-certificate", wm->require_id_on_certificate,
						       /*default*/true/*YES-TRUE*/,wm, c->logger);

	if (wm->aggressive == YN_YES && wm->ike_version >= IKEv2) {
		return diag("cannot specify aggressive mode with IKEv2");
	}
	if (wm->aggressive == YN_YES && wm->ike == NULL) {
		return diag("cannot specify aggressive mode without ike= to set algorithm");
	}
	config->aggressive = extract_yn("", "aggressive", wm->aggressive,
					/*default*/false, wm, c->logger);

	config->decap_dscp = extract_yn("", "decap-dscp", wm->decap_dscp,
					/*default*/false, wm, c->logger);

	config->encap_dscp = extract_yn("", "encap-dscp", wm->encap_dscp,
					/*default*/true, wm, c->logger);

	config->nopmtudisc = extract_yn("", "nopmtudisc", wm->nopmtudisc,
					/*default*/false, wm, c->logger);

	bool mobike = extract_yn("", "mobike", wm->mobike,
				 /*default*/false, wm, c->logger);
	config->mobike = mobike;
	if (mobike) {
		if (wm->ike_version < IKEv2) {
			return diag("MOBIKE requires IKEv2");
		}
		if (encap_mode != ENCAP_MODE_TUNNEL) {
			return diag("MOBIKE requires tunnel mode");
		}
		if (kernel_ops->migrate_ipsec_sa_is_enabled == NULL) {
			return diag("MOBIKE is not supported by %s kernel interface",
				    kernel_ops->interface_name);
		}
		/* probe the interface */
		err_t err = kernel_ops->migrate_ipsec_sa_is_enabled(c->logger);
		if (err != NULL) {
			return diag("MOBIKE support is not enabled for %s kernel interface: %s",
				    kernel_ops->interface_name, err);
		}
	}

	/* this warns when never_negotiate() */
	bool iptfs = extract_yn("", "iptfs", wm->iptfs,
				/*default*/false, wm, c->logger);
	if (iptfs) {
		/* lots of incompatibility */
		if (wm->ike_version < IKEv2) {
			return diag("IPTFS requires IKEv2");
		}
		if (encap_mode != ENCAP_MODE_TUNNEL) {
			name_buf sb;
			return diag("type=%s must be transport",
				    str_sparse(&type_option_names, wm->type, &sb));
		}
		if (wm->tfc > 0) {
			return diag("IPTFS is not compatible with tfc=%ju", wm->tfc);
		}
		if (compress) {
			return diag("IPTFS is not compatible with compress=yes");
		}
		if (encap_mode == ENCAP_MODE_TRANSPORT) {
			return diag("IPTFS is not compatible with type=transport");
		}
		if (encap_proto != ENCAP_PROTO_ESP) {
			name_buf sb;
			return diag("IPTFS is not compatible with phase2=%s",
				    str_enum(&encap_proto_story, wm->phase2, &sb));
		}

		err_t err = kernel_ops->iptfs_ipsec_sa_is_enabled(c->logger);
		if (err != NULL) {
			return diag("IPTFS is not supported by the kernel: %s", err);
		}

		deltatime_t uint32_max = deltatime_from_microseconds(UINT32_MAX);

		config->child_sa.iptfs.enabled = true;
		config->child_sa.iptfs.packet_size = wm->iptfs_packet_size;
		config->child_sa.iptfs.max_queue_size = wm->iptfs_max_queue_size;

		if (deltatime_cmp(wm->iptfs_drop_time, >=, uint32_max)) {
			deltatime_buf tb;
			return diag("iptfs-drop-time cannnot larger than %s",
				    str_deltatime(uint32_max, &tb));
		}
		config->child_sa.iptfs.drop_time = wm->iptfs_drop_time;

			if (deltatime_cmp(wm->iptfs_init_delay, >=, uint32_max)) {
			deltatime_buf tb;
			return diag("iptfs-init-delay cannnot larger than %s",
				    str_deltatime(uint32_max, &tb));
		}
		config->child_sa.iptfs.init_delay = wm->iptfs_init_delay;

		if (wm->iptfs_reorder_window > 65535) {
			return diag("iptfs reorder window cannot be larger than 65535");
		}
		config->child_sa.iptfs.reorder_window = wm->iptfs_reorder_window;
	}

	/*
	 * Extract iptfs parameters regardless; so that the default is
	 * consistent and toggling iptfs= doesn't seem to change the
	 * field.  Could warn about this but meh.
	 */
	config->child_sa.iptfs.fragmentation =
		extract_yn_p("", "iptfs-fragmentation", wm->iptfs_fragmentation,
			     /*default*/true, wm, c->logger,
			     "", "iptfs", wm->iptfs);

	/*
	 * RFC 5685 - IKEv2 Redirect mechanism.
	 */
	config->redirect.to = clone_str(wm->redirect_to, "connection redirect_to");
	config->redirect.accept_to = clone_str(wm->accept_redirect_to, "connection accept_redirect_to");
	if (wm->ike_version == IKEv1) {
		if (wm->send_redirect != YNA_UNSET) {
			llog(RC_LOG, c->logger,
			     "warning: IKEv1 connection ignores send-redirect=");
		}
	} else {
		switch (wm->send_redirect) {
		case YNA_YES:
			if (wm->redirect_to == NULL) {
				llog(RC_LOG, c->logger,
				     "warning: send-redirect=yes ignored, redirect-to= was not specified");
			}
			/* set it anyway!?!  the code checking it
			 * issues a second warning */
			config->redirect.send_always = true;
			break;

		case YNA_NO:
			if (wm->redirect_to != NULL) {
				llog(RC_LOG, c->logger,
				     "warning: send-redirect=no, redirect-to= is ignored");
			}
			config->redirect.send_never = true;
			break;

		case YNA_UNSET:
		case YNA_AUTO:
			break;
		}
	}

	if (wm->ike_version == IKEv1) {
		if (wm->accept_redirect != YN_UNSET) {
			llog(RC_LOG, c->logger,
			     "warning: IKEv1 connection ignores accept-redirect=");
		}
	} else {
		config->redirect.accept =
			extract_yn("", "acceept-redirect", wm->accept_redirect,
				   /*default*/false, wm, c->logger);
	}

	/* fragmentation */

	/*
	 * some options are set as part of our default, but
	 * some make no sense for shunts, so remove those again
	 */
	if (never_negotiate_wm(wm)) {
		if (wm->fragmentation != YNF_UNSET) {
			name_buf fb;
			llog(RC_LOG, c->logger,
			     "warning: never-negotiate connection ignores fragmentation=%s",
			     str_sparse(&ynf_option_names, wm->fragmentation, &fb));
		}
	} else if (wm->ike_version >= IKEv2 && wm->fragmentation == YNF_FORCE) {
		name_buf fb;
		llog(RC_LOG, c->logger,
		     "warning: IKEv1 only fragmentation=%s ignored; using fragmentation=yes",
		     str_sparse(&ynf_option_names, wm->fragmentation, &fb));
		config->ike_frag.allow = true;
	} else {
		switch (wm->fragmentation) {
		case YNF_UNSET: /*default*/
		case YNF_YES:
			config->ike_frag.allow = true;
			break;
		case YNF_NO:
			break;
		case YNF_FORCE:
			config->ike_frag.allow = true;
			config->ike_frag.v1_force = true;
		}
	}

	/* RFC 8229 TCP encap*/

	enum tcp_options iketcp;
	if (never_negotiate_wm(wm)) {
		if (wm->enable_tcp != 0) {
			sparse_buf eb;
			llog(RC_LOG, c->logger,
			     "warning: enable-tcp=%s ignored for type=passthrough connection",
			     str_sparse(&tcp_option_names, wm->enable_tcp, &eb));
		}
		/* cleanup inherited default; XXX: ? */
		iketcp = IKE_TCP_NO;
	} else if (c->config->ike_version < IKEv2) {
		if (wm->enable_tcp != 0 &&
		    wm->enable_tcp != IKE_TCP_NO) {
			return diag("enable-tcp= requires IKEv2");
		}
		iketcp = IKE_TCP_NO;
	} else if (wm->enable_tcp == 0) {
		iketcp = IKE_TCP_NO; /* default */
	} else {
		iketcp = wm->enable_tcp;
	}
	config->end[LEFT_END].host.iketcp = config->end[RIGHT_END].host.iketcp = iketcp;

	switch (iketcp) {
	case IKE_TCP_NO:
		if (wm->tcp_remoteport != 0) {
			llog(RC_LOG, c->logger,
			     "warning: tcp-remoteport=%ju ignored for non-TCP connections",
			     wm->tcp_remoteport);
		}
		/* keep tests happy, value ignored */
		config->remote_tcpport = ip_hport(NAT_IKE_UDP_PORT);
		break;
	case IKE_TCP_ONLY:
	case IKE_TCP_FALLBACK:
		if (wm->tcp_remoteport == 500) {
			return diag("tcp-remoteport cannot be 500");
		}
		if (wm->tcp_remoteport > 65535/*magic?*/) {
			return diag("tcp-remoteport=%ju is too big", wm->tcp_remoteport);
		}
		config->remote_tcpport =
			ip_hport(wm->tcp_remoteport == 0 ? NAT_IKE_UDP_PORT:
				 wm->tcp_remoteport);
		break;
	default:
		/* must  have been set */
		bad_sparse(c->logger, &tcp_option_names, iketcp);
	}


	/* authentication (proof of identity) */

	if (never_negotiate_wm(wm)) {
		dbg("ignore sighash, never negotiate");
	} else if (c->config->ike_version == IKEv1) {
		dbg("ignore sighash, IKEv1");
	} else {
		config->sighash_policy = wm->sighash_policy;
	}

	/* some port stuff */

	if (wm->end[RIGHT_END].protoport.has_port_wildcard && wm->end[LEFT_END].protoport.has_port_wildcard) {
		return diag("cannot have protoports with wildcard (%%any) ports on both sides");
	}

	/*
	 * When the other side is wildcard: we must check if other
	 * conditions met.
	 *
	 * MAKE this more sane in the face of unresolved IP
	 * addresses.
	 */
	if (wm->end[LEFT_END].host_type != KH_IPHOSTNAME && !address_is_specified(wm->end[LEFT_END].host_addr) &&
	    wm->end[RIGHT_END].host_type != KH_IPHOSTNAME && !address_is_specified(wm->end[RIGHT_END].host_addr)) {
		return diag("must specify host IP address for our side");
	}

	/* duplicate any alias, adding spaces to the beginning and end */
	config->connalias = clone_str(wm->connalias, "connection alias");

	config->dnshostname = clone_str(wm->dnshostname, "connection dnshostname");

	/*
	 * narrowing=?
	 *
	 * In addition to explicit narrowing=yes, seeing any sort of
	 * port wildcard (tcp/%any) implies narrowing.  This is
	 * largely IKEv1 and L2TP (it's the only test) but nothing
	 * implies that they can't.
	 */

	if (wm->narrowing == YN_NO && wm->ike_version < IKEv2) {
		return diag("narrowing=yes requires IKEv2");
	}
	if (wm->narrowing == YN_NO) {
		FOR_EACH_THING(end, &wm->end[LEFT_END], &wm->end[RIGHT_END]) {
			if (end->addresspool != NULL) {
				return diag("narrowing=no conflicts with %saddresspool=%s",
					    end->leftright,
					    end->addresspool);
			}
		}
	}
	bool narrowing =
		extract_yn("", "narrowing", wm->narrowing,
			   (wm->ike_version == IKEv2 && (wm->end[LEFT_END].addresspool != NULL ||
							 wm->end[RIGHT_END].addresspool != NULL)),
			   wm, c->logger);
#if 0
	/*
	 * Not yet: tcp/%any means narrow past the selector and down
	 * to a single port; while narrwing means narrow down to the
	 * selector.
	 */
	FOR_EACH_THING(end, &wm->end[LEFT_END], &wm->end[RIGHT_END]) {
		narrowing |= (end->protoport.is_set &&
			      end->protoport.has_port_wildcard);
	}
#endif
	config->narrowing = narrowing;

	config->rekey = extract_yn("", "rekey", wm->rekey,
				   /*default*/true, wm, c->logger);
	config->reauth = extract_yn("", "reauth", wm->reauth,
				    /*default*/false, wm, c->logger);

	switch (wm->autostart) {
	case AUTOSTART_UP:
	case AUTOSTART_START:
	{
		name_buf nb;
		ldbg(c->logger, "autostart=%s implies +UP",
		     str_sparse(&autostart_names, wm->autostart, &nb));
		add_policy(c, policy.up);
		break;
	}
	case AUTOSTART_ROUTE:
	case AUTOSTART_ONDEMAND:
	{
		name_buf nb;
		ldbg(c->logger, "autostart=%s implies +ROUTE",
		     str_sparse(&autostart_names, wm->autostart, &nb));
		add_policy(c, policy.route);
		break;
	}
	case AUTOSTART_KEEP:
	{
		name_buf nb;
		ldbg(c->logger, "autostart=%s implies +KEEP",
		     str_sparse(&autostart_names, wm->autostart, &nb));
		add_policy(c, policy.keep);
		break;
	}
	case AUTOSTART_IGNORE:
	case AUTOSTART_ADD:
	case AUTOSTART_UNSET:
		break;
	}

	/*
	 * Extract configurable shunts, set hardwired shunts.
	 */

	d = extract_shunt(config, wm, SHUNT_KIND_NEVER_NEGOTIATE,
			  /*unset*/SHUNT_UNSET);
	if (d != NULL) {
		return d;
	}

	d = extract_shunt(config, wm, SHUNT_KIND_NEGOTIATION,
			  /*unset*/SHUNT_HOLD);
	if (d != NULL) {
		return d;
	}

	if (is_fips_mode() && config->negotiation_shunt == SHUNT_PASS) {
		enum_buf sb;
		llog(RC_LOG, c->logger,
		     "FIPS: ignored negotiationshunt=%s - packets MUST be blocked in FIPS mode",
		     str_enum_short(&shunt_policy_names, config->negotiation_shunt, &sb));
		config->negotiation_shunt = SHUNT_HOLD;
	}

	d = extract_shunt(config, wm, SHUNT_KIND_FAILURE,
			  /*unset*/SHUNT_NONE);
	if (d != NULL) {
		return d;
	}

	/* make kernel code easier */
	config->shunt[SHUNT_KIND_BLOCK] = SHUNT_DROP;
	config->shunt[SHUNT_KIND_ONDEMAND] = SHUNT_TRAP;
	config->shunt[SHUNT_KIND_IPSEC] = SHUNT_IPSEC;

	if (is_fips_mode() && config->failure_shunt != SHUNT_NONE) {
		enum_buf eb;
		llog(RC_LOG, c->logger,
		     "FIPS: ignored failureshunt=%s - packets MUST be blocked in FIPS mode",
		     str_enum_short(&shunt_policy_names, config->failure_shunt, &eb));
		config->failure_shunt = SHUNT_NONE;
	}

	for (enum shunt_kind sk = SHUNT_KIND_FLOOR; sk < SHUNT_KIND_ROOF; sk++) {
		PASSERT(c->logger, sk < elemsof(config->shunt));
		PASSERT(c->logger, shunt_ok(sk, config->shunt[sk]));
	}

	/*
	 * Should ESN be disabled?
	 *
	 * Order things so that a lack of kernel support is the last
	 * resort (fixing the kernel will break less tests).
	 */

	if (wm->replay_window > kernel_ops->max_replay_window) {
		return diag("replay-window=%ju exceeds %s kernel interface limit of %ju",
			    wm->replay_window,
			    kernel_ops->interface_name,
			    kernel_ops->max_replay_window);
	} else if (!never_negotiate_wm(wm)) {
		config->child_sa.replay_window = wm->replay_window;
	}

	if (never_negotiate_wm(wm)) {
		if (wm->esn != YNE_UNSET) {
			name_buf nb;
			llog(RC_LOG, c->logger,
			     "warning: ignoring esn=%s as connection is never-negotiate",
			     str_sparse(&yne_option_names, wm->esn, &nb));
		}
	} else if (wm->replay_window == 0) {
		/*
		 * RFC 4303 states:
		 *
		 * Note: If a receiver chooses to not enable
		 * anti-replay for an SA, then the receiver SHOULD NOT
		 * negotiate ESN in an SA management protocol.  Use of
		 * ESN creates a need for the receiver to manage the
		 * anti-replay window (in order to determine the
		 * correct value for the high-order bits of the ESN,
		 * which are employed in the ICV computation), which
		 * is generally contrary to the notion of disabling
		 * anti-replay for an SA.
		 */
		if (wm->esn != YNE_UNSET && wm->esn != YNE_NO) {
			llog(RC_LOG, c->logger,
			     "warning: forcing esn=no as replay-window=0");
		} else {
			dbg("ESN: disabled as replay-window=0"); /* XXX: log? */
		}
		config->esn.no = true;
	} else if (!kernel_ops->esn_supported) {
		/*
		 * Only warn when there's an explicit esn=yes.
		 */
		if (wm->esn == YNE_YES ||
		    wm->esn == YNE_EITHER) {
			name_buf nb;
			llog(RC_LOG, c->logger,
			     "warning: %s kernel interface does not support ESN, ignoring esn=%s",
			     kernel_ops->interface_name,
			     str_sparse(&yne_option_names, wm->esn, &nb));
		}
		config->esn.no = true;
#ifdef USE_IKEv1
	} else if (wm->ike_version == IKEv1) {
		/*
		 * Ignore ESN when IKEv1.
		 *
		 * XXX: except it isn't; it still gets decoded and
		 * stuffed into the config.  It just isn't acted on.
		 */
		dbg("ESN: ignored as not implemented with IKEv1");
#if 0
		if (wm->esn != YNE_UNSET) {
			name_buf nb;
			llog(RC_LOG, c->logger,
			     "warning: ignoring esn=%s as not implemented with IKEv1",
			     str_sparse(yne_option_names, wm->esn, &nb));
		}
#endif
		switch (wm->esn) {
		case YNE_UNSET:
		case YNE_EITHER:
			config->esn.no = true;
			config->esn.yes = true;
			break;
		case YNE_NO:
			config->esn.no = true;
			break;
		case YNE_YES:
			config->esn.yes = true;
			break;
		}
#endif
	} else {
		switch (wm->esn) {
		case YNE_UNSET:
		case YNE_EITHER:
			config->esn.no = true;
			config->esn.yes = true;
			break;
		case YNE_NO:
			config->esn.no = true;
			break;
		case YNE_YES:
			config->esn.yes = true;
			break;
		}
	}

	if (wm->ike_version == IKEv1) {
		if (wm->ppk != NPPI_UNSET) {
			sparse_buf sb;
			llog(RC_LOG, c->logger,
			     "warning: ignoring ppk=%s as IKEv1",
			     str_sparse(&nppi_option_names, wm->ppk, &sb));
		}
	} else {
		switch (wm->ppk) {
		case NPPI_UNSET:
		case NPPI_NEVER:
			break;
		case NPPI_PERMIT:
		case NPPI_PROPOSE:
			config->ppk.allow = true;
			break;
		case NPPI_INSIST:
			config->ppk.allow = true;
			config->ppk.insist = true;
			break;
		}
	}

	connection_buf cb;
	policy_buf pb;
	dbg("added new %s connection "PRI_CONNECTION" with policy %s",
	    c->config->ike_info->version_name,
	    pri_connection(c, &cb), str_connection_policies(c, &pb));

	/* IKE cipher suites */

	if (never_negotiate_wm(wm)) {
		if (wm->ike != NULL) {
			llog(RC_LOG, c->logger,
			     "ignored ike= option for type=passthrough connection");
		}
	} else {
		const struct proposal_policy proposal_policy = {
			/* logic needs to match pick_initiator() */
			.version = c->config->ike_version,
			.alg_is_ok = ike_alg_is_ike,
			.pfs = pfs,
			.check_pfs_vs_dh = false,
			.logger_rc_flags = ALL_STREAMS,
			.logger = c->logger, /* on-stack */
			/* let defaults stumble on regardless */
			.ignore_parser_errors = (wm->ike == NULL),
		};

		struct proposal_parser *parser = ike_proposal_parser(&proposal_policy);
		config->ike_proposals.p = proposals_from_str(parser, wm->ike);

		if (c->config->ike_proposals.p == NULL) {
			pexpect(parser->diag != NULL); /* something */
			diag_t d = parser->diag; parser->diag = NULL;
			free_proposal_parser(&parser);
			return d;
		}
		free_proposal_parser(&parser);

		LDBGP_JAMBUF(DBG_BASE, c->logger, buf) {
			jam_string(buf, "ike (phase1) algorithm values: ");
			jam_proposals(buf, c->config->ike_proposals.p);
		}

		if (c->config->ike_version == IKEv2) {
			connection_buf cb;
			dbg("constructing local IKE proposals for "PRI_CONNECTION,
			    pri_connection(c, &cb));
			config->v2_ike_proposals =
				ikev2_proposals_from_proposals(IKEv2_SEC_PROTO_IKE,
							       config->ike_proposals.p,
							       c->logger);
			llog_v2_proposals(LOG_STREAM/*not-whack*/, c->logger,
					  config->v2_ike_proposals,
					  "IKE SA proposals (connection add)");
		}
	}

	/* ESP or AH cipher suites (but not both) */

	if (never_negotiate_wm(wm)) {
		if (wm->esp != NULL) {
			llog(RC_LOG, c->logger,
			     "ignored esp= option for type=passthrough connection");
		}
	} else  {
		PEXPECT(c->logger, encap_proto != ENCAP_PROTO_UNSET);

		const struct proposal_policy proposal_policy = {
			/*
			 * logic needs to match pick_initiator()
			 *
			 * XXX: Once pluto is changed to IKEv1 XOR
			 * IKEv2 it should be possible to move this
			 * magic into pluto proper and instead pass a
			 * simple boolean.
			 */
			.version = c->config->ike_version,
			.alg_is_ok = kernel_alg_is_ok,
			.pfs = pfs,
			.check_pfs_vs_dh = true,
			.logger_rc_flags = ALL_STREAMS,
			.logger = c->logger, /* on-stack */
			/* let defaults stumble on regardless */
			.ignore_parser_errors = (wm->esp == NULL),
		};

		/*
		 * We checked above that exactly one of POLICY_ENCRYPT
		 * and POLICY_AUTHENTICATE is on.  The only difference
		 * in processing is which function is called (and
		 * those functions are almost identical).
		 */
		struct proposal_parser *(*fn)(const struct proposal_policy *policy) =
			(encap_proto == ENCAP_PROTO_ESP) ? esp_proposal_parser :
			(encap_proto == ENCAP_PROTO_AH) ? ah_proposal_parser :
			NULL;
		passert(fn != NULL);
		struct proposal_parser *parser = fn(&proposal_policy);
		config->child_sa.proposals.p = proposals_from_str(parser, wm->esp);
		if (c->config->child_sa.proposals.p == NULL) {
			pexpect(parser->diag != NULL);
			diag_t d = parser->diag; parser->diag = NULL;
			free_proposal_parser(&parser);
			return d;
		}
		free_proposal_parser(&parser);

		LDBGP_JAMBUF(DBG_BASE, c->logger, buf) {
			jam_string(buf, "ESP/AH string values: ");
			jam_proposals(buf, c->config->child_sa.proposals.p);
		};

		/*
		 * For IKEv2, also generate the Child proposal that
		 * will be used during IKE AUTH.
		 *
		 * Since a Child SA established during an IKE_AUTH
		 * exchange does not propose DH (keying material is
		 * taken from the IKE SA's SKEYSEED), DH is stripped
		 * from the proposals.
		 *
		 * Since only things that affect this proposal suite
		 * are the connection's .policy bits and the contents
		 * .child_proposals, and modifying those triggers the
		 * creation of a new connection (true?), the
		 * connection can be cached.
		 */
		if (c->config->ike_version == IKEv2) {
			config->child_sa.v2_ike_auth_proposals =
				get_v2_IKE_AUTH_new_child_proposals(c);
			llog_v2_proposals(LOG_STREAM/*not-whack*/, c->logger,
					  config->child_sa.v2_ike_auth_proposals,
					  "Child SA proposals (connection add)");
		}
	}

	config->encapsulation = extract_yna("", "encapsulation", wm->encapsulation,
					    YNA_AUTO, YNA_NO, wm, c->logger);

	config->vti.shared = extract_yn("", "vti-shared", wm->vti_shared,
					/*default*/false, wm, c->logger);
	config->vti.routing = extract_yn("", "vti-routing", wm->vti_routing,
					 /*default*/false, wm, c->logger);
	if (wm->vti_interface != NULL && strlen(wm->vti_interface) >= IFNAMSIZ) {
		llog(RC_LOG, c->logger,
		     "warning: length of vti-interface '%s' exceeds IFNAMSIZ (%u)",
		     wm->vti_interface, (unsigned) IFNAMSIZ);
	}
	config->vti.interface = extract_str("",  "vti-interface", wm->vti_interface,
					    wm, c->logger);

	if (never_negotiate_wm(wm)) {
		if (wm->nic_offload != NIC_OFFLOAD_UNSET) {
			name_buf nb;
			llog(RC_LOG, c->logger, "nic-offload=%s ignored for never-negotiate connection",
			     str_sparse(&nic_offload_option_names, wm->nic_offload, &nb));
		}
		/* keep <<ipsec connectionstatus>> simple */
		config->nic_offload = NIC_OFFLOAD_NO;
	} else {
		switch (wm->nic_offload) {
		case NIC_OFFLOAD_UNSET:
		case NIC_OFFLOAD_NO:
			config->nic_offload = NIC_OFFLOAD_NO; /* default */
			break;
		case NIC_OFFLOAD_PACKET:
		case NIC_OFFLOAD_CRYPTO:
			if (kernel_ops->detect_nic_offload == NULL) {
				name_buf nb;
				return diag("no kernel support for nic-offload[=%s]",
					    str_sparse(&nic_offload_option_names, wm->nic_offload, &nb));
			}
			config->nic_offload = wm->nic_offload;
		}

		if (wm->nic_offload == NIC_OFFLOAD_PACKET) {
			if (encap_mode != ENCAP_MODE_TRANSPORT) {
				return diag("nic-offload=packet restricted to type=transport");
			}
			if (encap_proto != ENCAP_PROTO_ESP) {
				return diag("nic-offload=packet restricted to phase2=esp");
			}
			if (compress) {
				return diag("nic-offload=packet restricted to compression=no");
			}
			if (config->encapsulation == YNA_YES) {
				return diag("nic-offload=packet cannot specify encapsulation=yes");
			}

			/* byte/packet counters for packet offload on linux requires >= 6.7 */
			if (wm->sa_ipsec_max_bytes != 0 || wm->sa_ipsec_max_packets != 0) {
				if (!kernel_ge(KINFO_LINUX, 6, 7, 0)) {
					return diag("Linux kernel 6.7+ required for byte/packet counters and hardware offload");
				}
				ldbg(c->logger, "kernel >= 6.7 is GTG for h/w offload");
			}

			/* limited replay windows supported for packet offload */
			switch (wm->replay_window) {
			case 32:
			case 64:
			case 128:
			case 256:
				ldbg(c->logger, "packet offload replay-window compatible with all known hardware and Linux kernels");
				break;
			default:
				return diag("current packet offload hardware only supports replay-window of 32, 64, 128 or 256");
			}
			/* check if we need checks for tfcpad= , encap-dscp, nopmtudisc, ikepad, encapsulation, etc? */
		}

	}

	if (never_negotiate_wm(wm)) {
		dbg("skipping over misc settings as NEVER_NEGOTIATE");
	} else {

		deltatime_t rekeymargin;
		if (wm->rekeymargin.is_set) {
			if (deltasecs(wm->rekeymargin) > (INT_MAX / (100 + (intmax_t)wm->sa_rekeyfuzz_percent))) {
				return diag("rekeymargin=%jd is so large it causes overflow",
					    deltasecs(wm->rekeymargin));
			}
			rekeymargin = wm->rekeymargin;
		} else {
			rekeymargin = deltatime(SA_REPLACEMENT_MARGIN_DEFAULT);
		};
		config->sa_rekey_margin = rekeymargin;

		d = extract_lifetime(&config->sa_ike_max_lifetime,
				     "ikelifetime", wm->ikelifetime,
				     IKE_SA_LIFETIME_DEFAULT,
				     IKE_SA_LIFETIME_MAXIMUM,
				     FIPS_IKE_SA_LIFETIME_MAXIMUM,
				     rekeymargin,
				     c->logger, wm);
		if (d != NULL) {
			return d;
		}
		d = extract_lifetime(&config->sa_ipsec_max_lifetime,
				     "ipsec-lifetime", wm->ipsec_lifetime,
				     IPSEC_SA_LIFETIME_DEFAULT,
				     IPSEC_SA_LIFETIME_MAXIMUM,
				     FIPS_IPSEC_SA_LIFETIME_MAXIMUM,
				     rekeymargin,
				     c->logger, wm);
		if (d != NULL) {
			return d;
		}

		config->sa_rekey_fuzz = wm->sa_rekeyfuzz_percent;

		config->retransmit_timeout =
			(wm->retransmit_timeout.is_set ? wm->retransmit_timeout :
			 deltatime_from_milliseconds(RETRANSMIT_TIMEOUT_DEFAULT * 1000));
		config->retransmit_interval =
			(wm->retransmit_interval.is_set ? wm->retransmit_interval :
			 deltatime_from_milliseconds(RETRANSMIT_INTERVAL_DEFAULT_MS));

		/*
		 * A 1500 mtu packet requires 1500/16 ~= 90 crypto
		 * operations.  Always use NIST maximums for
		 * bytes/packets.
		 *
		 * https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
		 * "The total number of invocations of the
		 * authenticated encryption function shall not exceed
		 * 2^32 , including all IV lengths and all instances
		 * of the authenticated encryption function with the
		 * given key."
		 *
		 * Note "invocations" is not "bytes" or "packets", but
		 * the safest assumption is the most wasteful
		 * invocations which is 1 byte per packet.
		 *
		 * XXX: this code isn't yet doing this.
		 */
		config->sa_ipsec_max_bytes = wm->sa_ipsec_max_bytes;
		if (wm->sa_ipsec_max_bytes > IPSEC_SA_MAX_OPERATIONS) {
			llog(RC_LOG, c->logger,
			     "IPsec max bytes limited to the maximum allowed %s",
			     IPSEC_SA_MAX_OPERATIONS_STRING);
			config->sa_ipsec_max_bytes = IPSEC_SA_MAX_OPERATIONS;
		}
		config->sa_ipsec_max_packets = wm->sa_ipsec_max_packets;
		if (wm->sa_ipsec_max_packets > IPSEC_SA_MAX_OPERATIONS) {
			llog(RC_LOG, c->logger,
			     "IPsec max packets limited to the maximum allowed %s",
			     IPSEC_SA_MAX_OPERATIONS_STRING);
			config->sa_ipsec_max_packets = IPSEC_SA_MAX_OPERATIONS;
		}

		if (deltatime_cmp(config->sa_rekey_margin, >=, config->sa_ipsec_max_lifetime)) {
			deltatime_t new_rkm = deltatime_scale(config->sa_ipsec_max_lifetime, 1, 2);

			llog(RC_LOG, c->logger,
			     "rekeymargin (%jds) >= salifetime (%jds); reducing rekeymargin to %jds seconds",
			     deltasecs(config->sa_rekey_margin),
			     deltasecs(config->sa_ipsec_max_lifetime),
			     deltasecs(new_rkm));

			config->sa_rekey_margin = new_rkm;
		}

		const enum timescale dpd_timescale = TIMESCALE_SECONDS;
		switch (wm->ike_version) {
		case IKEv1:
			/* IKEv1's RFC 3706 DPD */
			if (wm->dpddelay != NULL &&
			    wm->dpdtimeout != NULL) {
				diag_t d;
				d = ttodeltatime(wm->dpddelay,
						 &config->dpd.delay,
						 dpd_timescale);
				if (d != NULL) {
					return diag_diag(&d, "dpddelay=%s invalid, ",
							 wm->dpddelay);
				}
				d = ttodeltatime(wm->dpdtimeout,
						 &config->dpd.timeout,
						 dpd_timescale);
				if (d != NULL) {
					return diag_diag(&d, "dpdtimeout=%s invalid, ",
							 wm->dpdtimeout);
				}
				deltatime_buf db, tb;
				ldbg(c->logger, "IKEv1 dpd.timeout=%s dpd.delay=%s",
				     str_deltatime(config->dpd.timeout, &db),
				     str_deltatime(config->dpd.delay, &tb));
			} else if (wm->dpddelay != NULL  ||
				   wm->dpdtimeout != NULL) {
				llog(RC_LOG, c->logger,
				     "warning: IKEv1 dpd settings are ignored unless both dpdtimeout= and dpddelay= are set");
			}
			break;
		case IKEv2:
			if (wm->dpddelay != NULL) {
				diag_t d;
				d = ttodeltatime(wm->dpddelay,
						 &config->dpd.delay,
						 dpd_timescale);
				if (d != NULL) {
					return diag_diag(&d, "dpddelay=%s invalid, ",
							 wm->dpddelay);
				}
			}
			if (wm->dpdtimeout != NULL) {
				/* actual values don't matter */
				llog(RC_LOG, c->logger,
				     "warning: IKEv2 ignores dpdtimeout==; use dpddelay= and retransmit-timeout=");
			}
			break;
		}

		/* Cisco interop: remote peer type */
		config->remote_peer_cisco = wm->remote_peer_type == REMOTE_PEER_CISCO;

		config->child_sa.metric = wm->metric;
		config->child_sa.mtu = wm->mtu;
		config->nat_keepalive = wm->nat_keepalive;
		if (wm->nat_ikev1_method == 0) {
			config->ikev1_natt = NATT_BOTH;
		} else {
			config->ikev1_natt = wm->nat_ikev1_method;
		}
		config->send_initial_contact = wm->initial_contact;
		config->send_vid_cisco_unity = wm->cisco_unity;
		config->send_vid_fake_strongswan = wm->fake_strongswan;
		config->send_vendorid = wm->send_vendorid;
		config->send_ca = wm->send_ca;
		config->xauthby = wm->xauthby;
		config->xauthfail = wm->xauthfail;

		/* RFC 8784 and draft-ietf-ipsecme-ikev2-qr-alt-04 */
		config->ppk_ids = clone_str(wm->ppk_ids, "connection ppk_ids");
		if (config->ppk_ids != NULL) {
			config->ppk_ids_shunks = shunks(shunk1(config->ppk_ids),
							", ",
							EAT_EMPTY_SHUNKS,
							HERE); /* process into shunks once */
		}
	}

	/*
	 * modecfg/cp
	 */

	config->modecfg.pull = extract_yn("", "modecfgpull", wm->modecfgpull,
					  /*default*/false, wm, c->logger);

	if (can_extract_str("", "modecfgdns", wm->modecfgdns, wm, c->logger)) {
		diag_t d = ttoaddresses_num(shunk1(wm->modecfgdns), ", ",
					    /* IKEv1 doesn't do IPv6 */
					    (wm->ike_version == IKEv1 ? &ipv4_info : NULL),
					    &config->modecfg.dns);
		if (d != NULL) {
			return diag_diag(&d, "modecfgdns=%s invalid: ", wm->modecfgdns);
		}
	}

	if (can_extract_str("", "modecfgdomains", wm->modecfgdomains, wm, c->logger)) {
		config->modecfg.domains = clone_shunk_tokens(shunk1(wm->modecfgdomains),
							     ", ", HERE);
		if (wm->ike_version == IKEv1 &&
		    config->modecfg.domains != NULL &&
		    config->modecfg.domains[1].ptr != NULL) {
			llog(RC_LOG, c->logger,
			     "IKEv1 only uses the first domain in modecfgdomain=%s",
			     wm->modecfgdomains);
			config->modecfg.domains[1] = null_shunk;
		}
	}

	config->modecfg.banner = extract_str("", "modecfgbanner", wm->modecfgbanner,
					     wm, c->logger);

	/*
	 * Marks.
	 *
	 * parse mark and mask values form the mark/mask string
	 * acceptable string formats are
	 * ( -1 | <nat> | <hex> ) [ / ( <nat> | <hex> ) ]
	 * examples:
	 *   10
	 *   10/0xffffffff
	 *   0xA/0xFFFFFFFF
	 *
	 * defaults:
	 *  if mark is provided and mask is not mask will default to 0xFFFFFFFF
	 *  if nothing is provided mark and mask are set to 0;
	 *
	 * mark-in= and mark-out= overwrite mark=
	 */

	if (can_extract_str("", "mark", wm->mark, wm, c->logger)) {
		mark_parse(wm->mark, &c->sa_marks.in, c->logger);
		mark_parse(wm->mark, &c->sa_marks.out, c->logger);
	}

	if (can_extract_str("", "mark-in", wm->mark_in, wm, c->logger)) {
		if (wm->mark != NULL) {
			llog(RC_LOG, c->logger, "warning: mark-in=%s overrides mark=%s",
			     wm->mark_in, wm->mark);
		}
		mark_parse(wm->mark_in, &c->sa_marks.in, c->logger);
	}

	if (can_extract_str("", "mark-out", wm->mark_out, wm, c->logger)) {
		if (wm->mark != NULL) {
			llog(RC_LOG, c->logger, "warning: mark-out=%s overrides mark=%s",
			     wm->mark_out, wm->mark);
		}
		mark_parse(wm->mark_out, &c->sa_marks.out, c->logger);
	}

	/*
	 * ipsec-interface
	 */

	struct ipsec_interface_config ipsec_interface = {0};
	if (can_extract_str("", "ipsec-interface", wm->ipsec_interface, wm, c->logger)) {
		diag_t d;
		d = parse_ipsec_interface(wm->ipsec_interface, &ipsec_interface, c->logger);
		if (d != NULL) {
			return d;
		}
		config->ipsec_interface = ipsec_interface;
	}

#ifdef HAVE_NM
	config->nm_configured = extract_yn("", "nm-configured", wm->nm_configured,
					   /*default*/false, wm, c->logger);
#endif

#ifdef USE_NFLOG
	c->nflog_group = wm->nflog_group;
#endif

	if (wm->priority > UINT32_MAX) {
		return diag("priority=%ju exceeds upper bound of %"PRIu32,
			    wm->priority, UINT32_MAX);
	}
	config->child_sa.priority = wm->priority;

	if (wm->tfc != 0) {
		if (encap_mode == ENCAP_MODE_TRANSPORT) {
			return diag("connection with type=transport cannot specify tfc=");
		}
		if (encap_proto == ENCAP_PROTO_AH) {
			return diag("connection with encap_proto=ah cannot specify tfc=");
		}
		if (wm->tfc > UINT32_MAX) {
			return diag("tfc=%ju exceeds upper bound of %"PRIu32,
				    wm->tfc, UINT32_MAX);
		}
		config->child_sa.tfcpad = wm->tfc;
	}

	config->send_no_esp_tfc = wm->send_no_esp_tfc;

	/*
	 * Since security labels use the same REQID for everything,
	 * pre-assign it.
	 */
	config->sa_reqid = (wm->sa_reqid != 0 ? wm->sa_reqid :
			    wm->sec_label != NULL ? gen_reqid() :
			    ipsec_interface.enabled ? ipsec_interface_reqid(ipsec_interface.id, c->logger) :
			    /*generated later*/0);
	ldbg(c->logger,
	     "c->sa_reqid="PRI_REQID" because wm->sa_reqid="PRI_REQID" and sec-label=%s",
	     pri_reqid(config->sa_reqid),
	     pri_reqid(wm->sa_reqid),
	     (wm->ike_version != IKEv2 ? "not-IKEv2" :
	      wm->sec_label != NULL ? wm->sec_label :
	      "n/a"));

	/*
	 * Set both end's sec_label to the same value.
	 */

	if (wm->sec_label != NULL) {
		ldbg(c->logger, "received sec_label '%s' from whack", wm->sec_label);
		if (wm->ike_version == IKEv1) {
			return diag("IKEv1 does not support Labeled IPsec");
		}
		/* include NUL! */
		shunk_t sec_label = shunk2(wm->sec_label, strlen(wm->sec_label)+1);
		err_t ugh = vet_seclabel(sec_label);
		if (ugh != NULL) {
			return diag("%s: policy-label=%s", ugh, wm->sec_label);
		}
		config->sec_label = clone_hunk(sec_label, "struct config sec_label");
	}

	/*
	 * Look for contradictions.
	 */

	if (wm->end[LEFT_END].addresspool != NULL &&
	    wm->end[RIGHT_END].addresspool != NULL) {
		return diag("both leftaddresspool= and rightaddresspool= defined");
	}

	if (wm->end[LEFT_END].modecfgserver == YN_YES &&
	    wm->end[RIGHT_END].modecfgserver == YN_YES) {
		diag_t d = diag("both leftmodecfgserver=yes and rightmodecfgserver=yes defined");
		if (!is_opportunistic_wm(wm)) {
			return d;
		}
		llog(RC_LOG, c->logger, "opportunistic: %s", str_diag(d));
		pfree_diag(&d);
	}

	if (wm->end[LEFT_END].modecfgclient == YN_YES &&
	    wm->end[RIGHT_END].modecfgclient == YN_YES) {
		diag_t d = diag("both leftmodecfgclient=yes and rightmodecfgclient=yes defined");
		if (!is_opportunistic_wm(wm)) {
			return d;
		}
		llog(RC_LOG, c->logger, "opportunistic: %s", str_diag(d));
		pfree_diag(&d);
	}

	if (wm->end[LEFT_END].cat == YN_YES && wm->end[RIGHT_END].cat == YN_YES) {
		diag_t d = diag("both leftcat=yes and rightcat=yes defined");
		if (!is_opportunistic_wm(wm)) {
			return d;
		}
		llog(RC_LOG, c->logger, "opportunistic: %s", str_diag(d));
		pfree_diag(&d);
	}

	if (wm->end[LEFT_END].virt != NULL && wm->end[RIGHT_END].virt != NULL) {
		return diag("both leftvirt= and rightvirt= defined");
	}

	if (is_group_wm(wm) && (wm->end[LEFT_END].virt != NULL ||
				wm->end[RIGHT_END].virt != NULL)) {
		return diag("connection groups do not support virtual subnets");
	}

	FOR_EACH_THING(this, LEFT_END, RIGHT_END) {
		int that = (this + 1) % END_ROOF;
		if (same_ca[that]) {
			config->end[that].host.ca = clone_hunk(config->end[this].host.ca,
							       "same ca");
			break;
		}
	}

	/*
	 * Connections can't be both client and server right?
	 *
	 * Unfortunately, no!
	 *
	 * OE configurations have configurations such as
	 * leftmodecfgclient=yes rightaddresspool= and
	 * leftmodeconfigclient=yes leftmodeconfigserver=yes which
	 * create a connection that is both a client and a server.
	 */

	if (config->end[LEFT_END].host.modecfg.server &&
	    config->end[RIGHT_END].host.modecfg.server) {
		diag_t d = diag("both left and right are configured as a server");
		if (!is_opportunistic_wm(wm)) {
			return d;
		}
		llog(RC_LOG, c->logger, "opportunistic: %s", str_diag(d));
		pfree_diag(&d);
	}

	if (config->end[LEFT_END].host.modecfg.client &&
	    config->end[RIGHT_END].host.modecfg.client) {
		diag_t d = diag("both left and right are configured as a client");
		if (!is_opportunistic_wm(wm)) {
			return d;
		}
		llog(RC_LOG, c->logger, "opportunistic: %s", str_diag(d));
		pfree_diag(&d);
	}

	FOR_EACH_THING(end, LEFT_END, RIGHT_END) {
		update_hosts_from_end_host_addr(c, end, host_addr[end], HERE); /* from add */
	}

	/*
	 * Cross-check the auth= vs authby= results.
	 */

	if (never_negotiate(c)) {
		if (!PEXPECT(c->logger,
			     c->local->host.config->auth == AUTH_NEVER &&
			     c->remote->host.config->auth == AUTH_NEVER)) {
			return diag("internal error");
		}
	} else {
		if (c->local->host.config->auth == AUTH_UNSET ||
		    c->remote->host.config->auth == AUTH_UNSET) {
			/*
			 * Since an unset auth is set from authby,
			 * authby= must have somehow been blanked out
			 * or left with something useless (such as
			 * never).
			 */
			return diag("no authentication (auth=, authby=) was set");
		}

		if ((c->local->host.config->auth == AUTH_PSK && c->remote->host.config->auth == AUTH_NULL) ||
		    (c->local->host.config->auth == AUTH_NULL && c->remote->host.config->auth == AUTH_PSK)) {
			enum_buf lab, rab;
			return diag("cannot mix PSK and NULL authentication (%sauth=%s and %sauth=%s)",
				    c->local->config->leftright,
				    str_enum(&keyword_auth_names, c->local->host.config->auth, &lab),
				    c->remote->config->leftright,
				    str_enum(&keyword_auth_names, c->remote->host.config->auth, &rab));
		}
	}

	/*
	 * For templates; start the instance counter.  Each time the
	 * connection is instantiated this is updated; ditto for
	 * instantiated instantiations such as is_labeled_child().
	 */
	c->instance_serial = 0;
	c->next_instance_serial = (is_template(c) ? 1 : 0);

	/* set internal fields */
	c->iface = NULL; /* initializing */

	c->redirect.attempt = 0;

	/* non configurable */
	config->ike_window = IKE_V2_OVERLAPPING_WINDOW_SIZE;

	/*
	 * We cannot have unlimited keyingtries for Opportunistic, or
	 * else we gain infinite partial IKE SA's. But also, more than
	 * one makes no sense, since it will be installing a
	 * failureshunt (not negotiationshunt) on the 2nd keyingtry,
	 * and try to re-install another negotiation or failure shunt.
	 */
	if (wm->keyingtries.set) {
		if (never_negotiate_wm(wm)) {
			llog(RC_LOG, c->logger,
			     "warning: keyingtries=%ju ignored, connection will never negotiate",
			     wm->keyingtries.value);
		} else if (is_opportunistic_wm(wm) &&
			   wm->keyingtries.value != 1) {
			llog(RC_LOG, c->logger,
			     "warning: keyingtries=%ju ignored, Opportunistic connections do not retry",
			     wm->keyingtries.value);
		} else {
			llog(RC_LOG, c->logger,
			     "warning: keyingtries=%ju ignored, UP connection will attempt to establish until marked DOWN",
			     wm->keyingtries.value);
		}
	}

	/*
	 * Extract the child configuration and save it.
	 */

	FOR_EACH_THING(end, LEFT_END, RIGHT_END) {
		d = extract_child_end_config(wm, whack_ends[end],
					     c, &config->end[end].child,
					     c->logger);
		if (d != NULL) {
			return d;
		}
	}

	/*
	 * Now cross check the configuration looking for IP version
	 * conflicts.
	 *
	 * First build a table of the IP address families that each
	 * end's child is using and then cross check it with the other
	 * end.  Either both ends use a AFI or both don't.
	 */

	struct {
		bool used;
		const char *field;
		char *value;
	} end_family[END_ROOF][IP_INDEX_ROOF] = {0};
	FOR_EACH_THING(end, LEFT_END, RIGHT_END) {
		const ip_selectors *const selectors = &c->end[end].config->child.selectors;
		const ip_ranges *const pools = &c->end[end].config->child.addresspools;
		if (selectors->len > 0) {
			FOR_EACH_ELEMENT(afi, ip_families) {
				if (selectors->ip[afi->ip_index].len > 0) {
					end_family[end][afi->ip_index].used = true;
					end_family[end][afi->ip_index].field = "subnet";
					end_family[end][afi->ip_index].value = whack_ends[end]->subnet;
				}
			}
		} else if (pools->len > 0) {
			FOR_EACH_ITEM(range, pools) {
				const struct ip_info *afi = range_type(range);
				/* only one for now */
				passert(end_family[end][afi->ip_index].used == false);
				end_family[end][afi->ip_index].used = true;
				end_family[end][afi->ip_index].field = "addresspool";
				end_family[end][afi->ip_index].value = whack_ends[end]->addresspool;
			}
		} else {
			end_family[end][host_afi->ip_index].used = true;
			end_family[end][host_afi->ip_index].field = "";
			end_family[end][host_afi->ip_index].value = whack_ends[end]->host_addr_name;
		}
	}

	/* legacy; check against clientaddrfamily */
	if (wm->child_afi != NULL) {
		/* is other ip version being used? */
		enum ip_index j = (wm->child_afi == &ipv4_info ? IPv6_INDEX :
				   IPv4_INDEX);
		FOR_EACH_THING(end, LEFT_END, RIGHT_END) {
			if (end_family[end][j].used) {
				return diag("\"childaddrfamily=%s\" conflicts with \"%s%s=%s\"",
					    wm->child_afi->ip_name,
					    config->end[end].leftright,
					    end_family[end][j].field,
					    end_family[end][j].value);
			}
		}
	}

	/* now check there's a match */
	FOR_EACH_ELEMENT(afi, ip_families) {
		enum ip_index i = afi->ip_index;

		/* both ends do; or both ends don't */
		if (end_family[LEFT_END][i].used == end_family[RIGHT_END][i].used) {
			continue;
		}
		/*
		 * Flip the AFI for RIGHT.  Presumably it being
		 * non-zero is the reason for the conflict?
		 */
		enum ip_index j = (i == IPv4_INDEX ? IPv6_INDEX : IPv4_INDEX);
		if (end_family[LEFT_END][i].used) {
			/* oops, no winner */
			pexpect(end_family[RIGHT_END][j].used);
		} else {
			swap(i, j);
			pexpect(end_family[LEFT_END][i].used);
			pexpect(end_family[RIGHT_END][j].used);
		}
		/*
		 * Both ends used child AFIs.
		 *
		 * Since no permutation was valid one end must
		 * be pure IPv4 and the other end pure IPv6
		 * say.
		 *
		 * Use the first list entry to get the AFI.
		 */
		return diag("address family of left%s=%s conflicts with right%s=%s",
			    end_family[LEFT_END][i].field,
			    end_family[LEFT_END][i].value,
			    end_family[RIGHT_END][j].field,
			    end_family[RIGHT_END][j].value);
	}

	/*
	 * Is spd.reqid necessary for all c?  CK_INSTANCE or
	 * CK_PERMANENT need one.  Does CK_TEMPLATE need one?
	 */
	c->child.reqid = child_reqid(c->config, c->logger);

	/*
	 * Fill in the child's selector proposals from the config.  It
	 * might use subnet or host or addresspool.
	 */

	VERBOSE_DBGP(DBG_BASE, c->logger, "%s() ...", __func__);
	add_proposals(c, host_afi, verbose);

	/*
	 * All done, enter it into the databases.  Since orient() may
	 * switch ends, triggering an spd rehash, insert things into
	 * the database first.
	 */
	connection_db_add(c);

	/*
	 * Force orientation (currently kind of unoriented?).
	 *
	 * If the connection orients,the SPDs and host-pair hash
	 * tables are updated.
	 *
	 * This function holds the just allocated reference.
	 */
	PASSERT(c->logger, !oriented(c));
	orient(c, c->logger);

	return NULL;
}

diag_t add_connection(const struct whack_message *wm, struct logger *logger)
{
	/* will inherit defaults */
	lset_t debugging = lmod(LEMPTY, wm->debugging);

	/*
	 * Allocate the configuration - only allocated on root
	 * connection; connection instances (clones) inherit these
	 * pointers.
	 */
	struct config *root_config = alloc_config(wm->ike_version);
	struct connection *c = alloc_connection(wm->name, NULL, root_config,
						debugging | wm->conn_debug,
						logger, HERE);
	c->root_config = root_config;

	diag_t d = extract_connection(wm, c, root_config);
	if (d != NULL) {
		struct connection *cp = c;
		PASSERT(c->logger, delref_where(&cp, c->logger, HERE) == c);
		discard_connection(&c, false/*not-valid*/, HERE);
		return d;
	}

	/* log all about this connection */

	/* connection is good-to-go: log against it */

	err_t tss = connection_requires_tss(c);
	if (tss != NULL) {
		llog(RC_LOG, c->logger, "connection is using multiple %s", tss);
	}

	LLOG_JAMBUF(RC_LOG, c->logger, buf) {
		jam_string(buf, "added");
		jam_string(buf, " ");
		jam_orientation(buf, c, /*oriented_details*/false);
	}

	policy_buf pb;
	ldbg(c->logger,
	     "ike_life: %jd; ipsec_life: %jds; rekey_margin: %jds; rekey_fuzz: %lu%%; replay_window: %ju; policy: %s ipsec_max_bytes: %ju ipsec_max_packets %ju",
	     deltasecs(c->config->sa_ike_max_lifetime),
	     deltasecs(c->config->sa_ipsec_max_lifetime),
	     deltasecs(c->config->sa_rekey_margin),
	     c->config->sa_rekey_fuzz,
	     c->config->child_sa.replay_window,
	     str_connection_policies(c, &pb),
	     c->config->sa_ipsec_max_bytes,
	     c->config->sa_ipsec_max_packets);
	release_whack(c->logger, HERE);
	return NULL;
}

static connection_priority_t max_prefix_len(struct connection_end *end)
{
	int len = 0;
	FOR_EACH_ITEM(selector, &end->child.selectors.proposed) {
		int prefix_len = selector_prefix_len((*selector));
		if (prefix_len >= 0) {
			len = max(len, prefix_len);
		}
	}
	return len;
}

connection_priority_t connection_priority(const struct connection *c)
{
	connection_priority_t pp = 0;
	/* space for IPv6 mask which is /128 */
	pp |= max_prefix_len(c->local);
	pp <<= 8;
	pp |= max_prefix_len(c->remote);
	pp <<= 1;
	pp |= is_instance(c);
	pp <<= 1;
	pp |= 1; /* never return zero aka BOTTOM_PRIORITY */
	return pp;
}

void jam_connection_priority(struct jambuf *buf, const struct connection *c)
{
	connection_priority_t pp = connection_priority(c);
	/* reverse the above */

	/* 1-bit never zero */
	pp >>= 1;
	/* 1-bit instance */
	unsigned instance = pp & 1;
	pp >>= 1;
	/* 8-bit remote */
	unsigned remote = pp & 0xff;
	pp >>= 8;
	/* 8-bit local */
	unsigned local = pp & 0xff;
	pp >>= 8;

	jam(buf, "%u,%u,%u", local, remote, instance);
}

/*
 * Format any information needed to identify an instance of a connection.
 * Fills any needed information into buf which MUST be big enough.
 * Road Warrior: peer's IP address
 * Opportunistic: [" " myclient "==="] " ..." peer ["===" peer_client] '\0'
 */

static size_t jam_connection_child(struct jambuf *b,
				   const char *prefix, const char *suffix,
				   const struct child_end *child,
				   const ip_address host_addr)
{
	const ip_selectors *selectors =
		(child->selectors.accepted.len > 0 ? &child->selectors.accepted :
		 child->selectors.proposed.len > 0 ? &child->selectors.proposed :
		 NULL);
	size_t s = 0;
	if (selectors == NULL) {
		/* no point */
	} else if (selectors->len == 1 &&
		   /* i.e., selector==host.addr[+protoport] */
		   range_eq_address(selector_range(selectors->list[0]), host_addr)) {
		/* compact denotation for "self" */
	} else {
		s += jam_string(b, prefix);
		if (child->config->addresspools.len > 0) {
			s += jam_string(b, "{");
		}
		const char *sep = "";
		FOR_EACH_ITEM(selector, selectors) {
			if (pexpect(selector->is_set)) {
				s += jam_selector_range(b, selector);
				if (selector_is_zero(*selector)) {
					s += jam_string(b, "?");
				}
			} else {
				s += jam_string(b, "?");
			}
			jam_string(b, sep); sep = ",";
		}
		if (child->config->addresspools.len > 0) {
			s += jam_string(b, "}");
		}
		s += jam_string(b, suffix);
	}
	return s;
}

static size_t jam_connection_suffix(struct jambuf *buf, const struct connection *c)
{
	size_t s = 0;
	if (is_opportunistic(c)) {
		/*
		 * XXX: print proposed or accepted selectors?
		 */
		s += jam_connection_child(buf, " ", "===", &c->local->child,
					  c->local->host.addr);
		s += jam_string(buf, " ...");
		s += jam_address_sensitive(buf, &c->remote->host.addr);
		s += jam_connection_child(buf, "===", "", &c->remote->child,
					  c->remote->host.addr);
	} else {
		s += jam_string(buf, " ");
		s += jam_address_sensitive(buf, &c->remote->host.addr);
	}
	return s;
}

size_t jam_connection(struct jambuf *buf, const struct connection *c)
{
	size_t s = 0;
	s += jam_connection_short(buf, c);
	if (c->instance_serial > 0) {
		s += jam_connection_suffix(buf, c);
	}
	return s;
}

size_t jam_connection_short(struct jambuf *buf, const struct connection *c)
{
	return jam_string(buf, c->prefix);
}

const char *str_connection_short(const struct connection *c)
{
	return c->prefix;
}

const char *str_connection_suffix(const struct connection *c, connection_buf *buf)
{
	struct jambuf p = ARRAY_AS_JAMBUF(buf->buf);
	if (c->instance_serial > 0) {
		jam_connection_suffix(&p, c);
	}
	return buf->buf;
}

size_t jam_connection_policies(struct jambuf *buf, const struct connection *c)
{
	const char *sep = "";
	size_t s = 0;
	enum shunt_policy shunt;

	/* Show [S]tring */
#define CS(S)					\
	{					\
		s += jam_string(buf, sep);	\
		s += jam_string(buf, S);	\
		sep = "+";			\
	}
	/* Show when True (and negotiate) */
#define CT(C, N)				\
	if (!never_negotiate(c) &&		\
	    c->config->C) {			\
		/* show when true */		\
		CS(#N);				\
	}
	/* Show when False (and negotiate) */
#define CF(C, N)				\
	if (!never_negotiate(c) &&		\
	    !c->config->C) {			\
		/* show when false */		\
		CS(#N);				\
	}
	/* Show when [P]redicate (and negotiate) */
#define CP(P, N)				\
	if (!never_negotiate(c) &&		\
	    P) {				\
		/* show when true */		\
		CS(#N);				\
	}
	/* Show when Predicate */
#define CNN(P,N)				\
	if (P) {				\
		/* show when never-negotiate */	\
		CS(#N);				\
	}

	if (c->config->ike_version > 0) {
		CS(c->config->ike_info->version_name);
	}

	struct authby authby = c->local->host.config->authby;
	if (authby_is_set(authby)) {
		s += jam_string(buf, sep);
		s += jam_authby(buf, authby);
		sep = "+";
	}

	switch (c->config->child_sa.encap_proto) {
	case ENCAP_PROTO_ESP:
		CS("ENCRYPT");
		break;
	case ENCAP_PROTO_AH:
		CS("AUTHENTICATE");
		break;
	default:
		break;
	}

	CT(child_sa.ipcomp, COMPRESS);
	if (!never_negotiate(c) &&
	    c->config->child_sa.encap_mode != ENCAP_MODE_UNSET) {
		enum_buf eb;
		CS(str_enum_short(&encap_mode_names, c->config->child_sa.encap_mode, &eb));
	}
	CT(child_sa.pfs, PFS);
	CT(decap_dscp, DECAP_DSCP);
	CF(encap_dscp, DONT_ENCAP_DSCP);
	CT(nopmtudisc, NOPMTUDISC);
	CT(ms_dh_downgrade, MS_DH_DOWNGRADE);
	CT(pfs_rekey_workaround, PFS_REKEY_WORKAROUND);

	/* note reverse logic */
	CF(require_id_on_certificate, ALLOW_NO_SAN);

	CT(dns_match_id, DNS_MATCH_ID);
	CT(sha2_truncbug, SHA2_TRUNCBUG);

	/* note reversed logic */
	CF(rekey, DONT_REKEY);

	CT(reauth, REAUTH);

	CNN(is_opportunistic(c), OPPORTUNISTIC);
	CNN(is_group_instance(c), GROUPINSTANCE);
	CNN(c->policy.route, ROUTE);
	CP(c->policy.up, UP);
	CP(c->policy.keep, KEEP);

	CP(is_xauth(c), XAUTH);
	CT(modecfg.pull, MODECFG_PULL);

	CT(aggressive, AGGRESSIVE);
	CT(overlapip, OVERLAPIP);

	CT(narrowing, IKEV2_ALLOW_NARROWING);

	CT(ikev2_pam_authorize, IKEV2_PAM_AUTHORIZE);

	CT(redirect.send_always, SEND_REDIRECT_ALWAYS);
	CT(redirect.send_never, SEND_REDIRECT_NEVER);
	CT(redirect.accept, ACCEPT_REDIRECT_YES);

	CT(ike_frag.allow, IKE_FRAG_ALLOW);
	CT(ike_frag.v1_force, IKE_FRAG_FORCE);

	/* need to reconstruct */
	if (c->config->v1_ikepad.message) {
		if (c->config->v1_ikepad.modecfg) {
			CS("IKEPAD_YES");
		}
		/* else is RFC */
	} else if (c->config->v1_ikepad.modecfg) {
		CS("IKEPAD_MODECFG"); /* can't happen!?! */
	} else {
		CS("IKEPAD_NO");
	}

	CT(mobike, MOBIKE);
	CT(ppk.allow, PPK_ALLOW);
	CT(ppk.insist, PPK_INSIST);
	CT(esn.no, ESN_NO);
	CT(esn.yes, ESN_YES);
	CT(intermediate, INTERMEDIATE);
	CT(ignore_peer_dns, IGNORE_PEER_DNS);
	CT(session_resumption, RESUME);

	CNN(is_group(c), GROUP);

	shunt = c->config->never_negotiate_shunt;
	if (shunt != SHUNT_UNSET) {
		s += jam_string(buf, sep);
		s += jam_enum_short(buf, &shunt_policy_names, shunt);
		sep = "+";
	}

	shunt = c->config->negotiation_shunt;
	if (shunt != SHUNT_HOLD) {
		s += jam_string(buf, sep);
		s += jam_string(buf, "NEGO_");
		s += jam_enum_short(buf, &shunt_policy_names, shunt);
		sep = "+";
	}

	shunt = c->config->failure_shunt;
	if (shunt != SHUNT_NONE) {
		s += jam_string(buf, sep);
		s += jam_string(buf, "failure");
		s += jam_enum_short(buf, &shunt_policy_names, shunt);
		sep = "+";
	}

	CNN(never_negotiate(c), NEVER_NEGOTIATE);

	return s;
}

const char *str_connection_policies(const struct connection *c, policy_buf *buf)
{
	struct jambuf p = ARRAY_AS_JAMBUF(buf->buf);
	jam_connection_policies(&p, c);
	return buf->buf;
}

/*
 * Find an existing connection for a trapped outbound packet.
 *
 * This is attempted before we bother with gateway discovery.
 *
 *   + the connection is routed or instance_of_routed_template
 *     (i.e. approved for on-demand)
 *
 *   + local subnet contains src address (or we are our_client)
 *
 *   + remote subnet contains dst address (or peer is peer_client)
 *
 *   + don't care about Phase 1 IDs (we don't know)
 *
 * Note: result may still need to be instantiated.  The winner has the
 * highest policy priority.
 *
 * If there are several with that priority, we give preference to the
 * first one that is an instance.
 *
 * See also find_outgoing_opportunistic_template().
 */

struct connection *find_connection_for_packet(const ip_packet packet,
					      shunk_t sec_label,
					      const struct logger *logger)
{
	packet_buf pb;
	ldbg(logger, "%s() looking for an out-going connection that matches packet %s sec_label="PRI_SHUNK,
	     __func__, str_packet(&packet, &pb), pri_shunk(sec_label));

	const ip_selector packet_src = packet_src_selector(packet);
	const ip_endpoint packet_dst = packet_dst_endpoint(packet);

	struct connection *best_connection = NULL;
	connection_priority_t best_priority = BOTTOM_PRIORITY;

	struct connection_filter cq = {
		.search = {
			.order = NEW2OLD,
			.verbose.logger = logger,
			.where = HERE,
		},
	};
	while (next_connection(&cq)) {
		struct connection *c = cq.c;

		if (!oriented(c)) {
			connection_buf cb;
			ldbg(logger, "    skipping "PRI_CONNECTION"; not oriented",
			     pri_connection(c, &cb));
			continue;
		}

		if (is_group(c)) {
			connection_buf cb;
			ldbg(logger, "    skipping "PRI_CONNECTION"; a food group",
			     pri_connection(c, &cb));
			continue;
		}

		/*
		 * Don't try to mix 'n' match acquire sec_label with
		 * non-sec_label connections.
		 */
		if (sec_label.len == 0 && is_labeled(c)) {
			connection_buf cb;
			ldbg(logger, "    skipping "PRI_CONNECTION"; has unwanted label",
			     pri_connection(c, &cb));
			continue;
		}
		if (sec_label.len > 0 && !is_labeled(c)) {
			connection_buf cb;
			ldbg(logger, "    skipping "PRI_CONNECTION"; doesn't have label",
			     pri_connection(c, &cb));
			continue;
		}

		/*
		 * Labeled IPsec, always start with the either the
		 * template or the parent - assume the kernel won't
		 * send a duplicate child request.
		 */
		if (is_labeled_child(c)) {
			connection_buf cb;
			ldbg(logger, "    skipping "PRI_CONNECTION"; IKEv2 sec_label connection is a child",
			     pri_connection(c, &cb));
			continue;
		}

		/*
		 * When there is a sec_label, it needs to be within
		 * the configuration's range.
		 */
		if (sec_label.len > 0 /*implies c->config->sec_label > 0 */ &&
		    !sec_label_within_range("acquire", sec_label,
					    c->config->sec_label, logger)) {
			connection_buf cb;
			ldbg(logger, "    skipping "PRI_CONNECTION"; packet sec_label="PRI_SHUNK" not within connection sec_label="PRI_SHUNK,
			     pri_connection(c, &cb), pri_shunk(sec_label),
			     pri_shunk(c->config->sec_label));
			continue;
		}

		/*
		 * Old comment from the dawn of time:
		 *
		 * Remember if the template is routed: if so, this
		 * instance applies for initiation even if it is
		 * created for responding.
		 *
		 * XXX: So, if the instance is routed, and so to is
		 * its template, then let it be reused for an outgoing
		 * connection?!?
		 */
		bool instance_initiation_ok =
			(is_opportunistic(c) &&
			 is_instance(c) &&
			 pexpect(c->clonedfrom != NULL) /* because instance */ &&
			 kernel_route_installed(c->clonedfrom));
		if (!kernel_route_installed(c) &&
		    !instance_initiation_ok &&
		    c->config->sec_label.len == 0) {
			connection_buf cb;
			ldbg(logger, "    skipping "PRI_CONNECTION"; !routed,!instance_initiation_ok,!sec_label",
			     pri_connection(c, &cb));
			continue;
		}

		/*
		 * The triggering packet needs to be within
		 * the client.
		 */

		connection_priority_t src = 0;
		FOR_EACH_ITEM(local, &c->local->child.selectors.proposed) {
			/*
			 * The packet source address is a selector, and not endpoint.
			 *
			 * If the triggering source port passed into
			 * the kernel is ephemeral (i.e., passed in
			 * with the value zero) that same ephemeral
			 * (zero) port is passed on to pluto.  A zero
			 * (unknown) port is not valid for an
			 * endpoint.
			 */
			if (selector_in_selector(packet_src, *local)) {
				/* add one so always non-zero */
				unsigned score =
					(((local->hport == packet_src.hport) << 2) |
					 ((local->ipproto == packet_src.ipproto) << 1) |
					 1);
				src = max(score, src);
			}
		}

		if (src == 0) {
			LDBGP_JAMBUF(DBG_BASE, logger, buf) {
				jam_string(buf, "    skipping ");
				jam_connection(buf, c);
				jam_string(buf, "; packet dst ");
				jam_selector(buf, &packet_src);
				jam_string(buf, " not in selectors ");
				jam_selectors(buf, c->local->child.selectors.proposed);
			}
			continue;
		}

		connection_priority_t dst = 0;
		FOR_EACH_ITEM(remote, &c->remote->child.selectors.proposed) {
			/*
			 * The packet destination address is always a
			 * proper endpoint.
			 */
			if (endpoint_in_selector(packet_dst, *remote)) {
				/* add one so always non-zero */
				unsigned score =
					(((remote->hport == packet_dst.hport) << 2) | 1);
				dst = max(score, dst);
			}
		}

		if (dst == 0) {
			LDBGP_JAMBUF(DBG_BASE, logger, buf) {
				jam_string(buf, "    skipping ");
				jam_connection(buf, c);
				jam_string(buf, "; packet dst ");
				jam_endpoint(buf, &packet_dst);
				jam_string(buf, " not in selectors ");
				jam_selectors(buf, c->remote->child.selectors.proposed);
			}
			continue;
		}

		/*
		 * More exact is better and bigger
		 *
		 * Instance score better than the template.  Exact
		 * protocol or exact port gets more points (see
		 * above).
		 */
		connection_priority_t priority =
			((connection_priority(c) << 3)/*space-for-2-bits+overflow*/ +
			 (src - 1/*2-bits, strip 1 added above*/) +
			 (dst - 1/*2-bits, strip 1 added above*/));

		if (best_connection != NULL &&
		    priority <= best_priority) {
			connection_buf cb, bcb;
			ldbg(logger,
			     "    skipping "PRI_CONNECTION" priority %"PRIu32"; doesn't best "PRI_CONNECTION" priority %"PRIu32,
			     pri_connection(c, &cb),
			     priority,
			     pri_connection(best_connection, &bcb),
			     best_priority);
			continue;
		}

		/* current is best; log why */
		if (best_connection == NULL) {
			connection_buf cb;
			ldbg(logger,
			     "    choosing "PRI_CONNECTION" priority %"PRIu32"; as first best",
			     pri_connection(c, &cb),
			     priority);
		} else {
			connection_buf cb, bcb;
			ldbg(logger,
			     "    choosing "PRI_CONNECTION" priority %"PRIu32"; as bests "PRI_CONNECTION" priority %"PRIu32,
			     pri_connection(c, &cb),
			     priority,
			     pri_connection(best_connection, &bcb),
			     best_priority);
		}

		best_connection = c;
		best_priority = priority;
	}

	if (best_connection == NULL) {
		ldbg(logger, "  concluding with empty; no match");
		return NULL;
	}

	/*
	 * XXX: So that the best connection can prevent negotiation?
	 */
	if (never_negotiate(best_connection)) {
		connection_buf cb;
		ldbg(logger, "  concluding with empty; best connection "PRI_CONNECTION" was NEVER_NEGOTIATE",
		     pri_connection(best_connection, &cb));
		return NULL;
	}

	connection_buf cib;
	enum_buf kb;
	dbg("  concluding with "PRI_CONNECTION" priority %" PRIu32 " kind=%s",
	    pri_connection(best_connection, &cib),
	    best_priority,
	    str_enum_short(&connection_kind_names, best_connection->local->kind, &kb));
	return best_connection;
}

/*
 * Recursively order instances.
 */

static int connection_instance_compare(const struct connection *cl,
				       const struct connection *cr)
{
	if (cl->clonedfrom != NULL && cr->clonedfrom != NULL) {
		int ret = connection_instance_compare(cl->clonedfrom,
						      cr->clonedfrom);
		if (ret != 0) {
			return ret;
		}
	}

	return (cl->instance_serial < cr->instance_serial ? -1 :
		cl->instance_serial > cr->instance_serial ? 1 :
		0);
}

/* signed result suitable for quicksort */
int connection_compare(const struct connection *cl,
		       const struct connection *cr)
{
	int ret;

	ret = strcmp(cl->name, cr->name);
	if (ret != 0) {
		return ret;
	}

	/* note: enum connection_kind behaves like int */
	ret = (long)cl->local->kind - (long)cr->local->kind;
	if (ret != 0) {
		return ret;
	}

	/* same name, and same type */
	ret = connection_instance_compare(cl, cr);
	if (ret != 0) {
		return ret;
	}

	connection_priority_t pl = connection_priority(cl);
	connection_priority_t pr = connection_priority(cr);
	return (pl < pr ? -1 :
		pl > pr ? 1 :
		0);
}

static int connection_compare_qsort(const void *l, const void *r)
{
	return connection_compare(*(const struct connection *const *)l,
				  *(const struct connection *const *)r);
}

/*
 * Return a sorted array of connections.  Caller must free.
 *
 * See also sort_states().
 */
struct connection **sort_connections(void)
{
	/* count up the connections */
	unsigned nr_connections = 0;
	{
		struct connection_filter cq = {
			.search = {
				.order = NEW2OLD,
				.verbose.logger = &global_logger,
				.where = HERE,
			},
		};
		while (next_connection(&cq)) {
			nr_connections++;
		}
	}

	if (nr_connections == 0) {
		return NULL;
	}

	/* make a NULL terminated array of connections */
	struct connection **connections = alloc_things(struct connection *,
						       nr_connections + 1,
						       "connection array");
	{
		unsigned i = 0;
		struct connection_filter cq = {
			.search = {
				.order = NEW2OLD,
				.verbose.logger = &global_logger,
				.where = HERE,
			},
		};
		while (next_connection(&cq)) {
			connections[i++] = cq.c;
		}
		passert(i == nr_connections);
	}

	/* sort it! */
	qsort(connections, nr_connections, sizeof(struct connection *),
	      connection_compare_qsort);

	return connections;
}

/*
 * Find a sourceip for the address family.
 */
ip_address config_end_sourceip(const ip_selector client, const struct child_end_config *end)
{
	const struct ip_info *afi = selector_info(client);
	FOR_EACH_ITEM(sourceip, &end->sourceip) {
		if (afi == address_type(sourceip)) {
			return *sourceip;
		}
	}

	return unset_address;
}

ip_address spd_end_sourceip(const struct spd_end *spde)
{
	/*
	 * Find a configured sourceip within the SPD's client.
	 */
	ip_address sourceip = config_end_sourceip(spde->client, spde->child->config);
	if (sourceip.is_set) {
		return sourceip;
	}

	/*
	 * Failing that see if CP is involved.  IKEv1 always leaves
	 * client_address_translation false.
	 */
	const struct ip_info *afi = selector_info(spde->client);
	if (afi != NULL &&
	    spde->child->lease[afi->ip_index].is_set &&
	    !spde->child->config->has_client_address_translation) {
		/* XXX: same as .lease[]? */
		ip_address a = selector_prefix(spde->client);
		pexpect(address_eq_address(a, spde->child->lease[afi->ip_index]));
		return selector_prefix(spde->client);
	}

	/* or give up */
	return unset_address;
}

/*
 * If the connection contains a newer SA, return it.
 */
so_serial_t get_newer_sa_from_connection(struct state *st)
{
	struct connection *c = st->st_connection;
	so_serial_t newest;

	if (IS_IKE_SA(st)) {
		newest = c->established_ike_sa;
		dbg("picked established_ike_sa #%lu for #%lu",
		    newest, st->st_serialno);
	} else {
		newest = c->established_child_sa;
		dbg("picked established_child_sa #%lu for #%lu",
		    newest, st->st_serialno);
	}

	if (newest != SOS_NOBODY && newest != st->st_serialno) {
		return newest;
	} else {
		return SOS_NOBODY;
	}
}

/* check to see that Ids of peers match */
bool same_peer_ids(const struct connection *c, const struct connection *d)
{
	return (same_id(&c->local->host.id, &d->local->host.id) &&
		same_id(&c->remote->host.id, &d->remote->host.id));
}

/* seems to be a good spot for now */
bool dpd_active_locally(const struct connection *c)
{
	return deltasecs(c->config->dpd.delay) != 0;
}

void append_end_selector(struct connection_end *end,
			 const struct ip_info *afi, ip_selector selector/*could be unset*/,
			 const struct logger *logger, where_t where)
{
	PASSERT_WHERE(logger, where, (selector_is_unset(&selector) ||
				      selector_info(selector) == afi));
	/*
	 * Either uninitialized, or using the (first) scratch entry
	 */
	if (end->child.selectors.proposed.list == NULL) {
		PASSERT_WHERE(logger, where, end->child.selectors.proposed.len == 0);
		end->child.selectors.proposed.list = end->child.selectors.assigned;
	} else {
		PASSERT_WHERE(logger, where, end->child.selectors.proposed.len > 0);
		PASSERT_WHERE(logger, where, end->child.selectors.proposed.list == end->child.selectors.assigned);
	}
	/* space? */
	PASSERT_WHERE(logger, where, end->child.selectors.proposed.len < elemsof(end->child.selectors.assigned));
	PASSERT_WHERE(logger, where, end->child.selectors.proposed.ip[afi->ip_index].len == 0);

	/* append the selector to assigned; always initlaize .list */
	unsigned i = end->child.selectors.proposed.len++;
	end->child.selectors.assigned[i] = selector;
	/* keep IPv[46] table in sync */
	end->child.selectors.proposed.ip[afi->ip_index].len = 1;
	end->child.selectors.proposed.ip[afi->ip_index].list = &end->child.selectors.assigned[i];

	selector_buf nb;
	ldbg(logger, "%s() %s.child.selectors.proposed[%d] %s "PRI_WHERE,
	     __func__,
	     end->config->leftright,
	     i, str_selector(&selector, &nb),
	     pri_where(where));
}

void update_end_selector_where(struct connection *c, enum end lr,
			       ip_selector new_selector,
			       const char *excuse, where_t where)
{
	struct connection_end *end = &c->end[lr];
	struct child_end *child = &end->child;
	struct child_end_selectors *end_selectors = &end->child.selectors;
	const char *leftright = end->config->leftright;

	PEXPECT_WHERE(c->logger, where, end_selectors->proposed.len == 1);
	ip_selector old_selector = end_selectors->proposed.list[0];
	selector_buf ob, nb;
	ldbg(c->logger, "%s() update %s.child.selector %s -> %s "PRI_WHERE,
	     __func__, leftright,
	     str_selector(&old_selector, &ob),
	     str_selector(&new_selector, &nb),
	     pri_where(where));

	/*
	 * Point the selectors list at and UPDATE the scratch value.
	 *
	 * Is the assumption that this is only applied when there is a
	 * single selector.  Reasonable?  Certainly don't want to
	 * truncate the selector list.
	 */
	zero(&end->child.selectors.proposed);
	const struct ip_info *afi = selector_info(new_selector);
	append_end_selector(end, afi, new_selector, c->logger, where);

	/*
	 * If needed, also update the SPD.  It's assumed for this code
	 * path there is only one (just like there is only one
	 * selector).
	 */
	if (c->spd != NULL) {
		PEXPECT_WHERE(c->logger, where, c->child.spds.len == 1);
		ip_selector old_client = c->spd->end[lr].client;
		if (!selector_eq_selector(old_selector, old_client)) {
			selector_buf sb, cb;
			llog_pexpect(c->logger, where,
				     "%s() %s.child.selector %s does not match %s.spd.client %s",
				     __func__, leftright,
				     str_selector(&old_selector, &sb),
				     end->config->leftright,
				     str_selector(&old_client, &cb));
		}
		c->spd->end[lr].client = new_selector;
	}

	/*
	 * When there's a selectors.list, any update to the first
	 * selector should be a no-op?  Lets find out.
	 *
	 * XXX: the CP payload code violoates this.
	 *
	 * It stomps on the child.selector without even looking at the
	 * traffic selectors.
	 *
	 * XXX: the TS code violates this.
	 *
	 * It scribbles the result of the TS negotiation on the
	 * child.selector.
	 */
	if (child->config->selectors.len > 0) {
		ip_selector selector = child->config->selectors.list[0];
		if (selector_eq_selector(new_selector, selector)) {
			selector_buf sb;
			ldbg(c->logger,
			     "%s() %s.child.selector %s matches selectors[0] "PRI_WHERE,
			     __func__, leftright,
			     str_selector(&new_selector, &sb),
			     pri_where(where));
		} else if (excuse != NULL) {
			selector_buf sb, cb;
			ldbg(c->logger,
			     "%s() %s.child.selector %s does not match %s.selectors[0] %s but %s "PRI_WHERE,
			     __func__, leftright, str_selector(&new_selector, &sb),
			     leftright, str_selector(&selector, &cb),
			     excuse, pri_where(where));
		} else {
			selector_buf sb, cb;
			llog_pexpect(c->logger, where,
				     "%s() %s.child.selector %s does not match %s.selectors[0] %s",
				     __func__, leftright, str_selector(&new_selector, &sb),
				     leftright, str_selector(&selector, &cb));
		}
	}
}

err_t connection_requires_tss(const struct connection *c)
{
	if (c->config->ike_version == IKEv1) {
		return NULL;
	}
	FOR_EACH_ELEMENT(end, c->end) {
		if (end->config->child.addresspools.len > 1) {
			return "addresspools";
		}
		if (end->config->child.selectors.len > 1) {
			return "subnets";
		}
		if (end->config->child.sourceip.len > 1) {
			return "sourceips";
		}
	}
	return NULL;
}

bool never_negotiate(const struct connection *c)
{
	if (c == NULL) {
		return false;
	}
	return (c->config->never_negotiate_shunt != SHUNT_UNSET);
}

bool is_opportunistic(const struct connection *c)
{
	return (c != NULL && c->config->opportunistic);
}

bool is_instance(const struct connection *c)
{
	if (c == NULL) {
		return false;
	}
	switch (c->local->kind) {
	case CK_INVALID:
		break;
	case CK_PERMANENT:
	case CK_TEMPLATE:
	case CK_GROUP:
	case CK_LABELED_TEMPLATE:
		return false;
	case CK_INSTANCE:
	case CK_LABELED_PARENT:
	case CK_LABELED_CHILD:
		return true;
	}
	bad_case(c->local->kind);
}

bool is_template(const struct connection *c)
{
	if (c == NULL) {
		return false;
	}
	switch (c->local->kind) {
	case CK_INVALID:
		break;
	case CK_TEMPLATE:
	case CK_LABELED_TEMPLATE:
		return true;
	case CK_PERMANENT:
	case CK_GROUP:
	case CK_INSTANCE:
	case CK_LABELED_PARENT:
	case CK_LABELED_CHILD:
		return false;
	}
	bad_case(c->local->kind);
}

bool is_opportunistic_template(const struct connection *c)
{
	if (c == NULL) {
		return false;
	}
	switch (c->local->kind) {
	case CK_INVALID:
		break;
	case CK_TEMPLATE:
		return is_opportunistic(c);
	case CK_LABELED_TEMPLATE:
	case CK_PERMANENT:
	case CK_GROUP:
	case CK_INSTANCE:
	case CK_LABELED_PARENT:
	case CK_LABELED_CHILD:
		return false;
	}
	bad_case(c->local->kind);
}

bool is_permanent(const struct connection *c)
{
	if (c == NULL) {
		return false;
	}
	switch (c->local->kind) {
	case CK_INVALID:
		break;
	case CK_PERMANENT:
		return true;
	case CK_TEMPLATE:
	case CK_LABELED_TEMPLATE:
	case CK_GROUP:
	case CK_INSTANCE:
	case CK_LABELED_PARENT:
	case CK_LABELED_CHILD:
		return false;
	}
	bad_case(c->local->kind);
}

bool is_group(const struct connection *c)
{
	if (c == NULL) {
		return false;
	}
	switch (c->local->kind) {
	case CK_INVALID:
		break;
	case CK_GROUP:
		return true;
	case CK_PERMANENT:
	case CK_TEMPLATE:
	case CK_LABELED_TEMPLATE:
	case CK_INSTANCE:
	case CK_LABELED_PARENT:
	case CK_LABELED_CHILD:
		return false;
	}
	bad_case(c->local->kind);
}

bool is_group_instance(const struct connection *c)
{
	if (c == NULL) {
		return false;
	}
	switch (c->local->kind) {
	case CK_INVALID:
		break;
	case CK_GROUP:
	case CK_PERMANENT:
	case CK_LABELED_TEMPLATE:
	case CK_LABELED_PARENT:
	case CK_LABELED_CHILD:
		return false;
	case CK_TEMPLATE:
		/* cloned from could be null; is_group() handles
		 * that */
		return is_group(c->clonedfrom);
	case CK_INSTANCE:
		/* cloned from could be null; is_group() handles
		 * that */
		return is_group(c->clonedfrom->clonedfrom);
	}
	bad_enum(c->logger, &connection_kind_names, c->local->kind);
}

bool is_labeled_where(const struct connection *c, where_t where)
{
	if (c == NULL) {
		return false;
	}
	switch (c->local->kind) {
	case CK_INVALID:
		break;
	case CK_LABELED_PARENT:
	case CK_LABELED_CHILD:
	case CK_LABELED_TEMPLATE:
		PASSERT_WHERE(c->logger, where, c->config->sec_label.len > 0);
		return true;
	case CK_TEMPLATE:
	case CK_PERMANENT:
	case CK_GROUP:
	case CK_INSTANCE:
		PASSERT_WHERE(c->logger, where, c->config->sec_label.len == 0);
		return false;
	}
	bad_case(c->local->kind);
}

bool is_labeled_template_where(const struct connection *c, where_t where)
{
	if (c == NULL) {
		return false;
	}
	switch (c->local->kind) {
	case CK_INVALID:
		break;
	case CK_LABELED_TEMPLATE:
		PASSERT_WHERE(c->logger, where, (c->config->sec_label.len > 0 &&
						 c->child.sec_label.len == 0));
		return true;
	case CK_LABELED_PARENT:
	case CK_LABELED_CHILD:
	case CK_TEMPLATE:
	case CK_PERMANENT:
	case CK_GROUP:
	case CK_INSTANCE:
		return false;
	}
	bad_case(c->local->kind);
}

bool is_labeled_parent_where(const struct connection *c, where_t where)
{
	if (c == NULL) {
		return false;
	}
	switch (c->local->kind) {
	case CK_INVALID:
		break;
	case CK_LABELED_PARENT:
		PASSERT_WHERE(c->logger, where, (c->config->sec_label.len > 0 &&
						 c->child.sec_label.len == 0));
		return true;
	case CK_LABELED_TEMPLATE:
	case CK_LABELED_CHILD:
	case CK_TEMPLATE:
	case CK_PERMANENT:
	case CK_GROUP:
	case CK_INSTANCE:
		return false;
	}
	bad_case(c->local->kind);
}

bool is_labeled_child_where(const struct connection *c, where_t where)
{
	if (c == NULL) {
		return false;
	}
	switch (c->local->kind) {
	case CK_INVALID:
		break;
	case CK_LABELED_CHILD:
		PASSERT_WHERE(c->logger, where, (c->config->sec_label.len > 0 &&
						 c->child.sec_label.len > 0));
		return true;
	case CK_LABELED_TEMPLATE:
	case CK_LABELED_PARENT:
	case CK_TEMPLATE:
	case CK_PERMANENT:
	case CK_GROUP:
	case CK_INSTANCE:
		return false;
	}
	bad_case(c->local->kind);
}

bool can_have_sa(const struct connection *c, 
		 enum sa_type sa_type)
{
	if (c == NULL) {
		return false;
	}
	switch (sa_type) {
	case IKE_SA:
		switch (c->local->kind) {
		case CK_INVALID:
			break;
		case CK_LABELED_CHILD:
		case CK_GROUP:
		case CK_LABELED_TEMPLATE:
		case CK_TEMPLATE:
			return false;
		case CK_LABELED_PARENT:
		case CK_PERMANENT:
		case CK_INSTANCE:
			return true;
		}
		bad_enum(c->logger, &connection_kind_names, c->local->kind);
	case CHILD_SA:
		switch (c->local->kind) {
		case CK_INVALID:
			break;
		case CK_LABELED_TEMPLATE:
		case CK_LABELED_PARENT:
		case CK_TEMPLATE:
		case CK_GROUP:
			return false;
		case CK_PERMANENT:
		case CK_INSTANCE:
		case CK_LABELED_CHILD:
			return true;
		}
		bad_enum(c->logger, &connection_kind_names, c->local->kind);
	}
	bad_case(sa_type);
}

/*
 * XXX: is this too strict?
 *
 * addconn was setting XAUTH when either of SERVER or CLIENT was set,
 * but the below only considers SERVER.
 */
 
bool is_xauth(const struct connection *c)
{
	return (c->local->host.config->xauth.server || c->remote->host.config->xauth.server ||
		c->local->host.config->xauth.client || c->remote->host.config->xauth.client);
}

bool is_v1_cisco_split(const struct spd *spd UNUSED, where_t where UNUSED)
{
#ifdef USE_CISCO_SPLIT
	if (spd->connection->remotepeertype == CISCO &&
	    spd->connection->child.spds.list == spd &&
	    spd->connection->child.spds.len > 1) {
		ldbg(spd->connection->logger,
		     "kernel: skipping first SPD, remotepeertype is CISCO, damage done "PRI_WHERE,
		     pri_where(were));
		return true;
	}
#endif
	return false;
}


/* IKE SA | ISAKMP SA || Child SA | IPsec SA */
const char *connection_sa_name(const struct connection *c, enum sa_type sa_type)
{
	switch (sa_type) {
	case IKE_SA:
		return c->config->ike_info->parent_sa_name;
	case CHILD_SA:
		return c->config->ike_info->child_sa_name;
	}
	bad_case(sa_type);
}

/* IKE | ISAKMP || Child | IPsec */
const char *connection_sa_short_name(const struct connection *c, enum sa_type sa_type)
{
	switch (sa_type) {
	case IKE_SA:
		return c->config->ike_info->parent_name;
	case CHILD_SA:
		return c->config->ike_info->child_name;
	}
	bad_case(sa_type);
}

struct child_policy child_sa_policy(const struct connection *c)
{
	if (c->config->child_sa.encap_proto == ENCAP_PROTO_ESP ||
	    c->config->child_sa.encap_proto == ENCAP_PROTO_AH) {
		return (struct child_policy) {
			.is_set = true,
			.transport = (c->config->child_sa.encap_mode == ENCAP_MODE_TRANSPORT),
			.compress = c->config->child_sa.ipcomp,
		};
	}

	return (struct child_policy) {0};
}

/*
 * Find newest Phase 1 negotiation state object for suitable for
 * connection c.
 *
 * Also used to find an IKEv1 ISAKMP SA suitable for sending a delete.
 */

bool connections_can_share_parent(const struct connection *c, const struct connection *d)
{
	/*
	 * Need matching version and parent for starters!
	 */
	if (c->config->ike_version != d->config->ike_version) {
		return false;
	}

	/*
	 * Check the initial host-pair.  Do these two mean that a much
	 * faster host-pair search could be used?
	 *
	 * Not really, it's called when searching for an IKE SA, and
	 * not a connection.  However, a connection search that uses
	 * .negotiating_ike_sa and/or .established_ike_sa, might?
	 */
	if (!address_eq_address(c->local->host.addr, d->local->host.addr)) {
		return false;
	}
	if (!address_eq_address(c->remote->host.first_addr, d->remote->host.first_addr)) {
		return false;
	}

	/*
	 * Also check any redirection.
	 */
	if (!address_eq_address(c->remote->host.addr, d->remote->host.addr)) {
		return false;
	}

	/*
	 * i.e., connection and IKE SA have the same authentication.
	 */
	if (!same_peer_ids(c, d)) {
		return false;
	}

	return true;
}

reqid_t child_reqid(const struct config *config, struct logger *logger)
{
	reqid_t reqid = (config->sa_reqid != 0 ? config->sa_reqid :
			 gen_reqid());
	ldbg(logger, "child.reqid="PRI_REQID" because c->sa_reqid="PRI_REQID" (%s)",
	     pri_reqid(reqid),
	     pri_reqid(config->sa_reqid),
	     (config->sa_reqid == 0 ? "generate" : "use"));
	return reqid;
}