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

#define _GNU_SOURCE
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>

#include <sys/stat.h>
#include <sys/types.h>

#include <import/ebpttree.h>
#include <import/ebsttree.h>

#include <haproxy/applet.h>
#include <haproxy/base64.h>
#include <haproxy/cfgparse.h>
#include <haproxy/channel.h>
#include <haproxy/cli.h>
#include <haproxy/errors.h>
#include <haproxy/sc_strm.h>
#include <haproxy/ssl_ckch.h>
#include <haproxy/ssl_sock.h>
#include <haproxy/ssl_ocsp.h>
#include <haproxy/ssl_utils.h>
#include <haproxy/stconn.h>
#include <haproxy/tools.h>

/* Uncommitted CKCH transaction */

static struct {
	struct ckch_store *new_ckchs;
	struct ckch_store *old_ckchs;
	char *path;
} ckchs_transaction;

/* Uncommitted CA file transaction */

static struct {
	struct cafile_entry *old_cafile_entry;
	struct cafile_entry *new_cafile_entry;
	char *path;
} cafile_transaction;

/* Uncommitted CRL file transaction */

static struct {
	struct cafile_entry *old_crlfile_entry;
	struct cafile_entry *new_crlfile_entry;
	char *path;
} crlfile_transaction;

/* CLI context used by "show cafile" */
struct show_cafile_ctx {
	struct cafile_entry *cur_cafile_entry;
	struct cafile_entry *old_cafile_entry;
	int ca_index;
	int show_all;
};

/* CLI context used by "show crlfile" */
struct show_crlfile_ctx {
	struct cafile_entry *cafile_entry;
	struct cafile_entry *old_crlfile_entry;
	int index;
};

/* CLI context used by "show cert" */
struct show_cert_ctx {
	struct ckch_store *old_ckchs;
	struct ckch_store *cur_ckchs;
	int transaction;
};

/* CLI context used by "commit cert" */
struct commit_cert_ctx {
	struct ckch_store *old_ckchs;
	struct ckch_store *new_ckchs;
	struct ckch_inst *next_ckchi;
	char *err;
	enum {
		CERT_ST_INIT = 0,
		CERT_ST_GEN,
		CERT_ST_INSERT,
		CERT_ST_SUCCESS,
		CERT_ST_FIN,
		CERT_ST_ERROR,
	} state;
};

/* CLI context used by "commit cafile" and "commit crlfile" */
struct commit_cacrlfile_ctx {
	struct cafile_entry *old_entry;
	struct cafile_entry *new_entry;
	struct ckch_inst_link *next_ckchi_link;
	enum cafile_type cafile_type; /* either CA or CRL, depending on the current command */
	char *err;
	enum {
		CACRL_ST_INIT = 0,
		CACRL_ST_GEN,
		CACRL_ST_CRLCB,
		CACRL_ST_INSERT,
		CACRL_ST_SUCCESS,
		CACRL_ST_FIN,
		CACRL_ST_ERROR,
	} state;
};


/*
 * Callback function, which is called if defined after loading CRLs from disk
 * when starting HAProxy (function __ssl_store_load_locations_file()), and after
 * committing new CRLs via CLI (function cli_io_handler_commit_cafile_crlfile()).
 *
 * The input parameters of the function are the path for the CRL data and
 * a structure containing information about X.509 certificates and CRLs.
 * In case of error, returns -1 with an error message in err; or the number
 * of revoked certificates (>= 0) otherwise.
 */
int (*ssl_commit_crlfile_cb)(const char *path, X509_STORE *ctx, char **err) = NULL;

/********************  cert_key_and_chain functions *************************
 * These are the functions that fills a cert_key_and_chain structure. For the
 * functions filling a SSL_CTX from a cert_key_and_chain, see ssl_sock.c
 */

/*
 * Try to parse Signed Certificate Timestamp List structure. This function
 * makes only basic test if the data seems like SCTL. No signature validation
 * is performed.
 */
static int ssl_sock_parse_sctl(struct buffer *sctl)
{
	int ret = 1;
	int len, pos, sct_len;
	unsigned char *data;

	if (sctl->data < 2)
		goto out;

	data = (unsigned char *) sctl->area;
	len = (data[0] << 8) | data[1];

	if (len + 2 != sctl->data)
		goto out;

	data = data + 2;
	pos = 0;
	while (pos < len) {
		if (len - pos < 2)
			goto out;

		sct_len = (data[pos] << 8) | data[pos + 1];
		if (pos + sct_len + 2 > len)
			goto out;

		pos += sct_len + 2;
	}

	ret = 0;

out:
	return ret;
}

/* Try to load a sctl from a buffer <buf> if not NULL, or read the file <sctl_path>
 * It fills the ckch->sctl buffer
 * return 0 on success or != 0 on failure */
int ssl_sock_load_sctl_from_file(const char *sctl_path, char *buf, struct ckch_data *data, char **err)
{
	int fd = -1;
	int r = 0;
	int ret = 1;
	struct buffer tmp;
	struct buffer *src;
	struct buffer *sctl;

	if (buf) {
		chunk_initstr(&tmp, buf);
		src = &tmp;
	} else {
		fd = open(sctl_path, O_RDONLY);
		if (fd == -1)
			goto end;

		trash.data = 0;
		while (trash.data < trash.size) {
			r = read(fd, trash.area + trash.data, trash.size - trash.data);
			if (r < 0) {
				if (errno == EINTR)
					continue;
				goto end;
			}
			else if (r == 0) {
				break;
			}
			trash.data += r;
		}
		src = &trash;
	}

	ret = ssl_sock_parse_sctl(src);
	if (ret)
		goto end;

	sctl = calloc(1, sizeof(*sctl));
	if (!chunk_dup(sctl, src)) {
		ha_free(&sctl);
		goto end;
	}
	/* no error, fill ckch with new context, old context must be free */
	if (data->sctl) {
		ha_free(&data->sctl->area);
		free(data->sctl);
	}
	data->sctl = sctl;
	ret = 0;
end:
	if (fd != -1)
		close(fd);

	return ret;
}

#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
/*
 * This function load the OCSP Response in DER format contained in file at
 * path 'ocsp_path' or base64 in a buffer <buf>
 *
 * Returns 0 on success, 1 in error case.
 */
int ssl_sock_load_ocsp_response_from_file(const char *ocsp_path, char *buf, struct ckch_data *data, char **err)
{
	int fd = -1;
	int r = 0;
	int ret = 1;
	struct buffer *ocsp_response;
	struct buffer *src = NULL;

	if (buf) {
		int i, j;
		/* if it's from a buffer it will be base64 */

		/* remove \r and \n from the payload */
		for (i = 0, j = 0; buf[i]; i++) {
			if (buf[i] == '\r' || buf[i] == '\n')
				continue;
			buf[j++] = buf[i];
		}
		buf[j] = 0;

		ret = base64dec(buf, j, trash.area, trash.size);
		if (ret < 0) {
			memprintf(err, "Error reading OCSP response in base64 format");
			goto end;
		}
		trash.data = ret;
		src = &trash;
	} else {
		fd = open(ocsp_path, O_RDONLY);
		if (fd == -1) {
			memprintf(err, "Error opening OCSP response file");
			goto end;
		}

		trash.data = 0;
		while (trash.data < trash.size) {
			r = read(fd, trash.area + trash.data, trash.size - trash.data);
			if (r < 0) {
				if (errno == EINTR)
					continue;

				memprintf(err, "Error reading OCSP response from file");
				goto end;
			}
			else if (r == 0) {
				break;
			}
			trash.data += r;
		}
		close(fd);
		fd = -1;
		src = &trash;
	}

	ocsp_response = calloc(1, sizeof(*ocsp_response));
	if (!chunk_dup(ocsp_response, src)) {
		ha_free(&ocsp_response);
		goto end;
	}
	/* no error, fill data with new context, old context must be free */
	if (data->ocsp_response) {
		ha_free(&data->ocsp_response->area);
		free(data->ocsp_response);
	}
	data->ocsp_response = ocsp_response;
	ret = 0;
end:
	if (fd != -1)
		close(fd);

	return ret;
}
#endif

/*
 * Try to load in a ckch every files related to a ckch.
 * (PEM, sctl, ocsp, issuer etc.)
 *
 * This function is only used to load files during the configuration parsing,
 * it is not used with the CLI.
 *
 * This allows us to carry the contents of the file without having to read the
 * file multiple times.  The caller must call
 * ssl_sock_free_cert_key_and_chain_contents.
 *
 * returns:
 *      0 on Success
 *      1 on SSL Failure
 */
int ssl_sock_load_files_into_ckch(const char *path, struct ckch_data *data, char **err)
{
	struct buffer *fp = NULL;
	int ret = 1;
	struct stat st;

	/* try to load the PEM */
	if (ssl_sock_load_pem_into_ckch(path, NULL, data , err) != 0) {
		goto end;
	}

	fp = alloc_trash_chunk();
	if (!fp) {
		memprintf(err, "%sCan't allocate memory\n", err && *err ? *err : "");
		goto end;
	}

	if (!chunk_strcpy(fp, path) || (b_data(fp) > MAXPATHLEN)) {
		memprintf(err, "%s '%s' filename too long'.\n",
			  err && *err ? *err : "", fp->area);
		ret = 1;
		goto end;
	}

	/* remove the ".crt" extension */
	if (global_ssl.extra_files_noext) {
		char *ext;

		/* look for the extension */
		if ((ext = strrchr(fp->area, '.'))) {

			if (strcmp(ext, ".crt") == 0) {
				*ext = '\0';
				fp->data = strlen(fp->area);
			}
		}

	}

	if (data->key == NULL) {
		/* If no private key was found yet and we cannot look for it in extra
		 * files, raise an error.
		 */
		if (!(global_ssl.extra_files & SSL_GF_KEY)) {
			memprintf(err, "%sNo Private Key found in '%s'.\n", err && *err ? *err : "", fp->area);
			goto end;
		}

		/* try to load an external private key if it wasn't in the PEM */
		if (!chunk_strcat(fp, ".key") || (b_data(fp) > MAXPATHLEN)) {
			memprintf(err, "%s '%s' filename too long'.\n",
				  err && *err ? *err : "", fp->area);
			ret = 1;
			goto end;
		}

		if (stat(fp->area, &st) == 0) {
			if (ssl_sock_load_key_into_ckch(fp->area, NULL, data, err)) {
				memprintf(err, "%s '%s' is present but cannot be read or parsed'.\n",
					  err && *err ? *err : "", fp->area);
				goto end;
			}
		}

		if (data->key == NULL) {
			memprintf(err, "%sNo Private Key found in '%s'.\n", err && *err ? *err : "", fp->area);
			goto end;
		}
		/* remove the added extension */
		*(fp->area + fp->data - strlen(".key")) = '\0';
		b_sub(fp, strlen(".key"));
	}


	if (!X509_check_private_key(data->cert, data->key)) {
		memprintf(err, "%sinconsistencies between private key and certificate loaded '%s'.\n",
		          err && *err ? *err : "", path);
		goto end;
	}

#ifdef HAVE_SSL_SCTL
	/* try to load the sctl file */
	if (global_ssl.extra_files & SSL_GF_SCTL) {
		struct stat st;

		if (!chunk_strcat(fp, ".sctl") || b_data(fp) > MAXPATHLEN) {
			memprintf(err, "%s '%s' filename too long'.\n",
			          err && *err ? *err : "", fp->area);
			ret = 1;
			goto end;
		}

		if (stat(fp->area, &st) == 0) {
			if (ssl_sock_load_sctl_from_file(fp->area, NULL, data, err)) {
				memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
					  err && *err ? *err : "", fp->area);
				ret = 1;
				goto end;
			}
		}
		/* remove the added extension */
		*(fp->area + fp->data - strlen(".sctl")) = '\0';
		b_sub(fp, strlen(".sctl"));
	}
#endif

	/* try to load an ocsp response file */
	if (global_ssl.extra_files & SSL_GF_OCSP) {
		struct stat st;

		if (!chunk_strcat(fp, ".ocsp") || b_data(fp) > MAXPATHLEN) {
			memprintf(err, "%s '%s' filename too long'.\n",
			          err && *err ? *err : "", fp->area);
			ret = 1;
			goto end;
		}

		if (stat(fp->area, &st) == 0) {
			if (ssl_sock_load_ocsp_response_from_file(fp->area, NULL, data, err)) {
				ret = 1;
				goto end;
			}
		}
		/* remove the added extension */
		*(fp->area + fp->data - strlen(".ocsp")) = '\0';
		b_sub(fp, strlen(".ocsp"));
	}

#ifndef OPENSSL_IS_BORINGSSL /* Useless for BoringSSL */
	if (data->ocsp_response && (global_ssl.extra_files & SSL_GF_OCSP_ISSUER)) {
		/* if no issuer was found, try to load an issuer from the .issuer */
		if (!data->ocsp_issuer) {
			struct stat st;

			if (!chunk_strcat(fp, ".issuer") || b_data(fp) > MAXPATHLEN) {
				memprintf(err, "%s '%s' filename too long'.\n",
					  err && *err ? *err : "", fp->area);
				ret = 1;
				goto end;
			}

			if (stat(fp->area, &st) == 0) {
				if (ssl_sock_load_issuer_file_into_ckch(fp->area, NULL, data, err)) {
					ret = 1;
					goto end;
				}

				if (X509_check_issued(data->ocsp_issuer, data->cert) != X509_V_OK) {
					memprintf(err, "%s '%s' is not an issuer'.\n",
						  err && *err ? *err : "", fp->area);
					ret = 1;
					goto end;
				}
			}
			/* remove the added extension */
			*(fp->area + fp->data - strlen(".issuer")) = '\0';
			b_sub(fp, strlen(".issuer"));
		}
	}
#endif

	ret = 0;

end:

	ERR_clear_error();

	/* Something went wrong in one of the reads */
	if (ret != 0)
		ssl_sock_free_cert_key_and_chain_contents(data);

	free_trash_chunk(fp);

	return ret;
}

/*
 *  Try to load a private key file from a <path> or a buffer <buf>
 *
 *  If it failed you should not attempt to use the ckch but free it.
 *
 *  Return 0 on success or != 0 on failure
 */
int ssl_sock_load_key_into_ckch(const char *path, char *buf, struct ckch_data *data , char **err)
{
	BIO *in = NULL;
	int ret = 1;
	EVP_PKEY *key = NULL;

	if (buf) {
		/* reading from a buffer */
		in = BIO_new_mem_buf(buf, -1);
		if (in == NULL) {
			memprintf(err, "%sCan't allocate memory\n", err && *err ? *err : "");
			goto end;
		}

	} else {
		/* reading from a file */
		in = BIO_new(BIO_s_file());
		if (in == NULL)
			goto end;

		if (BIO_read_filename(in, path) <= 0)
			goto end;
	}

	/* Read Private Key */
	key = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL);
	if (key == NULL) {
		memprintf(err, "%sunable to load private key from file '%s'.\n",
		          err && *err ? *err : "", path);
		goto end;
	}

	ret = 0;

	SWAP(data->key, key);

end:

	ERR_clear_error();
	if (in)
		BIO_free(in);
	if (key)
		EVP_PKEY_free(key);

	return ret;
}

/*
 *  Try to load a PEM file from a <path> or a buffer <buf>
 *  The PEM must contain at least a Certificate,
 *  It could contain a DH, a certificate chain and a PrivateKey.
 *
 *  If it failed you should not attempt to use the ckch but free it.
 *
 *  Return 0 on success or != 0 on failure
 */
int ssl_sock_load_pem_into_ckch(const char *path, char *buf, struct ckch_data *data , char **err)
{
	BIO *in = NULL;
	int ret = 1;
	X509 *ca;
	X509 *cert = NULL;
	EVP_PKEY *key = NULL;
	HASSL_DH *dh = NULL;
	STACK_OF(X509) *chain = NULL;

	if (buf) {
		/* reading from a buffer */
		in = BIO_new_mem_buf(buf, -1);
		if (in == NULL) {
			memprintf(err, "%sCan't allocate memory\n", err && *err ? *err : "");
			goto end;
		}

	} else {
		/* reading from a file */
		in = BIO_new(BIO_s_file());
		if (in == NULL) {
			memprintf(err, "%sCan't allocate memory\n", err && *err ? *err : "");
			goto end;
		}

		if (BIO_read_filename(in, path) <= 0) {
			memprintf(err, "%scannot open the file '%s'.\n",
			          err && *err ? *err : "", path);
			goto end;
		}
	}

	/* Read Private Key */
	key = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL);
	/* no need to check for errors here, because the private key could be loaded later */

#ifndef OPENSSL_NO_DH
	/* Seek back to beginning of file */
	if (BIO_reset(in) == -1) {
		memprintf(err, "%san error occurred while reading the file '%s'.\n",
		          err && *err ? *err : "", path);
		goto end;
	}

	dh = ssl_sock_get_dh_from_bio(in);
	ERR_clear_error();
	/* no need to return an error there, dh is not mandatory */
#endif

	/* Seek back to beginning of file */
	if (BIO_reset(in) == -1) {
		memprintf(err, "%san error occurred while reading the file '%s'.\n",
		          err && *err ? *err : "", path);
		goto end;
	}

	/* Read Certificate */
	cert = PEM_read_bio_X509_AUX(in, NULL, NULL, NULL);
	if (cert == NULL) {
		ret = ERR_get_error();
		memprintf(err, "%sunable to load certificate from file '%s': %s.\n",
		          err && *err ? *err : "", path, ERR_reason_error_string(ret));
		goto end;
	}

	/* Look for a Certificate Chain */
	while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
		if (chain == NULL)
			chain = sk_X509_new_null();
		if (!sk_X509_push(chain, ca)) {
			X509_free(ca);
			break;
		}
	}

	ret = ERR_get_error();
	if (ret && !(ERR_GET_LIB(ret) == ERR_LIB_PEM && ERR_GET_REASON(ret) == PEM_R_NO_START_LINE)) {
		memprintf(err, "%sunable to load certificate chain from file '%s': %s\n",
		          err && *err ? *err : "", path, ERR_reason_error_string(ret));
		goto end;
	}

	/* once it loaded the PEM, it should remove everything else in the data */
	if (data->ocsp_response) {
		ha_free(&data->ocsp_response->area);
		ha_free(&data->ocsp_response);
	}

	if (data->sctl) {
		ha_free(&data->sctl->area);
		ha_free(&data->sctl);
	}

	if (data->ocsp_issuer) {
		X509_free(data->ocsp_issuer);
		data->ocsp_issuer = NULL;
	}

	/* no error, fill data with new context, old context will be free at end: */
	SWAP(data->key, key);
	SWAP(data->dh, dh);
	SWAP(data->cert, cert);
	SWAP(data->chain, chain);

	ret = 0;

end:

	ERR_clear_error();
	if (in)
		BIO_free(in);
	if (key)
		EVP_PKEY_free(key);
	if (dh)
		HASSL_DH_free(dh);
	if (cert)
		X509_free(cert);
	if (chain)
		sk_X509_pop_free(chain, X509_free);

	return ret;
}

/* Frees the contents of a cert_key_and_chain
 */
void ssl_sock_free_cert_key_and_chain_contents(struct ckch_data *data)
{
	if (!data)
		return;

	/* Free the certificate and set pointer to NULL */
	if (data->cert)
		X509_free(data->cert);
	data->cert = NULL;

	/* Free the key and set pointer to NULL */
	if (data->key)
		EVP_PKEY_free(data->key);
	data->key = NULL;

	/* Free each certificate in the chain */
	if (data->chain)
		sk_X509_pop_free(data->chain, X509_free);
	data->chain = NULL;

	if (data->dh)
		HASSL_DH_free(data->dh);
	data->dh = NULL;

	if (data->sctl) {
		ha_free(&data->sctl->area);
		ha_free(&data->sctl);
	}

	if (data->ocsp_response) {
		ha_free(&data->ocsp_response->area);
		ha_free(&data->ocsp_response);
	}

	if (data->ocsp_issuer)
		X509_free(data->ocsp_issuer);
	data->ocsp_issuer = NULL;


	/* We need to properly remove the reference to the corresponding
	 * certificate_ocsp structure if it exists (which it should).
	 */
#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
	if (data->ocsp_cid) {
		struct certificate_ocsp *ocsp = NULL;
		unsigned char certid[OCSP_MAX_CERTID_ASN1_LENGTH] = {};
		unsigned int certid_length = 0;

		if (ssl_ocsp_build_response_key(data->ocsp_cid, (unsigned char*)certid, &certid_length) >= 0) {
			HA_SPIN_LOCK(OCSP_LOCK, &ocsp_tree_lock);
			ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, certid, OCSP_MAX_CERTID_ASN1_LENGTH);
			HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
			ssl_sock_free_ocsp(ocsp);
		}

		OCSP_CERTID_free(data->ocsp_cid);
		data->ocsp_cid = NULL;
	}
#endif
}

/*
 *
 * This function copy a cert_key_and_chain in memory
 *
 * It's used to try to apply changes on a ckch before committing them, because
 * most of the time it's not possible to revert those changes
 *
 * Return a the dst or NULL
 */
struct ckch_data *ssl_sock_copy_cert_key_and_chain(struct ckch_data *src,
                                                                   struct ckch_data *dst)
{
	if (!src || !dst)
		return NULL;

	if (src->cert) {
		dst->cert = src->cert;
		X509_up_ref(src->cert);
	}

	if (src->key) {
		dst->key = src->key;
		EVP_PKEY_up_ref(src->key);
	}

	if (src->chain) {
		dst->chain = X509_chain_up_ref(src->chain);
	}

	if (src->dh) {
#ifndef USE_OPENSSL_WOLFSSL
		HASSL_DH_up_ref(src->dh);
		dst->dh = src->dh;
#else
       dst->dh = wolfSSL_DH_dup(src->dh);
       if (!dst->dh)
           goto error;
#endif
	}

	if (src->sctl) {
		struct buffer *sctl;

		sctl = calloc(1, sizeof(*sctl));
		if (!chunk_dup(sctl, src->sctl)) {
			ha_free(&sctl);
			goto error;
		}
		dst->sctl = sctl;
	}

	if (src->ocsp_response) {
		struct buffer *ocsp_response;

		ocsp_response = calloc(1, sizeof(*ocsp_response));
		if (!chunk_dup(ocsp_response, src->ocsp_response)) {
			ha_free(&ocsp_response);
			goto error;
		}
		dst->ocsp_response = ocsp_response;
	}

	if (src->ocsp_issuer) {
		X509_up_ref(src->ocsp_issuer);
		dst->ocsp_issuer = src->ocsp_issuer;
	}

	dst->ocsp_cid = OCSP_CERTID_dup(src->ocsp_cid);

	return dst;

error:

	/* free everything */
	ssl_sock_free_cert_key_and_chain_contents(dst);

	return NULL;
}

/*
 * return 0 on success or != 0 on failure
 */
int ssl_sock_load_issuer_file_into_ckch(const char *path, char *buf, struct ckch_data *data, char **err)
{
	int ret = 1;
	BIO *in = NULL;
	X509 *issuer;

	if (buf) {
		/* reading from a buffer */
		in = BIO_new_mem_buf(buf, -1);
		if (in == NULL) {
			memprintf(err, "%sCan't allocate memory\n", err && *err ? *err : "");
			goto end;
		}

	} else {
		/* reading from a file */
		in = BIO_new(BIO_s_file());
		if (in == NULL)
			goto end;

		if (BIO_read_filename(in, path) <= 0)
			goto end;
	}

	issuer = PEM_read_bio_X509_AUX(in, NULL, NULL, NULL);
	if (!issuer) {
		memprintf(err, "%s'%s' cannot be read or parsed'.\n",
		          err && *err ? *err : "", path);
		goto end;
	}
	/* no error, fill data with new context, old context must be free */
	if (data->ocsp_issuer)
		X509_free(data->ocsp_issuer);
	data->ocsp_issuer = issuer;
	ret = 0;

end:

	ERR_clear_error();
	if (in)
		BIO_free(in);

	return ret;
}

/********************  ckch_store functions ***********************************
 * The ckch_store is a structure used to cache and index the SSL files used in
 * configuration
 */

/*
 * Free a ckch_store, its ckch, its instances and remove it from the ebtree
 */
void ckch_store_free(struct ckch_store *store)
{
	struct ckch_inst *inst, *inst_s;

	if (!store)
		return;

	list_for_each_entry_safe(inst, inst_s, &store->ckch_inst, by_ckchs) {
		ckch_inst_free(inst);
	}
	ebmb_delete(&store->node);

	ssl_sock_free_cert_key_and_chain_contents(store->data);
	ha_free(&store->data);

	/* free the ckch_conf content */
	ckch_conf_clean(&store->conf);

	free(store);
}

/*
 * create and initialize a ckch_store
 * <path> is the key name
 * <nmemb> is the number of store->ckch objects to allocate
 *
 * Return a ckch_store or NULL upon failure.
 */
struct ckch_store *ckch_store_new(const char *filename)
{
	struct ckch_store *store;
	int pathlen;

	pathlen = strlen(filename);
	store = calloc(1, sizeof(*store) + pathlen + 1);
	if (!store)
		return NULL;

	memcpy(store->path, filename, pathlen + 1);

	LIST_INIT(&store->ckch_inst);
	LIST_INIT(&store->crtlist_entry);

	store->data = calloc(1, sizeof(*store->data));
	if (!store->data)
		goto error;

	return store;
error:
	ckch_store_free(store);
	return NULL;
}

/* allocate and duplicate a ckch_store
 * Return a new ckch_store or NULL */
struct ckch_store *ckchs_dup(const struct ckch_store *src)
{
	struct ckch_store *dst;

	if (!src)
		return NULL;

	dst = ckch_store_new(src->path);
	if (!dst)
		return NULL;

	if (!ssl_sock_copy_cert_key_and_chain(src->data, dst->data))
		goto error;


	dst->conf.ocsp_update_mode = src->conf.ocsp_update_mode;

	return dst;

error:
	ckch_store_free(dst);

	return NULL;
}

/*
 * lookup a path into the ckchs tree.
 */
struct ckch_store *ckchs_lookup(char *path)
{
	struct ebmb_node *eb;

	eb = ebst_lookup(&ckchs_tree, path);
	if (!eb)
		return NULL;

	return ebmb_entry(eb, struct ckch_store, node);
}

/*
 * This function allocate a ckch_store and populate it with certificates from files.
 */
struct ckch_store *ckch_store_new_load_files_path(char *path, char **err)
{
	struct ckch_store *ckchs;

	ckchs = ckch_store_new(path);
	if (!ckchs) {
		memprintf(err, "%sunable to allocate memory.\n", err && *err ? *err : "");
		goto end;
	}

	if (ssl_sock_load_files_into_ckch(path, ckchs->data, err) == 1)
		goto end;

	ckchs->conf.used = CKCH_CONF_SET_EMPTY;

	/* insert into the ckchs tree */
	memcpy(ckchs->path, path, strlen(path) + 1);
	ebst_insert(&ckchs_tree, &ckchs->node);
	return ckchs;

end:
	ckch_store_free(ckchs);

	return NULL;
}

/*
 * This function allocate a ckch_store and populate it with certificates using
 * the ckch_conf structure.
 */
struct ckch_store *ckch_store_new_load_files_conf(char *name, struct ckch_conf *conf, char **err)
{
	struct ckch_store *ckchs;
	int cfgerr = ERR_NONE;
	char *tmpcrt = conf->crt;

	ckchs = ckch_store_new(name);
	if (!ckchs) {
		memprintf(err, "%sunable to allocate memory.\n", err && *err ? *err : "");
		goto end;
	}

	/* this is done for retro-compatibility. When no "filename" crt-store
	 * options were configured in a crt-list, try to load the files by
	 * auto-detecting them. */
	if ((conf->used == CKCH_CONF_SET_EMPTY || conf->used == CKCH_CONF_SET_CRTLIST) &&
		(!conf->key && !conf->ocsp && !conf->issuer && !conf->sctl)) {
		cfgerr = ssl_sock_load_files_into_ckch(conf->crt, ckchs->data, err);
		if (cfgerr & ERR_FATAL)
			goto end;
		/* set conf->crt to NULL so it's not erased */
		conf->crt = NULL;
	}

	/* load files using the ckch_conf */
	cfgerr = ckch_store_load_files(conf, ckchs, 0, err);
	if (cfgerr & ERR_FATAL)
		goto end;

	conf->crt = tmpcrt;

	/* insert into the ckchs tree */
	memcpy(ckchs->path, name, strlen(name) + 1);
	ebst_insert(&ckchs_tree, &ckchs->node);
	return ckchs;

end:
	ckch_store_free(ckchs);

	return NULL;
}

/********************  ckch_inst functions ******************************/

/* unlink a ckch_inst, free all SNIs, free the ckch_inst */
/* The caller must use the lock of the bind_conf if used with inserted SNIs */
void ckch_inst_free(struct ckch_inst *inst)
{
	struct sni_ctx *sni, *sni_s;
	struct ckch_inst_link_ref *link_ref, *link_ref_s;

	if (inst == NULL)
		return;

	list_for_each_entry_safe(sni, sni_s, &inst->sni_ctx, by_ckch_inst) {
		SSL_CTX_free(sni->ctx);
		LIST_DELETE(&sni->by_ckch_inst);
		ebmb_delete(&sni->name);
		free(sni);
	}
	SSL_CTX_free(inst->ctx);
	inst->ctx = NULL;
	LIST_DELETE(&inst->by_ckchs);
	LIST_DELETE(&inst->by_crtlist_entry);

	/* Free the cafile_link_refs list */
	list_for_each_entry_safe(link_ref, link_ref_s, &inst->cafile_link_refs, list) {
		if (link_ref->link && LIST_INLIST(&link_ref->link->list)) {
			/* Try to detach and free the ckch_inst_link only if it
			 * was attached, this way it can be used to loop from
			 * the caller */
			LIST_DEL_INIT(&link_ref->link->list);
			ha_free(&link_ref->link);
		}
		LIST_DELETE(&link_ref->list);
		free(link_ref);
	}

	free(inst);
}

/* Alloc and init a ckch_inst */
struct ckch_inst *ckch_inst_new()
{
	struct ckch_inst *ckch_inst;

	ckch_inst = calloc(1, sizeof *ckch_inst);
	if (!ckch_inst)
		return NULL;

	LIST_INIT(&ckch_inst->sni_ctx);
	LIST_INIT(&ckch_inst->by_ckchs);
	LIST_INIT(&ckch_inst->by_crtlist_entry);
	LIST_INIT(&ckch_inst->cafile_link_refs);

	return ckch_inst;
}


/********************  ssl_store functions ******************************/
struct eb_root cafile_tree = EB_ROOT;

/*
 * Returns the cafile_entry found in the cafile_tree indexed by the path 'path'.
 * If 'oldest_entry' is 1, returns the "original" cafile_entry (since
 * during a set cafile/commit cafile cycle there might be two entries for any
 * given path, the original one and the new one set via the CLI but not
 * committed yet).
 */
struct cafile_entry *ssl_store_get_cafile_entry(char *path, int oldest_entry)
{
	struct cafile_entry *ca_e = NULL;
	struct ebmb_node *eb;

	eb = ebst_lookup(&cafile_tree, path);
	while (eb) {
		ca_e = ebmb_entry(eb, struct cafile_entry, node);
		/* The ebst_lookup in a tree that has duplicates returns the
		 * oldest entry first. If we want the latest entry, we need to
		 * iterate over all the duplicates until we find the last one
		 * (in our case there should never be more than two entries for
		 * any given path). */
		if (oldest_entry)
			return ca_e;
		eb = ebmb_next_dup(eb);
	}
	return ca_e;
}

int ssl_store_add_uncommitted_cafile_entry(struct cafile_entry *entry)
{
	return (ebst_insert(&cafile_tree, &entry->node) != &entry->node);
}

X509_STORE* ssl_store_get0_locations_file(char *path)
{
	struct cafile_entry *ca_e = ssl_store_get_cafile_entry(path, 0);

	if (ca_e)
		return ca_e->ca_store;

	return NULL;
}

/* Create a cafile_entry object, without adding it to the cafile_tree. */
struct cafile_entry *ssl_store_create_cafile_entry(char *path, X509_STORE *store, enum cafile_type type)
{
	struct cafile_entry *ca_e;
	int pathlen;

	pathlen = strlen(path);

	ca_e = calloc(1, sizeof(*ca_e) + pathlen + 1);
	if (ca_e) {
		memcpy(ca_e->path, path, pathlen + 1);
		ca_e->ca_store = store;
		ca_e->type = type;
		LIST_INIT(&ca_e->ckch_inst_link);
	}
	return ca_e;
}


/* Duplicate a cafile_entry
 * Allocate the X509_STORE and copy the X509 and CRL inside.
 *
 * Return the newly allocated cafile_entry or NULL.
 *
 */
struct cafile_entry *ssl_store_dup_cafile_entry(struct cafile_entry *src)
{
	struct cafile_entry *dst = NULL;
	X509_STORE *store = NULL;
	STACK_OF(X509_OBJECT) *objs;
	int i;

	if (!src)
		return NULL;

	if (src->ca_store) {
		/* if there was a store in the src, copy it */
		store = X509_STORE_new();
		if (!store)
			goto err;

		objs = X509_STORE_get0_objects(src->ca_store);
		for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
			X509 *cert;
			X509_CRL *crl;

			cert = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
			if (cert) {
				if (X509_STORE_add_cert(store, cert) == 0) {
					/* only exits on error if the error is not about duplicate certificates */
					if (!(ERR_GET_REASON(ERR_get_error()) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
						goto err;
					}
				}

			}
			crl = X509_OBJECT_get0_X509_CRL(sk_X509_OBJECT_value(objs, i));
			if (crl) {
				if (X509_STORE_add_crl(store, crl) == 0) {
					/* only exits on error if the error is not about duplicate certificates */
					if (!(ERR_GET_REASON(ERR_get_error()) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
						goto err;
					}
				}

			}
		}
	}
	dst = ssl_store_create_cafile_entry(src->path, store, src->type);

	return dst;

err:
	X509_STORE_free(store);
	ha_free(&dst);

	return NULL;
}

/* Delete a cafile_entry. The caller is responsible from removing this entry
 * from the cafile_tree first if is was previously added into it. */
void ssl_store_delete_cafile_entry(struct cafile_entry *ca_e)
{
	struct ckch_inst_link *link, *link_s;
	if (!ca_e)
		return;

	X509_STORE_free(ca_e->ca_store);

	list_for_each_entry_safe(link, link_s, &ca_e->ckch_inst_link, list) {
		struct ckch_inst *inst = link->ckch_inst;
		struct ckch_inst_link_ref *link_ref, *link_ref_s;
		list_for_each_entry_safe(link_ref, link_ref_s, &inst->cafile_link_refs, list) {
			if (link_ref->link == link) {
				LIST_DELETE(&link_ref->list);
				free(link_ref);
				break;
			}
		}
		LIST_DELETE(&link->list);
		free(link);
	}

	free(ca_e);
}

/*
 * Fill a cafile_entry <ca_e> X509_STORE ca_e->store out of a buffer <cert_buf>
 * instead of out of a file. The <append> field should be set to 1 if you want
 * to keep the existing X509_STORE and append data to it.
 *
 * This function is used when the "set ssl ca-file" cli command is used.
 * It can parse CERTIFICATE sections as well as CRL ones.
 * Returns 0 in case of success, 1 otherwise.
 *
 * /!\ Warning: If there was an error the X509_STORE could have been modified so it's
 * better to not use it after a return 1.
 */
int ssl_store_load_ca_from_buf(struct cafile_entry *ca_e, char *cert_buf, int append)
{
	BIO *bio = NULL;
	STACK_OF(X509_INFO) *infos;
	X509_INFO *info;
	int i;
	int retval = 1;
	int retcert = 0;

	if (!ca_e)
		return 1;

	if (!append) {
		X509_STORE_free(ca_e->ca_store);
		ca_e->ca_store = NULL;
	}

	if (!ca_e->ca_store)
		ca_e->ca_store = X509_STORE_new();

	if (!ca_e->ca_store)
		goto end;

	bio = BIO_new_mem_buf(cert_buf, strlen(cert_buf));
	if (!bio)
		goto end;

	infos = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
	if (!infos)
		goto end;

	for (i = 0; i < sk_X509_INFO_num(infos) && !retcert; i++) {
		info = sk_X509_INFO_value(infos, i);

		/* X509_STORE_add_cert and X509_STORE_add_crl return 1 on success */
		if (info->x509)
			retcert = !X509_STORE_add_cert(ca_e->ca_store, info->x509);
		if (!retcert && info->crl)
			retcert = !X509_STORE_add_crl(ca_e->ca_store, info->crl);
	}

	/* return an error if we didn't compute all the X509_INFO or if there was none
	 * set to 0 if everything was right */
	if (!(retcert || (i != sk_X509_INFO_num(infos)) || (sk_X509_INFO_num(infos) == 0)))
		retval = 0;

	/* Cleanup */
	sk_X509_INFO_pop_free(infos, X509_INFO_free);

end:
	BIO_free(bio);

	return retval;
}

/*
 * Try to load a ca-file from disk into the ca-file cache.
 *  <shuterror> allows you to to stop emitting the errors.
 *  Return 0 upon error
 */
int __ssl_store_load_locations_file(char *path, int create_if_none, enum cafile_type type, int shuterror)
{
	X509_STORE *store = ssl_store_get0_locations_file(path);

	/* If this function is called by the CLI, we should not call the
	 * X509_STORE_load_locations function because it performs forbidden disk
	 * accesses. */
	if (!store && create_if_none) {
		STACK_OF(X509_OBJECT) *objs;
		int cert_count = 0;
		struct stat buf;
		struct cafile_entry *ca_e;
		const char *file = NULL;
		const char *dir = NULL;
		unsigned long e;

		store = X509_STORE_new();
		if (!store) {
			if (!shuterror)
				ha_alert("Cannot allocate memory!\n");
			goto err;
		}

		if (strcmp(path, "@system-ca") == 0) {
			dir = X509_get_default_cert_dir();
			if (!dir) {
				if (!shuterror)
					ha_alert("Couldn't get the system CA directory from X509_get_default_cert_dir().\n");
				goto err;
			}

		} else {

			if (stat(path, &buf) == -1) {
				if (!shuterror)
					ha_alert("Couldn't open the ca-file '%s' (%s).\n", path, strerror(errno));
				goto err;
			}

			if (S_ISDIR(buf.st_mode))
				dir = path;
			else
				file = path;
		}

		if (file) {
			if (!X509_STORE_load_locations(store, file, NULL)) {
				e = ERR_get_error();
				if (!shuterror)
					ha_alert("Couldn't open the ca-file '%s' (%s).\n", path, ERR_reason_error_string(e));
				goto err;
			}
		} else if (dir) {
			int n, i;
			struct dirent **de_list;

			n = scandir(dir, &de_list, 0, alphasort);
			if (n < 0)
				goto err;

			for (i= 0; i < n; i++) {
				char *end;
				struct dirent *de = de_list[i];
				BIO *in = NULL;
				X509 *ca = NULL;;

				ERR_clear_error();

				/* we try to load the files that would have
				 * been loaded in an hashed directory loaded by
				 * X509_LOOKUP_hash_dir, so according to "man 1
				 * c_rehash", we should load  ".pem", ".crt",
				 * ".cer", or ".crl". Files starting with a dot
				 * are ignored.
				 */
				end = strrchr(de->d_name, '.');
				if (!end || de->d_name[0] == '.' ||
				    (strcmp(end, ".pem") != 0 &&
				     strcmp(end, ".crt") != 0 &&
				     strcmp(end, ".cer") != 0 &&
				     strcmp(end, ".crl") != 0)) {
					free(de);
					continue;
				}
				in = BIO_new(BIO_s_file());
				if (in == NULL)
					goto scandir_err;

				chunk_printf(&trash, "%s/%s", dir, de->d_name);

				if (BIO_read_filename(in, trash.area) == 0)
					goto scandir_err;

				if (PEM_read_bio_X509_AUX(in, &ca, NULL, NULL) == NULL)
					goto scandir_err;

				if (X509_STORE_add_cert(store, ca) == 0) {
					/* only exits on error if the error is not about duplicate certificates */
					 if (!(ERR_GET_REASON(ERR_get_error()) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
						 goto scandir_err;
					 }
				}

				X509_free(ca);
				BIO_free(in);
				free(de);
				continue;

scandir_err:
				e = ERR_get_error();
				X509_free(ca);
				BIO_free(in);
				free(de);
				/* warn if it can load one of the files, but don't abort */
				if (!shuterror)
					ha_warning("ca-file: '%s' couldn't load '%s' (%s)\n", path, trash.area, ERR_reason_error_string(e));

			}
			free(de_list);
		} else {
			if (!shuterror)
				ha_alert("ca-file: couldn't load '%s'\n", path);
			goto err;
		}

		if (ssl_commit_crlfile_cb != NULL) {
			if (ssl_commit_crlfile_cb(path, store, NULL) == -1) {
				if (!shuterror)
					ha_alert("crl-file: couldn't load '%s'\n", path);
				goto err;
			}
		}

		objs = X509_STORE_get0_objects(store);
		cert_count = sk_X509_OBJECT_num(objs);
		if (cert_count == 0) {
			if (!shuterror)
				ha_warning("ca-file: 0 CA were loaded from '%s'\n", path);
		}
		ca_e = ssl_store_create_cafile_entry(path, store, type);
		if (!ca_e) {
			if (!shuterror)
				ha_alert("Cannot allocate memory!\n");
			goto err;
		}
		ebst_insert(&cafile_tree, &ca_e->node);
	}
	return (store != NULL);

err:
	X509_STORE_free(store);
	store = NULL;
	return 0;

}

int ssl_store_load_locations_file(char *path, int create_if_none, enum cafile_type type)
{
	return __ssl_store_load_locations_file(path, create_if_none, type, 0);
}

/*************************** CLI commands ***********************/

/* Type of SSL payloads that can be updated over the CLI */

struct cert_exts cert_exts[] = {
	{ "",        CERT_TYPE_PEM,      &ssl_sock_load_pem_into_ckch }, /* default mode, no extensions */
	{ "key",     CERT_TYPE_KEY,      &ssl_sock_load_key_into_ckch },
#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
	{ "ocsp",    CERT_TYPE_OCSP,     &ssl_sock_load_ocsp_response_from_file },
#endif
#ifdef HAVE_SSL_SCTL
	{ "sctl",    CERT_TYPE_SCTL,     &ssl_sock_load_sctl_from_file },
#endif
	{ "issuer",  CERT_TYPE_ISSUER,   &ssl_sock_load_issuer_file_into_ckch },
	{ NULL,      CERT_TYPE_MAX,      NULL },
};


/* release function of the  `show ssl cert' command */
static void cli_release_show_cert(struct appctx *appctx)
{
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
}

/* IO handler of "show ssl cert <filename>".
 * It makes use of a show_cert_ctx context, and ckchs_transaction in read-only.
 */
static int cli_io_handler_show_cert(struct appctx *appctx)
{
	struct show_cert_ctx *ctx = appctx->svcctx;
	struct buffer *trash = alloc_trash_chunk();
	struct ebmb_node *node;
	struct ckch_store *ckchs = NULL;

	if (trash == NULL)
		return 1;

	if (!ctx->old_ckchs && ckchs_transaction.old_ckchs) {
		ckchs = ckchs_transaction.old_ckchs;
		chunk_appendf(trash, "# transaction\n");
		chunk_appendf(trash, "*%s\n", ckchs->path);
		if (applet_putchk(appctx, trash) == -1)
			goto yield;
		ctx->old_ckchs = ckchs_transaction.old_ckchs;
	}

	if (!ctx->cur_ckchs) {
		chunk_appendf(trash, "# filename\n");
		node = ebmb_first(&ckchs_tree);
	} else {
		node = &ctx->cur_ckchs->node;
	}
	while (node) {
		ckchs = ebmb_entry(node, struct ckch_store, node);
		chunk_appendf(trash, "%s\n", ckchs->path);

		node = ebmb_next(node);
		if (applet_putchk(appctx, trash) == -1)
			goto yield;
	}

	ctx->cur_ckchs = NULL;
	free_trash_chunk(trash);
	return 1;
yield:

	free_trash_chunk(trash);
	ctx->cur_ckchs = ckchs;
	return 0; /* should come back */
}

/*
 * Extract and format the DNS SAN extensions and copy result into a chuink
 * Return 0;
 */
#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
static int ssl_sock_get_san_oneline(X509 *cert, struct buffer *out)
{
	int i;
	char *str;
	STACK_OF(GENERAL_NAME) *names = NULL;

	names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
	if (names) {
		for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
			GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
			if (i > 0)
				chunk_appendf(out, ", ");
			if (name->type == GEN_DNS) {
				if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
					chunk_appendf(out, "DNS:%s", str);
					OPENSSL_free(str);
				}
			}
		}
		sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
	}
	return 0;
}
#endif

/*
 * Build the ckch_inst_link that will be chained in the CA file entry and the
 * corresponding ckch_inst_link_ref that will be chained in the ckch instance.
 * Return 0 in case of success.
 */
static int do_chain_inst_and_cafile(struct cafile_entry *cafile_entry, struct ckch_inst *ckch_inst)
{
	struct ckch_inst_link *new_link;
	if (!LIST_ISEMPTY(&cafile_entry->ckch_inst_link)) {
		struct ckch_inst_link *link = LIST_ELEM(cafile_entry->ckch_inst_link.n,
							typeof(link), list);
		/* Do not add multiple references to the same
		 * instance in a cafile_entry */
		if (link->ckch_inst == ckch_inst) {
			return 1;
		}
	}

	new_link = calloc(1, sizeof(*new_link));
	if (new_link) {
		struct ckch_inst_link_ref *new_link_ref = calloc(1, sizeof(*new_link_ref));
		if (!new_link_ref) {
			free(new_link);
			return 1;
		}

		new_link->ckch_inst = ckch_inst;
		new_link_ref->link = new_link;
		LIST_INIT(&new_link->list);
		LIST_INIT(&new_link_ref->list);

		LIST_APPEND(&cafile_entry->ckch_inst_link, &new_link->list);
		LIST_APPEND(&ckch_inst->cafile_link_refs, &new_link_ref->list);
	}

	return 0;
}


/*
 * Link a CA file tree entry to the ckch instance that uses it.
 * To determine if and which CA file tree entries need to be linked to the
 * instance, we follow the same logic performed in ssl_sock_prepare_ctx when
 * processing the verify option.
 * This function works for a frontend as well as for a backend, depending on the
 * configuration parameters given (bind_conf or server).
 */
void ckch_inst_add_cafile_link(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf,
			       struct ssl_bind_conf *ssl_conf, const struct server *srv)
{
	int verify = SSL_VERIFY_NONE;

	if (srv) {

		if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
			verify = SSL_VERIFY_PEER;
		switch (srv->ssl_ctx.verify) {
		case SSL_SOCK_VERIFY_NONE:
			verify = SSL_VERIFY_NONE;
			break;
		case SSL_SOCK_VERIFY_REQUIRED:
			verify = SSL_VERIFY_PEER;
			break;
		}
	}
	else {
		switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
		case SSL_SOCK_VERIFY_NONE:
			verify = SSL_VERIFY_NONE;
			break;
		case SSL_SOCK_VERIFY_OPTIONAL:
			verify = SSL_VERIFY_PEER;
			break;
		case SSL_SOCK_VERIFY_REQUIRED:
			verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
			break;
		}
	}

	if (verify & SSL_VERIFY_PEER) {
		struct cafile_entry *ca_file_entry = NULL;
		struct cafile_entry *ca_verify_file_entry = NULL;
		struct cafile_entry *crl_file_entry = NULL;
		if (srv) {
			if (srv->ssl_ctx.ca_file) {
				ca_file_entry = ssl_store_get_cafile_entry(srv->ssl_ctx.ca_file, 0);

			}
			if (srv->ssl_ctx.crl_file) {
				crl_file_entry = ssl_store_get_cafile_entry(srv->ssl_ctx.crl_file, 0);
			}
		}
		else {
			char *ca_file = (ssl_conf && ssl_conf->ca_file) ? ssl_conf->ca_file : bind_conf->ssl_conf.ca_file;
			char *ca_verify_file = (ssl_conf && ssl_conf->ca_verify_file) ? ssl_conf->ca_verify_file : bind_conf->ssl_conf.ca_verify_file;
			char *crl_file = (ssl_conf && ssl_conf->crl_file) ? ssl_conf->crl_file : bind_conf->ssl_conf.crl_file;

			if (ca_file)
				ca_file_entry = ssl_store_get_cafile_entry(ca_file, 0);
			if (ca_verify_file)
				ca_verify_file_entry = ssl_store_get_cafile_entry(ca_verify_file, 0);
			if (crl_file)
				crl_file_entry = ssl_store_get_cafile_entry(crl_file, 0);
		}

		if (ca_file_entry) {
			/* If we have a ckch instance that is not already in the
			 * cafile_entry's list, add it to it. */
			if (do_chain_inst_and_cafile(ca_file_entry, ckch_inst))
				return;

		}
		if (ca_verify_file_entry && (ca_file_entry != ca_verify_file_entry)) {
			/* If we have a ckch instance that is not already in the
			 * cafile_entry's list, add it to it. */
			if (do_chain_inst_and_cafile(ca_verify_file_entry, ckch_inst))
				return;
		}
		if (crl_file_entry) {
			/* If we have a ckch instance that is not already in the
			 * cafile_entry's list, add it to it. */
			if (do_chain_inst_and_cafile(crl_file_entry, ckch_inst))
				return;
		}
	}
}



static int show_cert_detail(X509 *cert, STACK_OF(X509) *chain, struct buffer *out)
{
	BIO *bio = NULL;
	struct buffer *tmp = alloc_trash_chunk();
	int i;
	int write = -1;
	unsigned int len = 0;
	X509_NAME *name = NULL;

	if (!tmp)
		return -1;

	if (!cert)
		goto end;

	if (chain == NULL) {
		struct issuer_chain *issuer;
		issuer = ssl_get0_issuer_chain(cert);
		if (issuer) {
			chain = issuer->chain;
			chunk_appendf(out, "Chain Filename: ");
			chunk_appendf(out, "%s\n", issuer->path);
		}
	}
	chunk_appendf(out, "Serial: ");
	if (ssl_sock_get_serial(cert, tmp) == -1)
		goto end;
	dump_binary(out, tmp->area, tmp->data);
	chunk_appendf(out, "\n");

	chunk_appendf(out, "notBefore: ");
	chunk_reset(tmp);
	if ((bio = BIO_new(BIO_s_mem())) ==  NULL)
		goto end;
	if (ASN1_TIME_print(bio, X509_getm_notBefore(cert)) == 0)
		goto end;
	write = BIO_read(bio, tmp->area, tmp->size-1);
	tmp->area[write] = '\0';
	BIO_free(bio);
	bio = NULL;
	chunk_appendf(out, "%s\n", tmp->area);

	chunk_appendf(out, "notAfter: ");
	chunk_reset(tmp);
	if ((bio = BIO_new(BIO_s_mem())) == NULL)
		goto end;
	if (ASN1_TIME_print(bio, X509_getm_notAfter(cert)) == 0)
		goto end;
	if ((write = BIO_read(bio, tmp->area, tmp->size-1)) <= 0)
		goto end;
	tmp->area[write] = '\0';
	BIO_free(bio);
	bio = NULL;
	chunk_appendf(out, "%s\n", tmp->area);

#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
	chunk_appendf(out, "Subject Alternative Name: ");
	if (ssl_sock_get_san_oneline(cert, out) == -1)
		goto end;
	*(out->area + out->data) = '\0';
	chunk_appendf(out, "\n");
#endif
	chunk_reset(tmp);
	chunk_appendf(out, "Algorithm: ");
	if (cert_get_pkey_algo(cert, tmp) == 0)
		goto end;
	chunk_appendf(out, "%s\n", tmp->area);

	chunk_reset(tmp);
	chunk_appendf(out, "SHA1 FingerPrint: ");
	if (X509_digest(cert, EVP_sha1(), (unsigned char *) tmp->area, &len) == 0)
		goto end;
	tmp->data = len;
	dump_binary(out, tmp->area, tmp->data);
	chunk_appendf(out, "\n");

	chunk_appendf(out, "Subject: ");
	if ((name = X509_get_subject_name(cert)) == NULL)
		goto end;
	if ((ssl_sock_get_dn_oneline(name, tmp)) == -1)
		goto end;
	*(tmp->area + tmp->data) = '\0';
	chunk_appendf(out, "%s\n", tmp->area);

	chunk_appendf(out, "Issuer: ");
	if ((name = X509_get_issuer_name(cert)) == NULL)
		goto end;
	if ((ssl_sock_get_dn_oneline(name, tmp)) == -1)
		goto end;
	*(tmp->area + tmp->data) = '\0';
	chunk_appendf(out, "%s\n", tmp->area);

	/* Displays subject of each certificate in the chain */
	for (i = 0; i < sk_X509_num(chain); i++) {
		X509 *ca = sk_X509_value(chain, i);

		chunk_appendf(out, "Chain Subject: ");
		if ((name = X509_get_subject_name(ca)) == NULL)
			goto end;
		if ((ssl_sock_get_dn_oneline(name, tmp)) == -1)
			goto end;
		*(tmp->area + tmp->data) = '\0';
		chunk_appendf(out, "%s\n", tmp->area);

		chunk_appendf(out, "Chain Issuer: ");
		if ((name = X509_get_issuer_name(ca)) == NULL)
			goto end;
		if ((ssl_sock_get_dn_oneline(name, tmp)) == -1)
			goto end;
		*(tmp->area + tmp->data) = '\0';
		chunk_appendf(out, "%s\n", tmp->area);
	}

end:
	if (bio)
		BIO_free(bio);
	free_trash_chunk(tmp);

	return 0;
}

/*
 * Dump the OCSP certificate key (if it exists) of certificate <ckch> into
 * buffer <out>.
 * Returns 0 in case of success.
 */
static int ckch_store_show_ocsp_certid(struct ckch_store *ckch_store, struct buffer *out)
{
#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
	unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH] = {};
	unsigned int key_length = 0;
	int i;

	if (ssl_ocsp_build_response_key(ckch_store->data->ocsp_cid, (unsigned char*)key, &key_length) >= 0) {
		/* Dump the CERTID info */
		chunk_appendf(out, "OCSP Response Key: ");
		for (i = 0; i < key_length; ++i) {
			chunk_appendf(out, "%02x", key[i]);
		}
		chunk_appendf(out, "\n");
	}
#endif

	return 0;
}


/* IO handler of the details "show ssl cert <filename>".
 * It uses a struct show_cert_ctx and ckchs_transaction in read-only.
 */
static int cli_io_handler_show_cert_detail(struct appctx *appctx)
{
	struct show_cert_ctx *ctx = appctx->svcctx;
	struct ckch_store *ckchs = ctx->cur_ckchs;
	struct buffer *out = alloc_trash_chunk();
	int retval = 0;

	if (!out)
		goto end_no_putchk;

	chunk_appendf(out, "Filename: ");
	if (ckchs == ckchs_transaction.new_ckchs)
		chunk_appendf(out, "*");
	chunk_appendf(out, "%s\n", ckchs->path);

	chunk_appendf(out, "Status: ");
	if (ckchs->data->cert == NULL)
		chunk_appendf(out, "Empty\n");
	else if (LIST_ISEMPTY(&ckchs->ckch_inst))
		chunk_appendf(out, "Unused\n");
	else
		chunk_appendf(out, "Used\n");

	retval = show_cert_detail(ckchs->data->cert, ckchs->data->chain, out);
	if (retval < 0)
		goto end_no_putchk;
	else if (retval)
		goto end;

	ckch_store_show_ocsp_certid(ckchs, out);

end:
	if (applet_putchk(appctx, out) == -1)
		goto yield;

end_no_putchk:
	free_trash_chunk(out);
	return 1;
yield:
	free_trash_chunk(out);
	return 0; /* should come back */
}


/* IO handler of the details "show ssl cert <filename.ocsp>".
 * It uses a show_cert_ctx.
 */
static int cli_io_handler_show_cert_ocsp_detail(struct appctx *appctx)
{
#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
	struct show_cert_ctx *ctx = appctx->svcctx;
	struct ckch_store *ckchs = ctx->cur_ckchs;
	struct buffer *out = alloc_trash_chunk();
	int from_transaction = ctx->transaction;

	if (!out)
		goto end_no_putchk;

	/* If we try to display an ongoing transaction's OCSP response, we
	 * need to dump the ckch's ocsp_response buffer directly.
	 * Otherwise, we must rebuild the certificate's certid in order to
	 * look for the current OCSP response in the tree. */
	if (from_transaction && ckchs->data->ocsp_response) {
		if (ssl_ocsp_response_print(ckchs->data->ocsp_response, out))
			goto end_no_putchk;
	}
	else {
		unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH] = {};
		unsigned int key_length = 0;

		if (ssl_ocsp_build_response_key(ckchs->data->ocsp_cid, (unsigned char*)key, &key_length) < 0)
			goto end_no_putchk;

		if (ssl_get_ocspresponse_detail(key, out))
			goto end_no_putchk;
	}

	if (applet_putchk(appctx, out) == -1)
		goto yield;

end_no_putchk:
	free_trash_chunk(out);
	return 1;
yield:
	free_trash_chunk(out);
	return 0; /* should come back */
#else
	return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
#endif
}

/* parsing function for 'show ssl cert [certfile]' */
static int cli_parse_show_cert(char **args, char *payload, struct appctx *appctx, void *private)
{
	struct show_cert_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
	struct ckch_store *ckchs;

	if (!cli_has_level(appctx, ACCESS_LVL_OPER))
		return cli_err(appctx, "Can't allocate memory!\n");

	/* The operations on the CKCH architecture are locked so we can
	 * manipulate ckch_store and ckch_inst */
	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't show!\nOperations on certificates are currently locked!\n");

	/* check if there is a certificate to lookup */
	if (*args[3]) {
		int show_ocsp_detail = 0;
		int from_transaction = 0;
		char *end;

		/* We manage the special case "certname.ocsp" through which we
		 * can show the details of an OCSP response. */
		end = strrchr(args[3], '.');
		if (end && strcmp(end+1, "ocsp") == 0) {
			*end = '\0';
			show_ocsp_detail = 1;
		}

		if (*args[3] == '*') {
			from_transaction = 1;
			if (!ckchs_transaction.new_ckchs)
				goto error;

			ckchs = ckchs_transaction.new_ckchs;

			if (strcmp(args[3] + 1, ckchs->path) != 0)
				goto error;

		} else {
			if ((ckchs = ckchs_lookup(args[3])) == NULL)
				goto error;

		}

		ctx->cur_ckchs = ckchs;
		/* use the IO handler that shows details */
		if (show_ocsp_detail) {
			ctx->transaction = from_transaction;
			appctx->io_handler = cli_io_handler_show_cert_ocsp_detail;
		}
		else
			appctx->io_handler = cli_io_handler_show_cert_detail;
	}

	return 0;

error:
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	return cli_err(appctx, "Can't display the certificate: Not found or the certificate is a bundle!\n");
}

/* release function of the  `set ssl cert' command, free things and unlock the spinlock */
static void cli_release_commit_cert(struct appctx *appctx)
{
	struct commit_cert_ctx *ctx = appctx->svcctx;

	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	/* free every new sni_ctx and the new store, which are not in the trees so no spinlock there */
	if (ctx->new_ckchs)
		ckch_store_free(ctx->new_ckchs);
	ha_free(&ctx->err);
}


/*
 * Rebuild a new instance 'new_inst' based on an old instance 'ckchi' and a
 * specific ckch_store.
 * Returns 0 in case of success, 1 otherwise.
 */
int ckch_inst_rebuild(struct ckch_store *ckch_store, struct ckch_inst *ckchi,
                      struct ckch_inst **new_inst, char **err)
{
	int retval = 0;
	int errcode = 0;
	struct sni_ctx *sc0, *sc0s;
	char **sni_filter = NULL;
	int fcount = 0;

	if (ckchi->crtlist_entry) {
		sni_filter = ckchi->crtlist_entry->filters;
		fcount = ckchi->crtlist_entry->fcount;
	}

	if (ckchi->is_server_instance)
		errcode |= ckch_inst_new_load_srv_store(ckch_store->path, ckch_store, new_inst, err);
	else
		errcode |= ckch_inst_new_load_store(ckch_store->path, ckch_store, ckchi->bind_conf, ckchi->ssl_conf, sni_filter, fcount, ckchi->is_default, new_inst, err);

	if (errcode & ERR_CODE)
		return 1;

	/* if the previous ckchi was used as the default */
	if (ckchi->is_default)
		(*new_inst)->is_default = 1;

	(*new_inst)->is_server_instance = ckchi->is_server_instance;
	(*new_inst)->server = ckchi->server;
	/* Create a new SSL_CTX and link it to the new instance. */
	if ((*new_inst)->is_server_instance) {
		retval = ssl_sock_prep_srv_ctx_and_inst(ckchi->server, (*new_inst)->ctx, (*new_inst));
		if (retval)
			return 1;
	}

	/* create the link to the crtlist_entry */
	(*new_inst)->crtlist_entry = ckchi->crtlist_entry;

	/* we need to initialize the SSL_CTX generated */
	/* this iterate on the newly generated SNIs in the new instance to prepare their SSL_CTX */
	list_for_each_entry_safe(sc0, sc0s, &(*new_inst)->sni_ctx, by_ckch_inst) {
		if (!sc0->order) { /* we initialized only the first SSL_CTX because it's the same in the other sni_ctx's */
			errcode |= ssl_sock_prep_ctx_and_inst(ckchi->bind_conf, ckchi->ssl_conf, sc0->ctx, *new_inst, err);
			if (errcode & ERR_CODE)
				return 1;
		}
	}

	return 0;
}

/*
 * Load all the new SNIs of a newly built ckch instance in the trees, or replace
 * a server's main ckch instance.
 */
static void __ssl_sock_load_new_ckch_instance(struct ckch_inst *ckchi)
{
	/* The bind_conf will be null on server ckch_instances. */
	if (ckchi->is_server_instance) {
		int i;
		/* a lock is needed here since we have to free the SSL cache */
		HA_RWLOCK_WRLOCK(SSL_SERVER_LOCK, &ckchi->server->ssl_ctx.lock);
		/* free the server current SSL_CTX */
		SSL_CTX_free(ckchi->server->ssl_ctx.ctx);
		/* Actual ssl context update */
		SSL_CTX_up_ref(ckchi->ctx);
		ckchi->server->ssl_ctx.ctx = ckchi->ctx;
		ckchi->server->ssl_ctx.inst = ckchi;

		/* flush the session cache of the server */
		for (i = 0; i < global.nbthread; i++) {
			ha_free(&ckchi->server->ssl_ctx.reused_sess[i].sni);
			ha_free(&ckchi->server->ssl_ctx.reused_sess[i].ptr);
		}
		HA_RWLOCK_WRUNLOCK(SSL_SERVER_LOCK, &ckchi->server->ssl_ctx.lock);

	} else {
		HA_RWLOCK_WRLOCK(SNI_LOCK, &ckchi->bind_conf->sni_lock);
		ssl_sock_load_cert_sni(ckchi, ckchi->bind_conf);
		HA_RWLOCK_WRUNLOCK(SNI_LOCK, &ckchi->bind_conf->sni_lock);
	}
}

/*
 * Delete a ckch instance that was replaced after a CLI command.
 */
static void __ckch_inst_free_locked(struct ckch_inst *ckchi)
{
	if (ckchi->is_server_instance) {
		/* no lock for servers */
		ckch_inst_free(ckchi);
	} else {
		struct bind_conf __maybe_unused *bind_conf = ckchi->bind_conf;

		HA_RWLOCK_WRLOCK(SNI_LOCK, &bind_conf->sni_lock);
		ckch_inst_free(ckchi);
		HA_RWLOCK_WRUNLOCK(SNI_LOCK, &bind_conf->sni_lock);
	}
}

/* Replace a ckch_store in the ckch tree and insert the whole dependencies,
* then free the previous dependencies and store.
* Used in the case of a certificate update.
*
* Every dependencies must allocated before using this function.
*
* This function can't fail as it only update pointers, and does not alloc anything.
*
* /!\ This function must be used under the ckch lock. /!\
*
* - Insert every dependencies (SNI, crtlist_entry, ckch_inst, etc)
* - Delete the old ckch_store from the tree
* - Insert the new ckch_store
* - Free the old dependencies and the old ckch_store
*/
void ckch_store_replace(struct ckch_store *old_ckchs, struct ckch_store *new_ckchs)
{
	struct crtlist_entry *entry;
	struct ckch_inst *ckchi, *ckchis;

	LIST_SPLICE(&new_ckchs->crtlist_entry, &old_ckchs->crtlist_entry);
	list_for_each_entry(entry, &new_ckchs->crtlist_entry, by_ckch_store) {
		ebpt_delete(&entry->node);
		/* change the ptr and reinsert the node */
		entry->node.key = new_ckchs;
		ebpt_insert(&entry->crtlist->entries, &entry->node);
	}
	/* insert the new ckch_insts in the crtlist_entry */
	list_for_each_entry(ckchi, &new_ckchs->ckch_inst, by_ckchs) {
		if (ckchi->crtlist_entry)
			LIST_INSERT(&ckchi->crtlist_entry->ckch_inst, &ckchi->by_crtlist_entry);
	}
	/* First, we insert every new SNIs in the trees, also replace the default_ctx */
	list_for_each_entry_safe(ckchi, ckchis, &new_ckchs->ckch_inst, by_ckchs) {
		__ssl_sock_load_new_ckch_instance(ckchi);
	}
	/* delete the old sni_ctx, the old ckch_insts and the ckch_store */
	list_for_each_entry_safe(ckchi, ckchis, &old_ckchs->ckch_inst, by_ckchs) {
		__ckch_inst_free_locked(ckchi);
	}

	ckch_store_free(old_ckchs);
	ebst_insert(&ckchs_tree, &new_ckchs->node);
}


/*
 * This function tries to create the new ckch_inst and their SNIs
 *
 * /!\ don't forget to update __hlua_ckch_commit() if you changes things there. /!\
 */
static int cli_io_handler_commit_cert(struct appctx *appctx)
{
	struct commit_cert_ctx *ctx = appctx->svcctx;
	int y = 0;
	struct ckch_store *old_ckchs, *new_ckchs = NULL;
	struct ckch_inst *ckchi;

	usermsgs_clr("CLI");
	while (1) {
		switch (ctx->state) {
			case CERT_ST_INIT:
				/* This state just print the update message */
				chunk_printf(&trash, "Committing %s", ckchs_transaction.path);
				if (applet_putchk(appctx, &trash) == -1)
					goto yield;

				ctx->state = CERT_ST_GEN;
				__fallthrough;
			case CERT_ST_GEN:
				/*
				 * This state generates the ckch instances with their
				 * sni_ctxs and SSL_CTX.
				 *
				 * Since the SSL_CTX generation can be CPU consumer, we
				 * yield every 10 instances.
				 */

				old_ckchs = ctx->old_ckchs;
				new_ckchs = ctx->new_ckchs;

				/* get the next ckchi to regenerate */
				ckchi = ctx->next_ckchi;
				/* we didn't start yet, set it to the first elem */
				if (ckchi == NULL)
					ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);

				/* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
				list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
					struct ckch_inst *new_inst;

					/* save the next ckchi to compute in case of yield */
					ctx->next_ckchi = ckchi;

					/* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
					if (y >= 10) {
						applet_have_more_data(appctx); /* let's come back later */
						goto yield;
					}

					/* display one dot per new instance */
					if (applet_putstr(appctx, ".") == -1)
						goto yield;

					ctx->err = NULL;
					if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &ctx->err)) {
						ctx->state = CERT_ST_ERROR;
						goto error;
					}

					/* link the new ckch_inst to the duplicate */
					LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
					y++;
				}
				ctx->state = CERT_ST_INSERT;
				__fallthrough;
			case CERT_ST_INSERT:
				/* The generation is finished, we can insert everything */

				old_ckchs = ctx->old_ckchs;
				new_ckchs = ctx->new_ckchs;

				/* insert everything and remove the previous objects */
				ckch_store_replace(old_ckchs, new_ckchs);
				ctx->new_ckchs = ctx->old_ckchs = NULL;
				ctx->state = CERT_ST_SUCCESS;
				__fallthrough;
			case CERT_ST_SUCCESS:
				chunk_printf(&trash, "\n%sSuccess!\n", usermsgs_str());
				if (applet_putchk(appctx, &trash) == -1)
					goto yield;
				ctx->state = CERT_ST_FIN;
				__fallthrough;
			case CERT_ST_FIN:
				/* we achieved the transaction, we can set everything to NULL */
				ckchs_transaction.new_ckchs = NULL;
				ckchs_transaction.old_ckchs = NULL;
				ckchs_transaction.path = NULL;
				goto end;

			case CERT_ST_ERROR:
			  error:
				chunk_printf(&trash, "\n%s%sFailed!\n", usermsgs_str(), ctx->err);
				if (applet_putchk(appctx, &trash) == -1)
					goto yield;
				ctx->state = CERT_ST_FIN;
				break;
		}
	}
end:
	usermsgs_clr(NULL);
	/* success: call the release function and don't come back */
	return 1;

yield:
	usermsgs_clr(NULL);
	return 0; /* should come back */
}

/*
 * Parsing function of 'commit ssl cert'
 */
static int cli_parse_commit_cert(char **args, char *payload, struct appctx *appctx, void *private)
{
	struct commit_cert_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
	char *err = NULL;

	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
		return 1;

	if (!*args[3])
		return cli_err(appctx, "'commit ssl cert' expects a filename\n");

	/* The operations on the CKCH architecture are locked so we can
	 * manipulate ckch_store and ckch_inst */
	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't commit the certificate!\nOperations on certificates are currently locked!\n");

	if (!ckchs_transaction.path) {
		memprintf(&err, "No ongoing transaction! !\n");
		goto error;
	}

	if (strcmp(ckchs_transaction.path, args[3]) != 0) {
		memprintf(&err, "The ongoing transaction is about '%s' but you are trying to set '%s'\n", ckchs_transaction.path, args[3]);
		goto error;
	}

	/* if a certificate is here, a private key must be here too */
	if (ckchs_transaction.new_ckchs->data->cert && !ckchs_transaction.new_ckchs->data->key) {
		memprintf(&err, "The transaction must contain at least a certificate and a private key!\n");
		goto error;
	}

	if (!X509_check_private_key(ckchs_transaction.new_ckchs->data->cert, ckchs_transaction.new_ckchs->data->key)) {
		memprintf(&err, "inconsistencies between private key and certificate loaded '%s'.\n", ckchs_transaction.path);
		goto error;
	}

	/* init the appctx structure */
	ctx->state = CERT_ST_INIT;
	ctx->next_ckchi = NULL;
	ctx->new_ckchs = ckchs_transaction.new_ckchs;
	ctx->old_ckchs = ckchs_transaction.old_ckchs;

	/* we don't unlock there, it will be unlock after the IO handler, in the release handler */
	return 0;

error:

	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	err = memprintf(&err, "%sCan't commit %s!\n", err ? err : "", args[3]);

	return cli_dynerr(appctx, err);
}




/*
 * Parsing function of `set ssl cert`, it updates or creates a temporary ckch.
 * It uses a set_cert_ctx context, and ckchs_transaction under a lock.
 */
static int cli_parse_set_cert(char **args, char *payload, struct appctx *appctx, void *private)
{
	struct ckch_store *new_ckchs = NULL;
	struct ckch_store *old_ckchs = NULL;
	char *err = NULL;
	int i;
	int errcode = 0;
	char *end;
	struct cert_exts *cert_ext = &cert_exts[0]; /* default one, PEM */
	struct ckch_data *data;
	struct buffer *buf;

	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
		return 1;

	if (!*args[3] || !payload)
		return cli_err(appctx, "'set ssl cert' expects a filename and a certificate as a payload\n");

	/* The operations on the CKCH architecture are locked so we can
	 * manipulate ckch_store and ckch_inst */
	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't update the certificate!\nOperations on certificates are currently locked!\n");

	if ((buf = alloc_trash_chunk()) == NULL) {
		memprintf(&err, "%sCan't allocate memory\n", err ? err : "");
		errcode |= ERR_ALERT | ERR_FATAL;
		goto end;
	}

	if (!chunk_strcpy(buf, args[3])) {
		memprintf(&err, "%sCan't allocate memory\n", err ? err : "");
		errcode |= ERR_ALERT | ERR_FATAL;
		goto end;
	}

	/* check which type of file we want to update */
	for (i = 0; cert_exts[i].ext != NULL; i++) {
		end = strrchr(buf->area, '.');
		if (end && *cert_exts[i].ext && (strcmp(end + 1, cert_exts[i].ext) == 0)) {
			*end = '\0';
			buf->data = strlen(buf->area);
			cert_ext = &cert_exts[i];
			break;
		}
	}

	/* if there is an ongoing transaction */
	if (ckchs_transaction.path) {
		/* if there is an ongoing transaction, check if this is the same file */
		if (strcmp(ckchs_transaction.path, buf->area) != 0) {
			/* we didn't find the transaction, must try more cases below */

			/* if the del-ext option is activated we should try to take a look at a ".crt" too. */
			if (cert_ext->type != CERT_TYPE_PEM && global_ssl.extra_files_noext) {
				if (!chunk_strcat(buf, ".crt")) {
					memprintf(&err, "%sCan't allocate memory\n", err ? err : "");
					errcode |= ERR_ALERT | ERR_FATAL;
					goto end;
				}

				if (strcmp(ckchs_transaction.path, buf->area) != 0) {
					/* remove .crt of the error message */
					*(b_orig(buf) + b_data(buf) + strlen(".crt")) = '\0';
					b_sub(buf, strlen(".crt"));

					memprintf(&err, "The ongoing transaction is about '%s' but you are trying to set '%s'\n", ckchs_transaction.path, buf->area);
					errcode |= ERR_ALERT | ERR_FATAL;
					goto end;
				}
			}
		}

		old_ckchs = ckchs_transaction.new_ckchs;

	} else {

		/* lookup for the certificate in the tree */
		old_ckchs = ckchs_lookup(buf->area);

		if (!old_ckchs) {
			/* if the del-ext option is activated we should try to take a look at a ".crt" too. */
			if (cert_ext->type != CERT_TYPE_PEM && global_ssl.extra_files_noext) {
				if (!chunk_strcat(buf, ".crt")) {
					memprintf(&err, "%sCan't allocate memory\n", err ? err : "");
					errcode |= ERR_ALERT | ERR_FATAL;
					goto end;
				}
				old_ckchs = ckchs_lookup(buf->area);
			}
		}
	}

	if (!old_ckchs) {
		memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!\n",
		          err ? err : "");
		errcode |= ERR_ALERT | ERR_FATAL;
		goto end;
	}

	/* duplicate the ckch store */
	new_ckchs = ckchs_dup(old_ckchs);
	if (!new_ckchs) {
		memprintf(&err, "%sCannot allocate memory!\n",
			  err ? err : "");
		errcode |= ERR_ALERT | ERR_FATAL;
		goto end;
	}

	/* Reset the OCSP CID */
	if (cert_ext->type == CERT_TYPE_PEM || cert_ext->type == CERT_TYPE_KEY ||
	    cert_ext->type == CERT_TYPE_ISSUER) {
		OCSP_CERTID_free(new_ckchs->data->ocsp_cid);
		new_ckchs->data->ocsp_cid = NULL;
	}

	data = new_ckchs->data;

	/* apply the change on the duplicate */
	if (cert_ext->load(buf->area, payload, data, &err) != 0) {
		memprintf(&err, "%sCan't load the payload\n", err ? err : "");
		errcode |= ERR_ALERT | ERR_FATAL;
		goto end;
	}

	/* we succeed, we can save the ckchs in the transaction */

	/* if there wasn't a transaction, update the old ckchs */
	if (!ckchs_transaction.old_ckchs) {
		ckchs_transaction.old_ckchs = old_ckchs;
		ckchs_transaction.path = old_ckchs->path;
		err = memprintf(&err, "Transaction created for certificate %s!\n", ckchs_transaction.path);
	} else {
		err = memprintf(&err, "Transaction updated for certificate %s!\n", ckchs_transaction.path);

	}

	/* free the previous ckchs if there was a transaction */
	ckch_store_free(ckchs_transaction.new_ckchs);

	ckchs_transaction.new_ckchs = new_ckchs;


	/* creates the SNI ctxs later in the IO handler */

end:
	free_trash_chunk(buf);

	if (errcode & ERR_CODE) {
		ckch_store_free(new_ckchs);
		HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
		return cli_dynerr(appctx, memprintf(&err, "%sCan't update %s!\n", err ? err : "", args[3]));
	} else {
		HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
		return cli_dynmsg(appctx, LOG_NOTICE, err);
	}
	/* TODO: handle the ERR_WARN which are not handled because of the io_handler */
}

/* parsing function of 'abort ssl cert' */
static int cli_parse_abort_cert(char **args, char *payload, struct appctx *appctx, void *private)
{
	char *err = NULL;

	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
		return 1;

	if (!*args[3])
		return cli_err(appctx, "'abort ssl cert' expects a filename\n");

	/* The operations on the CKCH architecture are locked so we can
	 * manipulate ckch_store and ckch_inst */
	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't abort!\nOperations on certificates are currently locked!\n");

	if (!ckchs_transaction.path) {
		memprintf(&err, "No ongoing transaction!\n");
		goto error;
	}

	if (strcmp(ckchs_transaction.path, args[3]) != 0) {
		memprintf(&err, "The ongoing transaction is about '%s' but you are trying to abort a transaction for '%s'\n", ckchs_transaction.path, args[3]);
		goto error;
	}

	/* Only free the ckchs there, because the SNI and instances were not generated yet */
	ckch_store_free(ckchs_transaction.new_ckchs);
	ckchs_transaction.new_ckchs = NULL;
	ckchs_transaction.old_ckchs = NULL;
	ckchs_transaction.path = NULL;

	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);

	err = memprintf(&err, "Transaction aborted for certificate '%s'!\n", args[3]);
	return cli_dynmsg(appctx, LOG_NOTICE, err);

error:
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);

	return cli_dynerr(appctx, err);
}

/* parsing function of 'new ssl cert' */
static int cli_parse_new_cert(char **args, char *payload, struct appctx *appctx, void *private)
{
	struct ckch_store *store;
	char *err = NULL;
	char *path;

	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
		return 1;

	if (!*args[3])
		return cli_err(appctx, "'new ssl cert' expects a filename\n");

	path = args[3];

	/* The operations on the CKCH architecture are locked so we can
	 * manipulate ckch_store and ckch_inst */
	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't create a certificate!\nOperations on certificates are currently locked!\n");

	store = ckchs_lookup(path);
	if (store != NULL) {
		memprintf(&err, "Certificate '%s' already exists!\n", path);
		store = NULL; /* we don't want to free it */
		goto error;
	}
	/* we won't support multi-certificate bundle here */
	store = ckch_store_new(path);
	if (!store) {
		memprintf(&err, "unable to allocate memory.\n");
		goto error;
	}

	/* insert into the ckchs tree */
	ebst_insert(&ckchs_tree, &store->node);
	memprintf(&err, "New empty certificate store '%s'!\n", args[3]);

	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	return cli_dynmsg(appctx, LOG_NOTICE, err);
error:
	free(store);
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	return cli_dynerr(appctx, err);
}

/* parsing function of 'del ssl cert' */
static int cli_parse_del_cert(char **args, char *payload, struct appctx *appctx, void *private)
{
	struct ckch_store *store;
	char *err = NULL;
	char *filename;

	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
		return 1;

	if (!*args[3])
		return cli_err(appctx, "'del ssl cert' expects a certificate name\n");

	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't delete the certificate!\nOperations on certificates are currently locked!\n");

	filename = args[3];

	if (ckchs_transaction.path && strcmp(ckchs_transaction.path, filename) == 0) {
		memprintf(&err, "ongoing transaction for the certificate '%s'", filename);
		goto error;
	}

	store = ckchs_lookup(filename);
	if (store == NULL) {
		memprintf(&err, "certificate '%s' doesn't exist!\n", filename);
		goto error;
	}
	if (!LIST_ISEMPTY(&store->ckch_inst)) {
		memprintf(&err, "certificate '%s' in use, can't be deleted!\n", filename);
		goto error;
	}

	ebmb_delete(&store->node);
	ckch_store_free(store);

	memprintf(&err, "Certificate '%s' deleted!\n", filename);

	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	return cli_dynmsg(appctx, LOG_NOTICE, err);

error:
	memprintf(&err, "Can't remove the certificate: %s\n", err ? err : "");
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	return cli_dynerr(appctx, err);
}



/* parsing function of 'new ssl ca-file' */
static int cli_parse_new_cafile(char **args, char *payload, struct appctx *appctx, void *private)
{
	struct cafile_entry *cafile_entry;
	char *err = NULL;
	char *path;

	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
		return 1;

	if (!*args[3])
		return cli_err(appctx, "'new ssl ca-file' expects a filename\n");

	path = args[3];

	/* The operations on the CKCH architecture are locked so we can
	 * manipulate ckch_store and ckch_inst */
	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't create a CA file!\nOperations on certificates are currently locked!\n");

	cafile_entry = ssl_store_get_cafile_entry(path, 0);
	if (cafile_entry) {
		memprintf(&err, "CA file '%s' already exists!\n", path);
		goto error;
	}

	cafile_entry = ssl_store_create_cafile_entry(path, NULL, CAFILE_CERT);
	if (!cafile_entry) {
		memprintf(&err, "%sCannot allocate memory!\n",
			  err ? err : "");
		goto error;
	}

	/* Add the newly created cafile_entry to the tree so that
	 * any new ckch instance created from now can use it. */
	if (ssl_store_add_uncommitted_cafile_entry(cafile_entry))
		goto error;

	memprintf(&err, "New CA file created '%s'!\n", path);

	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	return cli_dynmsg(appctx, LOG_NOTICE, err);
error:
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	return cli_dynerr(appctx, err);
}

/*
 * Parsing function of `set ssl ca-file`
 */
static int cli_parse_set_cafile(char **args, char *payload, struct appctx *appctx, void *private)
{
	struct cafile_entry *old_cafile_entry = NULL;
	struct cafile_entry *new_cafile_entry = NULL;
	char *err = NULL;
	int errcode = 0;
	struct buffer *buf;
	int add_cmd = 0;

	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
		return 1;

	/* this is "add ssl ca-file" */
	if (*args[0] == 'a')
		add_cmd = 1;

	if (!*args[3] || !payload)
		return cli_err(appctx, "'set ssl ca-file' expects a filename and CAs as a payload\n");

	/* The operations on the CKCH architecture are locked so we can
	 * manipulate ckch_store and ckch_inst */
	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't update the CA file!\nOperations on certificates are currently locked!\n");

	if ((buf = alloc_trash_chunk()) == NULL) {
		memprintf(&err, "%sCan't allocate memory\n", err ? err : "");
		errcode |= ERR_ALERT | ERR_FATAL;
		goto end;
	}

	if (!chunk_strcpy(buf, args[3])) {
		memprintf(&err, "%sCan't allocate memory\n", err ? err : "");
		errcode |= ERR_ALERT | ERR_FATAL;
		goto end;
	}

	old_cafile_entry = NULL;
	new_cafile_entry = NULL;

	/* if there is an ongoing transaction */
	if (cafile_transaction.path) {
		/* if there is an ongoing transaction, check if this is the same file */
		if (strcmp(cafile_transaction.path, buf->area) != 0) {
			memprintf(&err, "The ongoing transaction is about '%s' but you are trying to set '%s'\n", cafile_transaction.path, buf->area);
			errcode |= ERR_ALERT | ERR_FATAL;
			goto end;
		}
		old_cafile_entry = cafile_transaction.old_cafile_entry;
	} else {
		/* lookup for the certificate in the tree */
		old_cafile_entry = ssl_store_get_cafile_entry(buf->area, 0);
	}

	if (!old_cafile_entry) {
		memprintf(&err, "%sCan't replace a CA file which is not referenced by the configuration!\n",
		          err ? err : "");
		errcode |= ERR_ALERT | ERR_FATAL;
		goto end;
	}

	/* if the transaction is new, duplicate the old_ca_file_entry, otherwise duplicate the cafile in the current transaction */
	if (cafile_transaction.new_cafile_entry)
		new_cafile_entry = ssl_store_dup_cafile_entry(cafile_transaction.new_cafile_entry);
	else
		new_cafile_entry = ssl_store_dup_cafile_entry(old_cafile_entry);

	if (!new_cafile_entry) {
		memprintf(&err, "%sCan't allocate memory\n", err ? err : "");
		errcode |= ERR_ALERT | ERR_FATAL;
		goto end;
	}

	/* Fill the new entry with the new CAs. The add_cmd variable determine
	   if we flush the X509_STORE or not */
	if (ssl_store_load_ca_from_buf(new_cafile_entry, payload, add_cmd)) {
		memprintf(&err, "%sInvalid payload\n", err ? err : "");
		errcode |= ERR_ALERT | ERR_FATAL;
		goto end;
	}

	/* we succeed, we can save the ca in the transaction */

	/* if there wasn't a transaction, update the old CA */
	if (!cafile_transaction.old_cafile_entry) {
		cafile_transaction.old_cafile_entry = old_cafile_entry;
		cafile_transaction.path = old_cafile_entry->path;
		err = memprintf(&err, "transaction created for CA %s!\n", cafile_transaction.path);
	} else {
		err = memprintf(&err, "transaction updated for CA %s!\n", cafile_transaction.path);
	}

	/* free the previous CA if there was a transaction */
	ssl_store_delete_cafile_entry(cafile_transaction.new_cafile_entry);

	cafile_transaction.new_cafile_entry = new_cafile_entry;

	/* creates the SNI ctxs later in the IO handler */

end:
	free_trash_chunk(buf);

	if (errcode & ERR_CODE) {
		ssl_store_delete_cafile_entry(new_cafile_entry);
		HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
		return cli_dynerr(appctx, memprintf(&err, "%sCan't update %s!\n", err ? err : "", args[3]));
	} else {

		HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
		return cli_dynmsg(appctx, LOG_NOTICE, err);
	}
}


/*
 * Parsing function of 'commit ssl ca-file'.
 * It uses a commit_cacrlfile_ctx that's also shared with "commit ssl crl-file".
 */
static int cli_parse_commit_cafile(char **args, char *payload, struct appctx *appctx, void *private)
{
	struct commit_cacrlfile_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
	char *err = NULL;

	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
		return 1;

	if (!*args[3])
		return cli_err(appctx, "'commit ssl ca-file' expects a filename\n");

	/* The operations on the CKCH architecture are locked so we can
	 * manipulate ckch_store and ckch_inst */
	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't commit the CA file!\nOperations on certificates are currently locked!\n");

	if (!cafile_transaction.path) {
		memprintf(&err, "No ongoing transaction! !\n");
		goto error;
	}

	if (strcmp(cafile_transaction.path, args[3]) != 0) {
		memprintf(&err, "The ongoing transaction is about '%s' but you are trying to set '%s'\n", cafile_transaction.path, args[3]);
		goto error;
	}
	/* init the appctx structure */
	ctx->state = CACRL_ST_INIT;
	ctx->next_ckchi_link = NULL;
	ctx->old_entry = cafile_transaction.old_cafile_entry;
	ctx->new_entry = cafile_transaction.new_cafile_entry;
	ctx->cafile_type = CAFILE_CERT;

	return 0;

error:

	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	err = memprintf(&err, "%sCan't commit %s!\n", err ? err : "", args[3]);

	return cli_dynerr(appctx, err);
}

/*
 * This function tries to create new ckch instances and their SNIs using a newly
 * set certificate authority (CA file) or a newly set Certificate Revocation
 * List (CRL), depending on the command being called.
 */
static int cli_io_handler_commit_cafile_crlfile(struct appctx *appctx)
{
	struct commit_cacrlfile_ctx *ctx = appctx->svcctx;
	int y = 0;
	struct cafile_entry *old_cafile_entry = ctx->old_entry;
	struct cafile_entry *new_cafile_entry = ctx->new_entry;
	struct ckch_inst_link *ckchi_link;
	char *path;

	/* The ctx was already validated by the ca-file/crl-file parsing
	 * function. Entries can only be NULL in CACRL_ST_SUCCESS or
	 * CACRL_ST_FIN states
	 */
	switch (ctx->cafile_type) {
		case CAFILE_CERT:
			path = cafile_transaction.path;
			break;
		case CAFILE_CRL:
			path = crlfile_transaction.path;
			break;
		default:
			path = NULL;
			goto error;
	}

	while (1) {
		switch (ctx->state) {
			case CACRL_ST_INIT:
				/* This state just print the update message */
				chunk_printf(&trash, "Committing %s", path);
				if (applet_putchk(appctx, &trash) == -1)
					goto yield;

				ctx->state = CACRL_ST_GEN;
				__fallthrough;
			case CACRL_ST_GEN:
				/*
				 * This state generates the ckch instances with their
				 * sni_ctxs and SSL_CTX.
				 *
				 * Since the SSL_CTX generation can be CPU consumer, we
				 * yield every 10 instances.
				 */

				/* get the next ckchi to regenerate */
				ckchi_link = ctx->next_ckchi_link;

				/* we didn't start yet, set it to the first elem */
				if (ckchi_link == NULL) {
					ckchi_link = LIST_ELEM(old_cafile_entry->ckch_inst_link.n, typeof(ckchi_link), list);
					/* Add the newly created cafile_entry to the tree so that
					 * any new ckch instance created from now can use it. */
					if (ssl_store_add_uncommitted_cafile_entry(new_cafile_entry)) {
						ctx->state = CACRL_ST_ERROR;
						goto error;
					}
				}

				list_for_each_entry_from(ckchi_link, &old_cafile_entry->ckch_inst_link, list) {
					struct ckch_inst *new_inst;

					/* save the next ckchi to compute */
					ctx->next_ckchi_link = ckchi_link;

					/* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
					if (y >= 10) {
						applet_have_more_data(appctx); /* let's come back later */
						goto yield;
					}

					/* display one dot per new instance */
					if (applet_putstr(appctx, ".") == -1)
						goto yield;

					/* Rebuild a new ckch instance that uses the same ckch_store
					 * than a reference ckchi instance but will use a new CA file. */
					ctx->err = NULL;
					if (ckch_inst_rebuild(ckchi_link->ckch_inst->ckch_store, ckchi_link->ckch_inst, &new_inst, &ctx->err)) {
						ctx->state = CACRL_ST_ERROR;
						goto error;
					}

					y++;
				}

				ctx->state = CACRL_ST_CRLCB;
				__fallthrough;
			case CACRL_ST_CRLCB:
				if ((ctx->cafile_type == CAFILE_CRL) && (ssl_commit_crlfile_cb != NULL)) {
					if (ssl_commit_crlfile_cb(crlfile_transaction.path, crlfile_transaction.new_crlfile_entry->ca_store, &ctx->err) == -1) {
						ctx->state = CACRL_ST_ERROR;
						goto error;
					}
				}
				ctx->state = CACRL_ST_INSERT;
				__fallthrough;
			case CACRL_ST_INSERT:
				/* The generation is finished, we can insert everything */

				/* insert the new ckch_insts in the crtlist_entry */
				list_for_each_entry(ckchi_link, &new_cafile_entry->ckch_inst_link, list) {
					if (ckchi_link->ckch_inst->crtlist_entry)
						LIST_INSERT(&ckchi_link->ckch_inst->crtlist_entry->ckch_inst,
							    &ckchi_link->ckch_inst->by_crtlist_entry);
				}

				/* First, we insert every new SNIs in the trees, also replace the default_ctx */
				list_for_each_entry(ckchi_link, &new_cafile_entry->ckch_inst_link, list) {
					__ssl_sock_load_new_ckch_instance(ckchi_link->ckch_inst);
				}

				/* delete the old sni_ctx, the old ckch_insts
				 * and the ckch_store. ckch_inst_free() also
				 * manipulates the list so it's cleaner to loop
				 * until it's empty  */
				while (!LIST_ISEMPTY(&old_cafile_entry->ckch_inst_link)) {
					ckchi_link = LIST_ELEM(old_cafile_entry->ckch_inst_link.n, typeof(ckchi_link), list);

					LIST_DEL_INIT(&ckchi_link->list); /* must reinit because ckch_inst checks the list */
					__ckch_inst_free_locked(ckchi_link->ckch_inst);
					free(ckchi_link);
				}

				/* Remove the old cafile entry from the tree */
				ebmb_delete(&old_cafile_entry->node);
				ssl_store_delete_cafile_entry(old_cafile_entry);

				ctx->old_entry = ctx->new_entry = NULL;
				ctx->state = CACRL_ST_SUCCESS;
				__fallthrough;
			case CACRL_ST_SUCCESS:
				if (applet_putstr(appctx, "\nSuccess!\n") == -1)
					goto yield;
				ctx->state = CACRL_ST_FIN;
				__fallthrough;
			case CACRL_ST_FIN:
				/* we achieved the transaction, we can set everything to NULL */
				switch (ctx->cafile_type) {
				case CAFILE_CERT:
					cafile_transaction.old_cafile_entry = NULL;
					cafile_transaction.new_cafile_entry = NULL;
					cafile_transaction.path = NULL;
					break;
				case CAFILE_CRL:
					crlfile_transaction.old_crlfile_entry = NULL;
					crlfile_transaction.new_crlfile_entry = NULL;
					crlfile_transaction.path = NULL;
					break;
				}
				goto end;

			case CACRL_ST_ERROR:
			  error:
				chunk_printf(&trash, "\n%sFailed!\n", ctx->err);
				if (applet_putchk(appctx, &trash) == -1)
					goto yield;
				ctx->state = CACRL_ST_FIN;
				break;
		}
	}
end:
	/* success: call the release function and don't come back */
	return 1;
yield:
	return 0; /* should come back */
}


/* parsing function of 'abort ssl ca-file' */
static int cli_parse_abort_cafile(char **args, char *payload, struct appctx *appctx, void *private)
{
	char *err = NULL;

	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
		return 1;

	if (!*args[3])
		return cli_err(appctx, "'abort ssl ca-file' expects a filename\n");

	/* The operations on the CKCH architecture are locked so we can
	 * manipulate ckch_store and ckch_inst */
	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't abort!\nOperations on certificates are currently locked!\n");

	if (!cafile_transaction.path) {
		memprintf(&err, "No ongoing transaction!\n");
		goto error;
	}

	if (strcmp(cafile_transaction.path, args[3]) != 0) {
		memprintf(&err, "The ongoing transaction is about '%s' but you are trying to abort a transaction for '%s'\n", cafile_transaction.path, args[3]);
		goto error;
	}

	/* Only free the uncommitted cafile_entry here, because the SNI and instances were not generated yet */
	ssl_store_delete_cafile_entry(cafile_transaction.new_cafile_entry);
	cafile_transaction.new_cafile_entry = NULL;
	cafile_transaction.old_cafile_entry = NULL;
	cafile_transaction.path = NULL;

	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);

	err = memprintf(&err, "Transaction aborted for certificate '%s'!\n", args[3]);
	return cli_dynmsg(appctx, LOG_NOTICE, err);

error:
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);

	return cli_dynerr(appctx, err);
}

/* release function of the `commit ssl ca-file' command, free things and unlock the spinlock.
 * It uses a commit_cacrlfile_ctx context.
 */
static void cli_release_commit_cafile(struct appctx *appctx)
{
	struct commit_cacrlfile_ctx *ctx = appctx->svcctx;
	struct cafile_entry *new_cafile_entry = ctx->new_entry;

	/* Remove the uncommitted cafile_entry from the tree. */
	if (new_cafile_entry) {
		ebmb_delete(&new_cafile_entry->node);
		ssl_store_delete_cafile_entry(new_cafile_entry);
	}
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	ha_free(&ctx->err);
}


/* IO handler of details "show ssl ca-file <filename[:index]>".
 * It uses a show_cafile_ctx context, and the global
 * cafile_transaction.new_cafile_entry in read-only.
 */
static int cli_io_handler_show_cafile_detail(struct appctx *appctx)
{
	struct show_cafile_ctx *ctx = appctx->svcctx;
	struct cafile_entry *cafile_entry = ctx->cur_cafile_entry;
	struct buffer *out = alloc_trash_chunk();
	int i = 0;
	X509 *cert;
	STACK_OF(X509_OBJECT) *objs;
	int retval = 0;
	int ca_index = ctx->ca_index;
	int show_all = ctx->show_all;

	if (!out)
		goto end_no_putchk;

	chunk_appendf(out, "Filename: ");
	if (cafile_entry == cafile_transaction.new_cafile_entry)
		chunk_appendf(out, "*");
	chunk_appendf(out, "%s\n", cafile_entry->path);

	chunk_appendf(out, "Status: ");
	if (!cafile_entry->ca_store)
		chunk_appendf(out, "Empty\n");
	else if (LIST_ISEMPTY(&cafile_entry->ckch_inst_link))
		chunk_appendf(out, "Unused\n");
	else
		chunk_appendf(out, "Used\n");

	if (!cafile_entry->ca_store)
		goto end;

	objs = X509_STORE_get0_objects(cafile_entry->ca_store);
	for (i = ca_index; i < sk_X509_OBJECT_num(objs); i++) {

		cert = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
		if (!cert)
			continue;

		/* file starts at line 1 */
		chunk_appendf(out, " \nCertificate #%d:\n", i+1);
		retval = show_cert_detail(cert, NULL, out);
		if (retval < 0)
			goto end_no_putchk;
		else if (retval)
			goto yield;

		if (applet_putchk(appctx, out) == -1)
			goto yield;

		if (!show_all)   /* only need to dump one certificate */
			goto end;
	}

end:
	free_trash_chunk(out);
	return 1; /* end, don't come back */

end_no_putchk:
	free_trash_chunk(out);
	return 1;
yield:
	/* save the current state */
	ctx->ca_index = i;
	free_trash_chunk(out);
	return 0; /* should come back */
}


/* parsing function for 'show ssl ca-file [cafile[:index]]'.
 * It prepares a show_cafile_ctx context, and checks the global
 * cafile_transaction under the ckch_lock (read only).
 */
static int cli_parse_show_cafile(char **args, char *payload, struct appctx *appctx, void *private)
{
	struct show_cafile_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
	struct cafile_entry *cafile_entry;
	int ca_index = 0;
	char *colons;
	char *err = NULL;

	if (!cli_has_level(appctx, ACCESS_LVL_OPER))
		return cli_err(appctx, "Can't allocate memory!\n");

	/* The operations on the CKCH architecture are locked so we can
	 * manipulate ckch_store and ckch_inst */
	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't show!\nOperations on certificates are currently locked!\n");

	ctx->show_all = 1; /* show all certificates */
	ctx->ca_index = 0;
	/* check if there is a certificate to lookup */
	if (*args[3]) {

		/* Look for an optional CA index after the CA file name */
		colons = strchr(args[3], ':');
		if (colons) {
			char *endptr;

			ca_index = strtol(colons + 1, &endptr, 10);
			/* Indexes start at 1 */
			if (colons + 1 == endptr || *endptr != '\0' || ca_index <= 0) {
				memprintf(&err, "wrong CA index after colons in '%s'!", args[3]);
				goto error;
			}
			*colons = '\0';
			ctx->ca_index = ca_index - 1; /* we start counting at 0 in the ca_store, but at 1 on the CLI */
			ctx->show_all = 0; /* show only one certificate */
		}

		if (*args[3] == '*') {
			if (!cafile_transaction.new_cafile_entry)
				goto error;

			cafile_entry = cafile_transaction.new_cafile_entry;

			if (strcmp(args[3] + 1, cafile_entry->path) != 0)
				goto error;

		} else {
			/* Get the "original" cafile_entry and not the
			 * uncommitted one if it exists. */
			if ((cafile_entry = ssl_store_get_cafile_entry(args[3], 1)) == NULL || cafile_entry->type != CAFILE_CERT)
				goto error;
		}

		ctx->cur_cafile_entry = cafile_entry;
		/* use the IO handler that shows details */
		appctx->io_handler = cli_io_handler_show_cafile_detail;
	}

	return 0;

error:
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	if (err)
		return cli_dynerr(appctx, err);
	return cli_err(appctx, "Can't display the CA file : Not found!\n");
}


/* release function of the 'show ssl ca-file' command */
static void cli_release_show_cafile(struct appctx *appctx)
{
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
}


/* This function returns the number of certificates in a cafile_entry. */
static int get_certificate_count(struct cafile_entry *cafile_entry)
{
	int cert_count = 0;
	STACK_OF(X509_OBJECT) *objs;

	if (cafile_entry && cafile_entry->ca_store) {
		objs = X509_STORE_get0_objects(cafile_entry->ca_store);
		if (objs)
			cert_count = sk_X509_OBJECT_num(objs);
	}
	return cert_count;
}

/* IO handler of "show ssl ca-file". The command taking a specific CA file name
 * is managed in cli_io_handler_show_cafile_detail.
 * It uses a show_cafile_ctx and the global cafile_transaction.new_cafile_entry
 * in read-only.
 */
static int cli_io_handler_show_cafile(struct appctx *appctx)
{
	struct show_cafile_ctx *ctx = appctx->svcctx;
	struct buffer *trash = alloc_trash_chunk();
	struct ebmb_node *node;
	struct cafile_entry *cafile_entry = NULL;

	if (trash == NULL)
		return 1;

	if (!ctx->old_cafile_entry && cafile_transaction.old_cafile_entry) {
		chunk_appendf(trash, "# transaction\n");
		chunk_appendf(trash, "*%s", cafile_transaction.old_cafile_entry->path);
		chunk_appendf(trash, " - %d certificate(s)\n", get_certificate_count(cafile_transaction.new_cafile_entry));
		if (applet_putchk(appctx, trash) == -1)
			goto yield;
		ctx->old_cafile_entry = cafile_transaction.new_cafile_entry;
	}

	/* First time in this io_handler. */
	if (!ctx->cur_cafile_entry) {
		chunk_appendf(trash, "# filename\n");
		node = ebmb_first(&cafile_tree);
	} else {
		/* We yielded during a previous call. */
		node = &ctx->cur_cafile_entry->node;
	}

	while (node) {
		cafile_entry = ebmb_entry(node, struct cafile_entry, node);
		if (cafile_entry->type == CAFILE_CERT) {
			chunk_appendf(trash, "%s", cafile_entry->path);

			chunk_appendf(trash, " - %d certificate(s)\n", get_certificate_count(cafile_entry));
		}

		node = ebmb_next(node);
		if (applet_putchk(appctx, trash) == -1)
			goto yield;
	}

	ctx->cur_cafile_entry = NULL;
	free_trash_chunk(trash);
	return 1;
yield:

	free_trash_chunk(trash);
	ctx->cur_cafile_entry = cafile_entry;
	return 0; /* should come back */
}

/* parsing function of 'del ssl ca-file' */
static int cli_parse_del_cafile(char **args, char *payload, struct appctx *appctx, void *private)
{
	struct cafile_entry *cafile_entry;
	char *err = NULL;
	char *filename;

	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
		return 1;

	if (!*args[3])
		return cli_err(appctx, "'del ssl ca-file' expects a CA file name\n");

	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't delete the CA file!\nOperations on certificates are currently locked!\n");

	filename = args[3];

	if (cafile_transaction.path && strcmp(cafile_transaction.path, filename) == 0) {
		memprintf(&err, "ongoing transaction for the CA file '%s'", filename);
		goto error;
	}

	cafile_entry = ssl_store_get_cafile_entry(filename, 0);
	if (!cafile_entry) {
		memprintf(&err, "CA file '%s' doesn't exist!\n", filename);
		goto error;
	}

	if (!LIST_ISEMPTY(&cafile_entry->ckch_inst_link)) {
		memprintf(&err, "CA file '%s' in use, can't be deleted!\n", filename);
		goto error;
	}

	/* Remove the cafile_entry from the tree */
	ebmb_delete(&cafile_entry->node);
	ssl_store_delete_cafile_entry(cafile_entry);

	memprintf(&err, "CA file '%s' deleted!\n", filename);

	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	return cli_dynmsg(appctx, LOG_NOTICE, err);

error:
	memprintf(&err, "Can't remove the CA file: %s\n", err ? err : "");
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	return cli_dynerr(appctx, err);
}

/* parsing function of 'new ssl crl-file' */
static int cli_parse_new_crlfile(char **args, char *payload, struct appctx *appctx, void *private)
{
	struct cafile_entry *cafile_entry;
	char *err = NULL;
	char *path;

	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
		return 1;

	if (!*args[3])
		return cli_err(appctx, "'new ssl crl-file' expects a filename\n");

	path = args[3];

	/* The operations on the CKCH architecture are locked so we can
	 * manipulate ckch_store and ckch_inst */
	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't create a CRL file!\nOperations on certificates are currently locked!\n");

	cafile_entry = ssl_store_get_cafile_entry(path, 0);
	if (cafile_entry) {
		memprintf(&err, "CRL file '%s' already exists!\n", path);
		goto error;
	}

	cafile_entry = ssl_store_create_cafile_entry(path, NULL, CAFILE_CRL);
	if (!cafile_entry) {
		memprintf(&err, "%sCannot allocate memory!\n", err ? err : "");
		goto error;
	}

	/* Add the newly created cafile_entry to the tree so that
	 * any new ckch instance created from now can use it. */
	if (ssl_store_add_uncommitted_cafile_entry(cafile_entry))
		goto error;

	memprintf(&err, "New CRL file created '%s'!\n", path);

	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	return cli_dynmsg(appctx, LOG_NOTICE, err);
error:
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	return cli_dynerr(appctx, err);
}

/* Parsing function of `set ssl crl-file` */
static int cli_parse_set_crlfile(char **args, char *payload, struct appctx *appctx, void *private)
{
	struct cafile_entry *old_crlfile_entry = NULL;
	struct cafile_entry *new_crlfile_entry = NULL;
	char *err = NULL;
	int errcode = 0;
	struct buffer *buf;

	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
		return 1;

	if (!*args[3] || !payload)
		return cli_err(appctx, "'set ssl crl-file' expects a filename and CRLs as a payload\n");

	/* The operations on the CKCH architecture are locked so we can
	 * manipulate ckch_store and ckch_inst */
	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't update the CRL file!\nOperations on certificates are currently locked!\n");

	if ((buf = alloc_trash_chunk()) == NULL) {
		memprintf(&err, "%sCan't allocate memory\n", err ? err : "");
		errcode |= ERR_ALERT | ERR_FATAL;
		goto end;
	}

	if (!chunk_strcpy(buf, args[3])) {
		memprintf(&err, "%sCan't allocate memory\n", err ? err : "");
		errcode |= ERR_ALERT | ERR_FATAL;
		goto end;
	}

	old_crlfile_entry = NULL;
	new_crlfile_entry = NULL;

	/* if there is an ongoing transaction */
	if (crlfile_transaction.path) {
		/* if there is an ongoing transaction, check if this is the same file */
		if (strcmp(crlfile_transaction.path, buf->area) != 0) {
			memprintf(&err, "The ongoing transaction is about '%s' but you are trying to set '%s'\n", crlfile_transaction.path, buf->area);
			errcode |= ERR_ALERT | ERR_FATAL;
			goto end;
		}
		old_crlfile_entry = crlfile_transaction.old_crlfile_entry;
	}
	else {
		/* lookup for the certificate in the tree */
		old_crlfile_entry = ssl_store_get_cafile_entry(buf->area, 0);
	}

	if (!old_crlfile_entry) {
		memprintf(&err, "%sCan't replace a CRL file which is not referenced by the configuration!\n",
		          err ? err : "");
		errcode |= ERR_ALERT | ERR_FATAL;
		goto end;
	}

	/* Create a new cafile_entry without adding it to the cafile tree. */
	new_crlfile_entry = ssl_store_create_cafile_entry(old_crlfile_entry->path, NULL, CAFILE_CRL);
	if (!new_crlfile_entry) {
		memprintf(&err, "%sCannot allocate memory!\n", err ? err : "");
		errcode |= ERR_ALERT | ERR_FATAL;
		goto end;
	}

	/* Fill the new entry with the new CRL. */
	if (ssl_store_load_ca_from_buf(new_crlfile_entry, payload, 0)) {
		memprintf(&err, "%sInvalid payload\n", err ? err : "");
		errcode |= ERR_ALERT | ERR_FATAL;
		goto end;
	}

	/* we succeed, we can save the crl in the transaction */

	/* if there wasn't a transaction, update the old CRL */
	if (!crlfile_transaction.old_crlfile_entry) {
		crlfile_transaction.old_crlfile_entry = old_crlfile_entry;
		crlfile_transaction.path = old_crlfile_entry->path;
		err = memprintf(&err, "transaction created for CRL %s!\n", crlfile_transaction.path);
	} else {
		err = memprintf(&err, "transaction updated for CRL %s!\n", crlfile_transaction.path);
	}

	/* free the previous CRL file if there was a transaction */
	ssl_store_delete_cafile_entry(crlfile_transaction.new_crlfile_entry);

	crlfile_transaction.new_crlfile_entry = new_crlfile_entry;

	/* creates the SNI ctxs later in the IO handler */

end:
	free_trash_chunk(buf);

	if (errcode & ERR_CODE) {
		ssl_store_delete_cafile_entry(new_crlfile_entry);
		HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
		return cli_dynerr(appctx, memprintf(&err, "%sCan't update %s!\n", err ? err : "", args[3]));
	} else {

		HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
		return cli_dynmsg(appctx, LOG_NOTICE, err);
	}
}

/* Parsing function of 'commit ssl crl-file'.
 * It uses a commit_cacrlfile_ctx that's also shared with "commit ssl ca-file".
 */
static int cli_parse_commit_crlfile(char **args, char *payload, struct appctx *appctx, void *private)
{
	struct commit_cacrlfile_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
	char *err = NULL;

	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
		return 1;

	if (!*args[3])
		return cli_err(appctx, "'commit ssl ca-file' expects a filename\n");

	/* The operations on the CKCH architecture are locked so we can
	 * manipulate ckch_store and ckch_inst */
	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't commit the CRL file!\nOperations on certificates are currently locked!\n");

	if (!crlfile_transaction.path) {
		memprintf(&err, "No ongoing transaction! !\n");
		goto error;
	}

	if (strcmp(crlfile_transaction.path, args[3]) != 0) {
		memprintf(&err, "The ongoing transaction is about '%s' but you are trying to set '%s'\n", crlfile_transaction.path, args[3]);
		goto error;
	}
	/* init the appctx structure */
	ctx->state = CACRL_ST_INIT;
	ctx->next_ckchi_link = NULL;
	ctx->old_entry = crlfile_transaction.old_crlfile_entry;
	ctx->new_entry = crlfile_transaction.new_crlfile_entry;
	ctx->cafile_type = CAFILE_CRL;

	return 0;

error:

	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	err = memprintf(&err, "%sCan't commit %s!\n", err ? err : "", args[3]);

	return cli_dynerr(appctx, err);
}


/* release function of the `commit ssl crl-file' command, free things and unlock the spinlock.
 * it uses a commit_cacrlfile_ctx that's the same as for "commit ssl ca-file".
 */
static void cli_release_commit_crlfile(struct appctx *appctx)
{
	struct commit_cacrlfile_ctx *ctx = appctx->svcctx;
	struct cafile_entry *new_crlfile_entry = ctx->new_entry;

	/* Remove the uncommitted cafile_entry from the tree. */
	if (new_crlfile_entry) {
		ebmb_delete(&new_crlfile_entry->node);
		ssl_store_delete_cafile_entry(new_crlfile_entry);
	}
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	ha_free(&ctx->err);
}

/* parsing function of 'del ssl crl-file' */
static int cli_parse_del_crlfile(char **args, char *payload, struct appctx *appctx, void *private)
{
	struct cafile_entry *cafile_entry;
	char *err = NULL;
	char *filename;

	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
		return 1;

	if (!*args[3])
		return cli_err(appctx, "'del ssl crl-file' expects a CRL file name\n");

	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't delete the CRL file!\nOperations on certificates are currently locked!\n");

	filename = args[3];

	if (crlfile_transaction.path && strcmp(crlfile_transaction.path, filename) == 0) {
		memprintf(&err, "ongoing transaction for the CRL file '%s'", filename);
		goto error;
	}

	cafile_entry = ssl_store_get_cafile_entry(filename, 0);
	if (!cafile_entry) {
		memprintf(&err, "CRL file '%s' doesn't exist!\n", filename);
		goto error;
	}
	if (cafile_entry->type != CAFILE_CRL) {
		memprintf(&err, "'del ssl crl-file' does not work on CA files!\n");
		goto error;
	}

	if (!LIST_ISEMPTY(&cafile_entry->ckch_inst_link)) {
		memprintf(&err, "CRL file '%s' in use, can't be deleted!\n", filename);
		goto error;
	}

	/* Remove the cafile_entry from the tree */
	ebmb_delete(&cafile_entry->node);
	ssl_store_delete_cafile_entry(cafile_entry);

	memprintf(&err, "CRL file '%s' deleted!\n", filename);

	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	return cli_dynmsg(appctx, LOG_NOTICE, err);

error:
	memprintf(&err, "Can't remove the CRL file: %s\n", err ? err : "");
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	return cli_dynerr(appctx, err);
}

/* parsing function of 'abort ssl crl-file' */
static int cli_parse_abort_crlfile(char **args, char *payload, struct appctx *appctx, void *private)
{
	char *err = NULL;

	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
		return 1;

	if (!*args[3])
		return cli_err(appctx, "'abort ssl crl-file' expects a filename\n");

	/* The operations on the CKCH architecture are locked so we can
	 * manipulate ckch_store and ckch_inst */
	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't abort!\nOperations on certificates are currently locked!\n");

	if (!crlfile_transaction.path) {
		memprintf(&err, "No ongoing transaction!\n");
		goto error;
	}

	if (strcmp(crlfile_transaction.path, args[3]) != 0) {
		memprintf(&err, "The ongoing transaction is about '%s' but you are trying to abort a transaction for '%s'\n", crlfile_transaction.path, args[3]);
		goto error;
	}

	/* Only free the uncommitted cafile_entry here, because the SNI and instances were not generated yet */
	ssl_store_delete_cafile_entry(crlfile_transaction.new_crlfile_entry);
	crlfile_transaction.new_crlfile_entry = NULL;
	crlfile_transaction.old_crlfile_entry = NULL;
	crlfile_transaction.path = NULL;

	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);

	err = memprintf(&err, "Transaction aborted for certificate '%s'!\n", args[3]);
	return cli_dynmsg(appctx, LOG_NOTICE, err);

error:
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);

	return cli_dynerr(appctx, err);
}


/*
 * Display a Certificate Resignation List's information.
 * The information displayed is inspired by the output of 'openssl crl -in
 * crl.pem -text'.
 * Returns 0 in case of success.
 */
static int show_crl_detail(X509_CRL *crl, struct buffer *out)
{
	BIO *bio = NULL;
	struct buffer *tmp = alloc_trash_chunk();
	long version;
	X509_NAME *issuer;
	int write = -1;
#ifndef USE_OPENSSL_WOLFSSL
	STACK_OF(X509_REVOKED) *rev = NULL;
	X509_REVOKED *rev_entry = NULL;
	int i;
#endif

	if (!tmp)
		return -1;

	if ((bio = BIO_new(BIO_s_mem())) == NULL)
		goto end;

	/* Version (as displayed by 'openssl crl') */
	version = X509_CRL_get_version(crl);
	chunk_appendf(out, "Version %ld\n", version + 1);

	/* Signature Algorithm */
	chunk_appendf(out, "Signature Algorithm: %s\n", OBJ_nid2ln(X509_CRL_get_signature_nid(crl)));

	/* Issuer */
	chunk_appendf(out, "Issuer: ");
	if ((issuer = X509_CRL_get_issuer(crl)) == NULL)
		goto end;
	if ((ssl_sock_get_dn_oneline(issuer, tmp)) == -1)
		goto end;
	*(tmp->area + tmp->data) = '\0';
	chunk_appendf(out, "%s\n", tmp->area);

	/* Last Update */
	chunk_appendf(out, "Last Update: ");
	chunk_reset(tmp);
	if (BIO_reset(bio) == -1)
		goto end;
	if (ASN1_TIME_print(bio, X509_CRL_get0_lastUpdate(crl)) == 0)
		goto end;
	write = BIO_read(bio, tmp->area, tmp->size-1);
	tmp->area[write] = '\0';
	chunk_appendf(out, "%s\n", tmp->area);


	/* Next Update */
	chunk_appendf(out, "Next Update: ");
	chunk_reset(tmp);
	if (BIO_reset(bio) == -1)
		goto end;
	if (ASN1_TIME_print(bio, X509_CRL_get0_nextUpdate(crl)) == 0)
		goto end;
	write = BIO_read(bio, tmp->area, tmp->size-1);
	tmp->area[write] = '\0';
	chunk_appendf(out, "%s\n", tmp->area);

#ifndef USE_OPENSSL_WOLFSSL
	/* Revoked Certificates */
	rev = X509_CRL_get_REVOKED(crl);
	if (sk_X509_REVOKED_num(rev) > 0)
		chunk_appendf(out, "Revoked Certificates:\n");
	else
		chunk_appendf(out, "No Revoked Certificates.\n");

	for (i = 0; i < sk_X509_REVOKED_num(rev); i++) {
		rev_entry = sk_X509_REVOKED_value(rev, i);

		/* Serial Number and Revocation Date */
		if (BIO_reset(bio) == -1)
			goto end;
		BIO_printf(bio , "    Serial Number: ");
		i2a_ASN1_INTEGER(bio, (ASN1_INTEGER*)X509_REVOKED_get0_serialNumber(rev_entry));
		BIO_printf(bio, "\n        Revocation Date: ");
		if (ASN1_TIME_print(bio, X509_REVOKED_get0_revocationDate(rev_entry)) == 0)
			goto end;
		BIO_printf(bio, "\n");

		write = BIO_read(bio, tmp->area, tmp->size-1);
		tmp->area[write] = '\0';
		chunk_appendf(out, "%s", tmp->area);
	}
#endif /* not USE_OPENSSL_WOLFSSL */

end:
	free_trash_chunk(tmp);
	if (bio)
		BIO_free(bio);

	return 0;
}

/* IO handler of details "show ssl crl-file <filename[:index]>".
 * It uses show_crlfile_ctx and the global
 * crlfile_transaction.new_cafile_entry in read-only.
 */
static int cli_io_handler_show_crlfile_detail(struct appctx *appctx)
{
	struct show_crlfile_ctx *ctx = appctx->svcctx;
	struct cafile_entry *cafile_entry = ctx->cafile_entry;
	struct buffer *out = alloc_trash_chunk();
	int i;
	X509_CRL *crl;
	STACK_OF(X509_OBJECT) *objs;
	int retval = 0;
	int index = ctx->index;

	if (!out)
		goto end_no_putchk;

	chunk_appendf(out, "Filename: ");
	if (cafile_entry == crlfile_transaction.new_crlfile_entry)
		chunk_appendf(out, "*");
	chunk_appendf(out, "%s\n", cafile_entry->path);

	chunk_appendf(out, "Status: ");
	if (!cafile_entry->ca_store)
		chunk_appendf(out, "Empty\n");
	else if (LIST_ISEMPTY(&cafile_entry->ckch_inst_link))
		chunk_appendf(out, "Unused\n");
	else
		chunk_appendf(out, "Used\n");

	if (!cafile_entry->ca_store)
		goto end;

	objs = X509_STORE_get0_objects(cafile_entry->ca_store);
	for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
		crl = X509_OBJECT_get0_X509_CRL(sk_X509_OBJECT_value(objs, i));
		if (!crl)
			continue;

		/* CRL indexes start at 1 on the CLI output. */
		if (index && index-1 != i)
			continue;

		chunk_appendf(out, " \nCertificate Revocation List #%d:\n", i+1);
		retval = show_crl_detail(crl, out);
		if (retval < 0)
			goto end_no_putchk;
		else if (retval || index)
			goto end;
	}

end:
	if (applet_putchk(appctx, out) == -1)
		goto yield;

end_no_putchk:
	free_trash_chunk(out);
	return 1;
yield:
	free_trash_chunk(out);
	return 0; /* should come back */
}

/* parsing function for 'show ssl crl-file [crlfile[:index]]'.
 * It sets the context to a show_crlfile_ctx, and the global
 * cafile_transaction.new_crlfile_entry under the ckch_lock.
 */
static int cli_parse_show_crlfile(char **args, char *payload, struct appctx *appctx, void *private)
{
	struct show_crlfile_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
	struct cafile_entry *cafile_entry;
	long index = 0;
	char *colons;
	char *err = NULL;

	if (!cli_has_level(appctx, ACCESS_LVL_OPER))
		return cli_err(appctx, "Can't allocate memory!\n");

	/* The operations on the CKCH architecture are locked so we can
	 * manipulate ckch_store and ckch_inst */
	if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
		return cli_err(appctx, "Can't show!\nOperations on certificates are currently locked!\n");

	/* check if there is a certificate to lookup */
	if (*args[3]) {

		/* Look for an optional index after the CRL file name */
		colons = strchr(args[3], ':');
		if (colons) {
			char *endptr;

			index = strtol(colons + 1, &endptr, 10);
			/* Indexes start at 1 */
			if (colons + 1 == endptr || *endptr != '\0' || index <= 0) {
				memprintf(&err, "wrong CRL index after colons in '%s'!", args[3]);
				goto error;
			}
			*colons = '\0';
		}

		if (*args[3] == '*') {
			if (!crlfile_transaction.new_crlfile_entry)
				goto error;

			cafile_entry = crlfile_transaction.new_crlfile_entry;

			if (strcmp(args[3] + 1, cafile_entry->path) != 0)
				goto error;

		} else {
			/* Get the "original" cafile_entry and not the
			 * uncommitted one if it exists. */
			if ((cafile_entry = ssl_store_get_cafile_entry(args[3], 1)) == NULL || cafile_entry->type != CAFILE_CRL)
				goto error;
		}

		ctx->cafile_entry = cafile_entry;
		ctx->index = index;
		/* use the IO handler that shows details */
		appctx->io_handler = cli_io_handler_show_crlfile_detail;
	}

	return 0;

error:
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
	if (err)
		return cli_dynerr(appctx, err);
	return cli_err(appctx, "Can't display the CRL file : Not found!\n");
}

/* IO handler of "show ssl crl-file". The command taking a specific CRL file name
 * is managed in cli_io_handler_show_crlfile_detail. */
static int cli_io_handler_show_crlfile(struct appctx *appctx)
{
	struct show_crlfile_ctx *ctx = appctx->svcctx;
	struct buffer *trash = alloc_trash_chunk();
	struct ebmb_node *node;
	struct cafile_entry *cafile_entry = NULL;

	if (trash == NULL)
		return 1;

	if (!ctx->old_crlfile_entry && crlfile_transaction.old_crlfile_entry) {
		chunk_appendf(trash, "# transaction\n");
		chunk_appendf(trash, "*%s\n", crlfile_transaction.old_crlfile_entry->path);
		if (applet_putchk(appctx, trash) == -1)
			goto yield;
		ctx->old_crlfile_entry = crlfile_transaction.old_crlfile_entry;
	}

	/* First time in this io_handler. */
	if (!ctx->cafile_entry) {
		chunk_appendf(trash, "# filename\n");
		node = ebmb_first(&cafile_tree);
	} else {
		/* We yielded during a previous call. */
		node = &ctx->cafile_entry->node;
	}

	while (node) {
		cafile_entry = ebmb_entry(node, struct cafile_entry, node);
		if (cafile_entry->type == CAFILE_CRL) {
			chunk_appendf(trash, "%s\n", cafile_entry->path);
		}

		node = ebmb_next(node);
		if (applet_putchk(appctx, trash) == -1)
			goto yield;
	}

	ctx->cafile_entry = NULL;
	free_trash_chunk(trash);
	return 1;
yield:

	free_trash_chunk(trash);
	ctx->cafile_entry = cafile_entry;
	return 0; /* should come back */
}


/* release function of the 'show ssl crl-file' command */
static void cli_release_show_crlfile(struct appctx *appctx)
{
	HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
}


void ckch_deinit()
{
	struct eb_node *node, *next;
	struct ckch_store *store;
	struct ebmb_node *canode;

	/* deinit the ckch stores */
	node = eb_first(&ckchs_tree);
	while (node) {
		next = eb_next(node);
		store = ebmb_entry(node, struct ckch_store, node);
		ckch_store_free(store);
		node = next;
	}

	/* deinit the ca-file store */
	canode = ebmb_first(&cafile_tree);
	while (canode) {
		struct cafile_entry *entry = NULL;

		entry = ebmb_entry(canode, struct cafile_entry, node);
		canode = ebmb_next(canode);
		ebmb_delete(&entry->node);
		ssl_store_delete_cafile_entry(entry);
	}
}

/* register cli keywords */
static struct cli_kw_list cli_kws = {{ },{
	{ { "new", "ssl", "cert", NULL },       "new ssl cert <certfile>                 : create a new certificate file to be used in a crt-list or a directory", cli_parse_new_cert, NULL, NULL },
	{ { "set", "ssl", "cert", NULL },       "set ssl cert <certfile> <payload>       : replace a certificate file",                                            cli_parse_set_cert, NULL, NULL },
	{ { "commit", "ssl", "cert", NULL },    "commit ssl cert <certfile>              : commit a certificate file",                                             cli_parse_commit_cert, cli_io_handler_commit_cert, cli_release_commit_cert },
	{ { "abort", "ssl", "cert", NULL },     "abort ssl cert <certfile>               : abort a transaction for a certificate file",                            cli_parse_abort_cert, NULL, NULL },
	{ { "del", "ssl", "cert", NULL },       "del ssl cert <certfile>                 : delete an unused certificate file",                                     cli_parse_del_cert, NULL, NULL },
	{ { "show", "ssl", "cert", NULL },      "show ssl cert [<certfile>]              : display the SSL certificates used in memory, or the details of a file", cli_parse_show_cert, cli_io_handler_show_cert, cli_release_show_cert },

	{ { "new", "ssl", "ca-file", NULL },    "new ssl ca-file <cafile>                : create a new CA file to be used in a crt-list",                         cli_parse_new_cafile, NULL, NULL },
	{ { "add", "ssl", "ca-file", NULL },    "add ssl ca-file <cafile> <payload>      : add a certificate into the CA file",                                    cli_parse_set_cafile, NULL, NULL },
	{ { "set", "ssl", "ca-file", NULL },    "set ssl ca-file <cafile> <payload>      : replace a CA file",                                                     cli_parse_set_cafile, NULL, NULL },
	{ { "commit", "ssl", "ca-file", NULL }, "commit ssl ca-file <cafile>             : commit a CA file",                                                      cli_parse_commit_cafile, cli_io_handler_commit_cafile_crlfile, cli_release_commit_cafile },
	{ { "abort", "ssl", "ca-file", NULL },  "abort ssl ca-file <cafile>              : abort a transaction for a CA file",                                     cli_parse_abort_cafile, NULL, NULL },
	{ { "del", "ssl", "ca-file", NULL },    "del ssl ca-file <cafile>                : delete an unused CA file",                                              cli_parse_del_cafile, NULL, NULL },
	{ { "show", "ssl", "ca-file", NULL },   "show ssl ca-file [<cafile>[:<index>]]   : display the SSL CA files used in memory, or the details of a <cafile>, or a single certificate of index <index> of a CA file <cafile>", cli_parse_show_cafile, cli_io_handler_show_cafile, cli_release_show_cafile },

	{ { "new", "ssl", "crl-file", NULL },   "new ssl crl-file <crlfile>               : create a new CRL file to be used in a crt-list",                        cli_parse_new_crlfile, NULL, NULL },
	{ { "set", "ssl", "crl-file", NULL },   "set ssl crl-file <crlfile> <payload>    : replace a CRL file",                                                    cli_parse_set_crlfile, NULL, NULL },
	{ { "commit", "ssl", "crl-file", NULL },"commit ssl crl-file <crlfile>           : commit a CRL file",                                                     cli_parse_commit_crlfile, cli_io_handler_commit_cafile_crlfile, cli_release_commit_crlfile },
	{ { "abort", "ssl", "crl-file", NULL }, "abort ssl crl-file <crlfile>            : abort a transaction for a CRL file",                                    cli_parse_abort_crlfile, NULL, NULL },
	{ { "del", "ssl", "crl-file", NULL },   "del ssl crl-file <crlfile>              : delete an unused CRL file",                                             cli_parse_del_crlfile, NULL, NULL },
	{ { "show", "ssl", "crl-file", NULL },  "show ssl crl-file [<crlfile[:<index>>]] : display the SSL CRL files used in memory, or the details of a <crlfile>, or a single CRL of index <index> of CRL file <crlfile>", cli_parse_show_crlfile, cli_io_handler_show_crlfile, cli_release_show_crlfile },
	{ { NULL }, NULL, NULL, NULL }
}};

INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);

static char *current_crtbase = NULL;
static char *current_keybase = NULL;
static int crtstore_load = 0; /* did we already load in this crt-store */

struct ckch_conf_kws ckch_conf_kws[] = {
	{ "alias",                               -1,                 PARSE_TYPE_NONE, NULL,                                  NULL },
	{ "crt",    offsetof(struct ckch_conf, crt),    PARSE_TYPE_STR, ckch_conf_load_pem,           &current_crtbase },
	{ "key",    offsetof(struct ckch_conf, key),    PARSE_TYPE_STR, ckch_conf_load_key,           &current_keybase },
	{ "ocsp",   offsetof(struct ckch_conf, ocsp),   PARSE_TYPE_STR, ckch_conf_load_ocsp_response, &current_crtbase },
	{ "issuer", offsetof(struct ckch_conf, issuer), PARSE_TYPE_STR, ckch_conf_load_ocsp_issuer,   &current_crtbase },
	{ "sctl",   offsetof(struct ckch_conf, sctl),   PARSE_TYPE_STR, ckch_conf_load_sctl,          &current_crtbase },
	{ "ocsp-update", offsetof(struct ckch_conf, ocsp_update_mode), PARSE_TYPE_ONOFF, ocsp_update_init, NULL   },
	{ NULL,     -1,                                  PARSE_TYPE_STR, NULL,                                  NULL            }
};

/* crt-store does not try to find files, but use the stored filename */
int ckch_store_load_files(struct ckch_conf *f, struct ckch_store *c, int cli, char **err)
{
	int i;
	int err_code = 0;
	int rc = 1;
	struct ckch_data *d = c->data;

	for (i = 0; ckch_conf_kws[i].name; i++) {
		void *src = NULL;

		if (ckch_conf_kws[i].offset < 0)
			continue;

		if (!ckch_conf_kws[i].func)
			continue;

		src = (void *)((intptr_t)f + (ptrdiff_t)ckch_conf_kws[i].offset);

		switch (ckch_conf_kws[i].type) {
			case PARSE_TYPE_STR:
			{
				char *v;
				char *path;
				char **base = ckch_conf_kws[i].base;
				char path_base[PATH_MAX];

				v = *(char **)src;
				if (!v)
					goto next;

				path = v;
				if (base && *base && *path != '/') {
					int rv = snprintf(path_base, sizeof(path_base), "%s/%s", *base, path);
					if (rv >= sizeof(path_base)) {
						memprintf(err, "'%s/%s' : path too long", *base, path);
						err_code |= ERR_ALERT | ERR_FATAL;
						goto out;
					}
					path = path_base;
				}
				rc = ckch_conf_kws[i].func(path, NULL, d, cli, err);
				if (rc) {
					err_code |= ERR_ALERT | ERR_FATAL;
					memprintf(err, "%s '%s' cannot be read or parsed.", err && *err ? *err : "", path);
					goto out;
				}
				break;
			}

			case PARSE_TYPE_INT:
			case PARSE_TYPE_ONOFF:
			{
				int v = *(int *)src;
				rc = ckch_conf_kws[i].func(&v, NULL, d, cli, err);
				if (rc) {
					err_code |= ERR_ALERT | ERR_FATAL;
					memprintf(err, "%s '%d' cannot be read or parsed.", err && *err ? *err : "", v);
					goto out;
				}

				break;
			}

			default:
				break;
		}
next:
		;
	}

out:
	if (err_code & ERR_FATAL)
		ssl_sock_free_cert_key_and_chain_contents(d);
	ERR_clear_error();

	return err_code;
}

/* Parse a local crt-base or key-base for a crt-store */
static int crtstore_parse_path_base(char **args, int section_type, struct proxy *curpx, const struct proxy *defpx,
                        const char *file, int linenum, char **err)
{
	int err_code = ERR_NONE;

	if (!*args[1]) {
		memprintf(err, "parsing [%s:%d] : '%s' requires a <path> argument.",
		          file, linenum, args[0]);
		err_code |= ERR_ALERT | ERR_FATAL;
		goto out;
	}

	if (crtstore_load) {
		memprintf(err, "parsing [%s:%d] : '%s' can't be used after a load line, use it at the beginning of the section.",
		          file, linenum, args[0]);
		err_code |= ERR_ALERT | ERR_FATAL;
		goto out;
	}

	if (args[0][1] == 'r') {
		/* crt-base */
		free(current_crtbase);
		current_crtbase = strdup(args[1]);
	} else if (args[0][1] == 'e') {
		/* key-base */
		free(current_keybase);
		current_keybase = strdup(args[1]);
	}
out:
	return err_code;
}

/*
 * Check if ckch_conf <prev> and <new> are compatible:
 *
 * new \ prev | EMPTY | CRTLIST  | CRTSTORE
 * ----------------------------------------
 *  EMPTY     |  OK   |  X       |   OK
 * ----------------------------------------
 *  CRTLIST   |  X    | CMP      |  CMP
 * ----------------------------------------
 *
 * Return:
 *  1 when the 2 structures have different variables or are incompatible
 *  0 when the 2 structures have equal variables or are compatibles
 */
int ckch_conf_cmp(struct ckch_conf *prev, struct ckch_conf *new, char **err)
{
	int ret = 0;
	int i;

	if (!prev || !new)
	    return 1;

	/* compatibility check */

	if (prev->used == CKCH_CONF_SET_EMPTY) {
		if (new->used == CKCH_CONF_SET_CRTLIST) {
			memprintf(err, "%sCan't use the certificate previously defined without any keyword with these keywords:\n", *err ? *err : "");
			ret = 1;
		}
		if (new->used == CKCH_CONF_SET_EMPTY)
			return 0;

	} else if (prev->used == CKCH_CONF_SET_CRTLIST) {
		if (new->used == CKCH_CONF_SET_EMPTY) {
			memprintf(err, "%sCan't use the certificate previously defined with keywords without these keywords:\n", *err ? *err : "");
			ret = 1;
		}
	} else if (prev->used == CKCH_CONF_SET_CRTSTORE) {
		if (new->used == CKCH_CONF_SET_EMPTY)
			return 0;
	}


	for (i = 0; ckch_conf_kws[i].name != NULL; i++) {

		if (strcmp(ckch_conf_kws[i].name, "crt") == 0)
			continue;

		switch (ckch_conf_kws[i].type) {
			case PARSE_TYPE_STR: {
				char *avail1, *avail2;
				avail1 = *(char **)((intptr_t)prev + (ptrdiff_t)ckch_conf_kws[i].offset);
				avail2 = *(char **)((intptr_t)new + (ptrdiff_t)ckch_conf_kws[i].offset);

				/* must alert when strcmp is wrong, or when one of the field is NULL */
				if (((avail1 && avail2) && strcmp(avail1, avail2) != 0) || (!!avail1 ^ !!avail2)) {
					memprintf(err, "%s- different parameter '%s' : previously '%s' vs '%s'\n", *err ? *err : "", ckch_conf_kws[i].name, avail1, avail2);
					ret = 1;
				}
			}
			break;

			default:
				break;
		}
		/* special case for ocsp-update and default */
		if (strcmp(ckch_conf_kws[i].name, "ocsp-update") == 0) {
			int o1, o2; /* ocsp-update from the configuration */
			int q1, q2; /* final ocsp-update value (from default) */


			o1 = *(int *)((intptr_t)prev + (ptrdiff_t)ckch_conf_kws[i].offset);
			o2 = *(int *)((intptr_t)new + (ptrdiff_t)ckch_conf_kws[i].offset);

			q1 = (o1 == SSL_SOCK_OCSP_UPDATE_DFLT) ? global_ssl.ocsp_update.mode : o1;
			q2 = (o2 == SSL_SOCK_OCSP_UPDATE_DFLT) ? global_ssl.ocsp_update.mode : o2;

			if (q1 != q2) {
				int j = 1;
				int o = o1;
				int q = q1;
				memprintf(err, "%s- different parameter '%s' : previously ", *err ? *err : "", ckch_conf_kws[i].name);

				do {
					switch (o) {
						case SSL_SOCK_OCSP_UPDATE_DFLT:
							memprintf(err, "%s'default' (ocsp-update.mode %s)", *err ? *err : "", (q > 0) ? "on" : "off");
						break;
						case SSL_SOCK_OCSP_UPDATE_ON:
							memprintf(err, "%s'%s'", *err ? *err : "", "on");
						break;
						case SSL_SOCK_OCSP_UPDATE_OFF:
							memprintf(err, "%s'%s'", *err ? *err : "", "off");
						break;
					}
					o = o2;
					q = q2;
					if (j)
						memprintf(err, "%s vs ", *err ? *err : "");
				} while (j--);
				memprintf(err, "%s\n", *err ? *err : "");
				ret = 1;
			}
		}
	}

out:
	return ret;
}

/*
 *  Compare a previously generated ckch_conf with an empty one, using ckch_conf_cmp().
 */
int ckch_conf_cmp_empty(struct ckch_conf *prev, char **err)
{
	struct ckch_conf new = {};

	return ckch_conf_cmp(prev, &new, err);
}

/* parse ckch_conf keywords for crt-list */
int ckch_conf_parse(char **args, int cur_arg, struct ckch_conf *f, int *found, const char *file, int linenum, char **err)
{
	int i;
	int err_code = 0;

	for (i = 0; ckch_conf_kws[i].name != NULL; i++) {
		if (strcmp(ckch_conf_kws[i].name, args[cur_arg]) == 0) {
			void *target;
			*found = 1;
			target = (char **)((intptr_t)f + (ptrdiff_t)ckch_conf_kws[i].offset);

			if (ckch_conf_kws[i].type == PARSE_TYPE_STR) {
				char **t = target;

				*t = strdup(args[cur_arg + 1]);
				if (!*t) {
					ha_alert("parsing [%s:%d]: out of memory.\n", file, linenum);
					err_code |= ERR_ALERT | ERR_ABORT;
					goto out;
				}
			} else if (ckch_conf_kws[i].type == PARSE_TYPE_INT) {
				int *t = target;
				char *stop;

				*t = strtol(args[cur_arg + 1], &stop, 10);
				if (*stop != '\0') {
					memprintf(err, "parsing [%s:%d] : cannot parse '%s' value '%s', an integer is expected.\n",
					          file, linenum, args[cur_arg], args[cur_arg + 1]);
					err_code |= ERR_ALERT | ERR_FATAL;
					goto out;
				}
			} else if (ckch_conf_kws[i].type == PARSE_TYPE_ONOFF) {
				int *t = target;

				if (strcmp(args[cur_arg + 1], "on") == 0) {
					*t = 1;
				} else if (strcmp(args[cur_arg + 1], "off") == 0) {
					*t = -1;
				} else {
					memprintf(err, "parsing [%s:%d] : cannot parse '%s' value '%s', 'on' or 'off' is expected.\n",
					          file, linenum, args[cur_arg], args[cur_arg + 1]);
					err_code |= ERR_ALERT | ERR_FATAL;
					goto out;
				}
			}
			break;
		}
	}
out:
	return err_code;
}

/* freeing the content of a ckch_conf structure */
void ckch_conf_clean(struct ckch_conf *conf)
{
	free(conf->crt);
	free(conf->key);
	free(conf->ocsp);
	free(conf->issuer);
	free(conf->sctl);
}

static char current_crtstore_name[PATH_MAX] = {};

static int crtstore_parse_load(char **args, int section_type, struct proxy *curpx, const struct proxy *defpx,
                        const char *file, int linenum, char **err)
{
	int err_code = 0;
	int cur_arg = 0;
	struct ckch_conf f = {};
	struct ckch_store *c = NULL;
	char store_path[PATH_MAX]; /* complete path with crt_base */
	char alias_name[PATH_MAX]; /* complete alias name with the store prefix '@/' */
	char *final_name = NULL; /* name used as a key in the ckch_store */

	cur_arg++; /* skip "load" */

	while (*(args[cur_arg])) {
		int found = 0;

		if (strcmp("alias", args[cur_arg]) == 0) {
			int rv;

			if (*args[cur_arg + 1] == '/') {
				memprintf(err, "parsing [%s:%d] : cannot parse '%s' value '%s', '/' is forbidden as the first character.\n",
					  file, linenum, args[cur_arg], args[cur_arg + 1]);
				err_code |= ERR_ALERT | ERR_FATAL;
				goto out;
			}

			rv = snprintf(alias_name, sizeof(alias_name), "@%s/%s", current_crtstore_name, args[cur_arg + 1]);
			if (rv >= sizeof(alias_name)) {
				memprintf(err, "parsing [%s:%d] : cannot parse '%s' value '%s', too long, max len is %zd.\n",
					  file, linenum, args[cur_arg], args[cur_arg + 1], sizeof(alias_name));
				err_code |= ERR_ALERT | ERR_FATAL;
				goto out;
			}
			final_name = alias_name;
			found = 1;
		} else {
			err_code |= ckch_conf_parse(args, cur_arg, &f, &found, file, linenum, err);
			if (err_code & ERR_FATAL)
			goto out;
		}

		if (!found) {
			memprintf(err,"parsing [%s:%d] : '%s %s' in section 'crt-store': unknown keyword '%s'.",
			         file, linenum, args[0], args[cur_arg],args[cur_arg]);
			err_code |= ERR_ALERT | ERR_FATAL;
			goto out;
		}
		cur_arg += 2;
	}

	if (!f.crt) {
		memprintf(err,"parsing [%s:%d] : '%s' in section 'crt-store': mandatory 'crt' parameter not found.",
		         file, linenum, args[0]);
		err_code |= ERR_ALERT | ERR_FATAL;
		goto out;
	}

	crtstore_load = 1;

	if (!final_name) {
		final_name = f.crt;

		/* if no alias was used:
		 * - when a crt-store exists, use @store/crt
		 * - or use the absolute file (crt_base + crt)
		 * - or the relative file when no crt_base exists
		 */
		if (current_crtstore_name[0] != '\0') {
			int rv;

			/* add the crt-store name, avoid a double / if the crt starts by it */
			rv = snprintf(alias_name, sizeof(alias_name), "@%s%s%s", current_crtstore_name, f.crt[0] != '/' ? "/" : "", f.crt);
			if (rv >= sizeof(alias_name)) {
				memprintf(err, "parsing [%s:%d] : cannot parse '%s' value '%s', too long, max len is %zd.\n",
				          file, linenum, args[cur_arg], args[cur_arg + 1], sizeof(alias_name));
				err_code |= ERR_ALERT | ERR_FATAL;
				goto out;
			}
			final_name = alias_name;
		} else if (global_ssl.crt_base && *f.crt != '/') {
			int rv;
			/* When no crt_store name, complete the name in the ckch_tree with 'crt-base' */

			rv = snprintf(store_path, sizeof(store_path), "%s/%s", global_ssl.crt_base, f.crt);
			if (rv >= sizeof(store_path)) {
				memprintf(err, "'%s/%s' : path too long", global_ssl.crt_base, f.crt);
				err_code |= ERR_ALERT | ERR_FATAL;
				goto out;
			}
			final_name = store_path;
		}
	}
	/* process and insert the ckch_store */
	c = ckch_store_new(final_name);
	if (!c)
		goto alloc_error;

	err_code |= ckch_store_load_files(&f, c,  0, err);
	if (err_code & ERR_FATAL)
		goto out;

	c->conf = f;
	c->conf.used = CKCH_CONF_SET_CRTSTORE;

	if (ebst_insert(&ckchs_tree, &c->node) != &c->node) {
		memprintf(err,"parsing [%s:%d] : '%s' in section 'crt-store': store '%s' was already defined.",
		         file, linenum, args[0], c->path);
		err_code |= ERR_ALERT | ERR_FATAL;
		goto out;
	}

out:
	/* free ckch_conf content */
	if (err_code & ERR_FATAL)
		ckch_store_free(c);
	return err_code;

alloc_error:
	ha_alert("parsing [%s:%d]: out of memory.\n", file, linenum);
	err_code |= ERR_ALERT | ERR_ABORT;
	goto out;
}

/*
 * Parse "crt-store" section and create corresponding ckch_stores.
 *
 * The function returns 0 in success case, otherwise, it returns error
 * flags.
 */
static int cfg_parse_crtstore(const char *file, int linenum, char **args, int kwm)
{
	struct cfg_kw_list *kwl;
	const char *best;
	int index;
	int rc = 0;
	int err_code = 0;
	char *errmsg = NULL;

	if (strcmp(args[0], "crt-store") == 0) { /* new crt-store section */
		if (!*args[1]) {
			current_crtstore_name[0] = '\0';
		} else {
			rc = snprintf(current_crtstore_name, sizeof(current_crtstore_name), "%s", args[1]);
			if (rc >= sizeof(current_crtstore_name)) {
				ha_alert("parsing [%s:%d] : 'crt-store' <name> argument is too long.\n", file, linenum);
				current_crtstore_name[0] = '\0';
				err_code |= ERR_ALERT | ERR_FATAL | ERR_ABORT;
				goto out;
			}
		}

		if (*args[2]) {
			ha_alert("parsing [%s:%d] : 'crt-store' section only supports a <name> argument.\n", file, linenum);
			err_code |= ERR_ALERT | ERR_FATAL | ERR_ABORT;
			goto out;
		}
		/* copy the crt_base and key_base */
		ha_free(&current_crtbase);
		if (global_ssl.crt_base)
			current_crtbase = strdup(global_ssl.crt_base);
		ha_free(&current_keybase);
		if (global_ssl.key_base)
			current_keybase = strdup(global_ssl.key_base);
		crtstore_load = 0;

		goto out;
	}

	list_for_each_entry(kwl, &cfg_keywords.list, list) {
		for (index = 0; kwl->kw[index].kw != NULL; index++) {
			if (kwl->kw[index].section != CFG_CRTSTORE)
				continue;
			if (strcmp(kwl->kw[index].kw, args[0]) == 0) {
				if (check_kw_experimental(&kwl->kw[index], file, linenum, &errmsg)) {
					ha_alert("%s\n", errmsg);
					err_code |= ERR_ALERT | ERR_FATAL | ERR_ABORT;
					goto out;
				}

				/* prepare error message just in case */
				rc = kwl->kw[index].parse(args, CFG_CRTSTORE, NULL, NULL, file, linenum, &errmsg);
				if (rc & ERR_ALERT) {
					ha_alert("parsing [%s:%d] : %s\n", file, linenum, errmsg);
					err_code |= rc;
					goto out;
				}
				else if (rc & ERR_WARN) {
					ha_warning("parsing [%s:%d] : %s\n", file, linenum, errmsg);
					err_code |= rc;
					goto out;
				}
				goto out;
			}
		}
	}

	best = cfg_find_best_match(args[0], &cfg_keywords.list, CFG_CRTSTORE, NULL);
	if (best)
		ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section; did you mean '%s' maybe ?\n", file, linenum, args[0], cursection, best);
	else
		ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
	err_code |= ERR_ALERT | ERR_FATAL;
	goto out;

out:
	if (err_code & ERR_FATAL)
		err_code |= ERR_ABORT;
	free(errmsg);
	return err_code;
}

static int cfg_post_parse_crtstore()
{
	current_crtstore_name[0] = '\0';
	ha_free(&current_crtbase);
	ha_free(&current_keybase);

	return ERR_NONE;
}

REGISTER_CONFIG_SECTION("crt-store", cfg_parse_crtstore, cfg_post_parse_crtstore);

static struct cfg_kw_list cfg_kws = {ILH, {
	{ CFG_CRTSTORE, "crt-base", crtstore_parse_path_base },
	{ CFG_CRTSTORE, "key-base", crtstore_parse_path_base },
	{ CFG_CRTSTORE, "load", crtstore_parse_load },
	{ 0, NULL, NULL },
}};
INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);