summaryrefslogtreecommitdiffstats
path: root/src/shrpx_tls.cc
blob: 00cf1ca90e94785846c5bea5349e350843f59436 (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
/*
 * nghttp2 - HTTP/2 C Library
 *
 * Copyright (c) 2012 Tatsuhiro Tsujikawa
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#include "shrpx_tls.h"

#ifdef HAVE_SYS_SOCKET_H
#  include <sys/socket.h>
#endif // HAVE_SYS_SOCKET_H
#ifdef HAVE_NETDB_H
#  include <netdb.h>
#endif // HAVE_NETDB_H
#include <netinet/tcp.h>
#include <pthread.h>
#include <sys/types.h>

#include <vector>
#include <string>
#include <iomanip>

#include <iostream>

#include "ssl_compat.h"

#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/rand.h>
#include <openssl/dh.h>
#ifndef OPENSSL_NO_OCSP
#  include <openssl/ocsp.h>
#endif // OPENSSL_NO_OCSP
#if OPENSSL_3_0_0_API
#  include <openssl/params.h>
#  include <openssl/core_names.h>
#  include <openssl/decoder.h>
#endif // OPENSSL_3_0_0_API
#ifdef NGHTTP2_OPENSSL_IS_BORINGSSL
#  include <openssl/hmac.h>
#endif // NGHTTP2_OPENSSL_IS_BORINGSSL

#include <nghttp2/nghttp2.h>

#ifdef ENABLE_HTTP3
#  include <ngtcp2/ngtcp2.h>
#  include <ngtcp2/ngtcp2_crypto.h>
#  ifdef HAVE_LIBNGTCP2_CRYPTO_QUICTLS
#    include <ngtcp2/ngtcp2_crypto_quictls.h>
#  endif // HAVE_LIBNGTCP2_CRYPTO_QUICTLS
#  ifdef HAVE_LIBNGTCP2_CRYPTO_BORINGSSL
#    include <ngtcp2/ngtcp2_crypto_boringssl.h>
#  endif // HAVE_LIBNGTCP2_CRYPTO_BORINGSSL
#endif   // ENABLE_HTTP3

#ifdef HAVE_LIBBROTLI
#  include <brotli/encode.h>
#  include <brotli/decode.h>
#endif // HAVE_LIBBROTLI

#include "shrpx_log.h"
#include "shrpx_client_handler.h"
#include "shrpx_config.h"
#include "shrpx_worker.h"
#include "shrpx_downstream_connection_pool.h"
#include "shrpx_http2_session.h"
#include "shrpx_memcached_request.h"
#include "shrpx_memcached_dispatcher.h"
#include "shrpx_connection_handler.h"
#ifdef ENABLE_HTTP3
#  include "shrpx_http3_upstream.h"
#endif // ENABLE_HTTP3
#include "util.h"
#include "tls.h"
#include "template.h"
#include "timegm.h"

using namespace nghttp2;
using namespace std::chrono_literals;

namespace shrpx {

namespace tls {

namespace {
int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  if (!preverify_ok) {
    int err = X509_STORE_CTX_get_error(ctx);
    int depth = X509_STORE_CTX_get_error_depth(ctx);
    if (err == X509_V_ERR_CERT_HAS_EXPIRED && depth == 0 &&
        get_config()->tls.client_verify.tolerate_expired) {
      LOG(INFO) << "The client certificate has expired, but is accepted by "
                   "configuration";
      return 1;
    }
    LOG(ERROR) << "client certificate verify error:num=" << err << ":"
               << X509_verify_cert_error_string(err) << ":depth=" << depth;
  }
  return preverify_ok;
}
} // namespace

int set_alpn_prefs(std::vector<unsigned char> &out,
                   const std::vector<StringRef> &protos) {
  size_t len = 0;

  for (const auto &proto : protos) {
    if (proto.size() > 255) {
      LOG(FATAL) << "Too long ALPN identifier: " << proto.size();
      return -1;
    }

    len += 1 + proto.size();
  }

  if (len > (1 << 16) - 1) {
    LOG(FATAL) << "Too long ALPN identifier list: " << len;
    return -1;
  }

  out.resize(len);
  auto ptr = out.data();

  for (const auto &proto : protos) {
    *ptr++ = proto.size();
    ptr = std::copy(std::begin(proto), std::end(proto), ptr);
  }

  return 0;
}

namespace {
int ssl_pem_passwd_cb(char *buf, int size, int rwflag, void *user_data) {
  auto config = static_cast<Config *>(user_data);
  auto len = static_cast<int>(config->tls.private_key_passwd.size());
  if (size < len + 1) {
    LOG(ERROR) << "ssl_pem_passwd_cb: buf is too small " << size;
    return 0;
  }
  // Copy string including last '\0'.
  memcpy(buf, config->tls.private_key_passwd.data(), len + 1);
  return len;
}
} // namespace

namespace {
std::shared_ptr<std::vector<uint8_t>>
get_ocsp_data(TLSContextData *tls_ctx_data) {
#ifdef HAVE_ATOMIC_STD_SHARED_PTR
  return tls_ctx_data->ocsp_data.load(std::memory_order_acquire);
#else  // !HAVE_ATOMIC_STD_SHARED_PTR
  std::lock_guard<std::mutex> g(tls_ctx_data->mu);
  return tls_ctx_data->ocsp_data;
#endif // !HAVE_ATOMIC_STD_SHARED_PTR
}
} // namespace

namespace {
void set_ocsp_response(SSL *ssl) {
#ifdef NGHTTP2_OPENSSL_IS_BORINGSSL
  auto tls_ctx_data =
      static_cast<TLSContextData *>(SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  auto data = get_ocsp_data(tls_ctx_data);

  if (!data) {
    return;
  }

  SSL_set_ocsp_response(ssl, data->data(), data->size());
#endif // NGHTTP2_OPENSSL_IS_BORINGSSL
}
} // namespace

namespace {
// *al is set to SSL_AD_UNRECOGNIZED_NAME by openssl, so we don't have
// to set it explicitly.
int servername_callback(SSL *ssl, int *al, void *arg) {
  auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
  auto handler = static_cast<ClientHandler *>(conn->data);
  auto worker = handler->get_worker();

  auto rawhost = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  if (rawhost == nullptr) {
    set_ocsp_response(ssl);

    return SSL_TLSEXT_ERR_NOACK;
  }

  auto len = strlen(rawhost);
  // NI_MAXHOST includes terminal NULL.
  if (len == 0 || len + 1 > NI_MAXHOST) {
    set_ocsp_response(ssl);

    return SSL_TLSEXT_ERR_NOACK;
  }

  std::array<char, NI_MAXHOST> buf;

  auto end_buf = std::copy_n(rawhost, len, std::begin(buf));

  util::inp_strlower(std::begin(buf), end_buf);

  auto hostname = StringRef{std::begin(buf), end_buf};

#ifdef ENABLE_HTTP3
  auto cert_tree = conn->proto == Proto::HTTP3
                       ? worker->get_quic_cert_lookup_tree()
                       : worker->get_cert_lookup_tree();
#else  // !ENABLE_HTTP3
  auto cert_tree = worker->get_cert_lookup_tree();
#endif // !ENABLE_HTTP3

  auto idx = cert_tree->lookup(hostname);
  if (idx == -1) {
    set_ocsp_response(ssl);

    return SSL_TLSEXT_ERR_NOACK;
  }

  handler->set_tls_sni(hostname);

  auto conn_handler = worker->get_connection_handler();

#ifdef ENABLE_HTTP3
  const auto &ssl_ctx_list = conn->proto == Proto::HTTP3
                                 ? conn_handler->get_quic_indexed_ssl_ctx(idx)
                                 : conn_handler->get_indexed_ssl_ctx(idx);
#else  // !ENABLE_HTTP3
  const auto &ssl_ctx_list = conn_handler->get_indexed_ssl_ctx(idx);
#endif // !ENABLE_HTTP3

  assert(!ssl_ctx_list.empty());

#ifdef NGHTTP2_GENUINE_OPENSSL
  auto num_sigalgs =
      SSL_get_sigalgs(ssl, 0, nullptr, nullptr, nullptr, nullptr, nullptr);

  for (idx = 0; idx < num_sigalgs; ++idx) {
    int signhash;

    SSL_get_sigalgs(ssl, idx, nullptr, nullptr, &signhash, nullptr, nullptr);
    switch (signhash) {
    case NID_ecdsa_with_SHA256:
    case NID_ecdsa_with_SHA384:
    case NID_ecdsa_with_SHA512:
      break;
    default:
      continue;
    }

    break;
  }

  if (idx == num_sigalgs) {
    SSL_set_SSL_CTX(ssl, ssl_ctx_list[0]);

    return SSL_TLSEXT_ERR_OK;
  }

  auto num_shared_curves = SSL_get_shared_curve(ssl, -1);

  for (auto i = 0; i < num_shared_curves; ++i) {
    auto shared_curve = SSL_get_shared_curve(ssl, i);
#  if OPENSSL_3_0_0_API
    // It looks like only short name is defined in OpenSSL.  No idea
    // which one to use because it is unknown that which one
    // EVP_PKEY_get_utf8_string_param("group") returns.
    auto shared_curve_name = OBJ_nid2sn(shared_curve);
    if (shared_curve_name == nullptr) {
      continue;
    }
#  endif // OPENSSL_3_0_0_API

    for (auto ssl_ctx : ssl_ctx_list) {
      auto cert = SSL_CTX_get0_certificate(ssl_ctx);
      auto pubkey = X509_get0_pubkey(cert);

      if (EVP_PKEY_base_id(pubkey) != EVP_PKEY_EC) {
        continue;
      }

#  if OPENSSL_3_0_0_API
      std::array<char, 64> curve_name;
      if (!EVP_PKEY_get_utf8_string_param(pubkey, "group", curve_name.data(),
                                          curve_name.size(), nullptr)) {
        continue;
      }

      if (strcmp(shared_curve_name, curve_name.data()) == 0) {
        SSL_set_SSL_CTX(ssl, ssl_ctx);
        return SSL_TLSEXT_ERR_OK;
      }
#  else  // !OPENSSL_3_0_0_API
      auto eckey = EVP_PKEY_get0_EC_KEY(pubkey);
      if (eckey == nullptr) {
        continue;
      }

      auto ecgroup = EC_KEY_get0_group(eckey);
      auto cert_curve = EC_GROUP_get_curve_name(ecgroup);

      if (shared_curve == cert_curve) {
        SSL_set_SSL_CTX(ssl, ssl_ctx);
        return SSL_TLSEXT_ERR_OK;
      }
#  endif // !OPENSSL_3_0_0_API
    }
  }
#endif // NGHTTP2_GENUINE_OPENSSL

  SSL_set_SSL_CTX(ssl, ssl_ctx_list[0]);

  set_ocsp_response(ssl);

  return SSL_TLSEXT_ERR_OK;
}
} // namespace

#ifndef NGHTTP2_OPENSSL_IS_BORINGSSL
namespace {
int ocsp_resp_cb(SSL *ssl, void *arg) {
  auto ssl_ctx = SSL_get_SSL_CTX(ssl);
  auto tls_ctx_data =
      static_cast<TLSContextData *>(SSL_CTX_get_app_data(ssl_ctx));

  auto data = get_ocsp_data(tls_ctx_data);

  if (!data) {
    return SSL_TLSEXT_ERR_OK;
  }

  auto buf = static_cast<uint8_t *>(
      CRYPTO_malloc(data->size(), NGHTTP2_FILE_NAME, __LINE__));

  if (!buf) {
    return SSL_TLSEXT_ERR_OK;
  }

  std::copy(std::begin(*data), std::end(*data), buf);

  SSL_set_tlsext_status_ocsp_resp(ssl, buf, data->size());

  return SSL_TLSEXT_ERR_OK;
}
} // namespace
#endif // NGHTTP2_OPENSSL_IS_BORINGSSL

constexpr auto MEMCACHED_SESSION_CACHE_KEY_PREFIX =
    "nghttpx:tls-session-cache:"_sr;

namespace {
int tls_session_client_new_cb(SSL *ssl, SSL_SESSION *session) {
  auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
  if (conn->tls.client_session_cache == nullptr) {
    return 0;
  }

  try_cache_tls_session(conn->tls.client_session_cache, session,
                        std::chrono::steady_clock::now());

  return 0;
}
} // namespace

namespace {
int tls_session_new_cb(SSL *ssl, SSL_SESSION *session) {
  auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
  auto handler = static_cast<ClientHandler *>(conn->data);
  auto worker = handler->get_worker();
  auto dispatcher = worker->get_session_cache_memcached_dispatcher();
  auto &balloc = handler->get_block_allocator();

#ifdef TLS1_3_VERSION
  if (SSL_version(ssl) == TLS1_3_VERSION) {
    return 0;
  }
#endif // TLS1_3_VERSION

  const unsigned char *id;
  unsigned int idlen;

  id = SSL_SESSION_get_id(session, &idlen);

  if (LOG_ENABLED(INFO)) {
    LOG(INFO) << "Memcached: cache session, id="
              << util::format_hex(std::span{id, idlen});
  }

  auto req = std::make_unique<MemcachedRequest>();
  req->op = MemcachedOp::ADD;
  req->key = MEMCACHED_SESSION_CACHE_KEY_PREFIX;
  req->key +=
      util::format_hex(balloc, std::span{id, static_cast<size_t>(idlen)});

  auto sessionlen = i2d_SSL_SESSION(session, nullptr);
  req->value.resize(sessionlen);
  auto buf = &req->value[0];
  i2d_SSL_SESSION(session, &buf);
  req->expiry = 12_h;
  req->cb = [](MemcachedRequest *req, MemcachedResult res) {
    if (LOG_ENABLED(INFO)) {
      LOG(INFO) << "Memcached: session cache done.  key=" << req->key
                << ", status_code=" << static_cast<uint16_t>(res.status_code)
                << ", value="
                << std::string(std::begin(res.value), std::end(res.value));
    }
    if (res.status_code != MemcachedStatusCode::NO_ERROR) {
      LOG(WARN) << "Memcached: failed to cache session key=" << req->key
                << ", status_code=" << static_cast<uint16_t>(res.status_code)
                << ", value="
                << std::string(std::begin(res.value), std::end(res.value));
    }
  };
  assert(!req->canceled);

  dispatcher->add_request(std::move(req));

  return 0;
}
} // namespace

namespace {
SSL_SESSION *tls_session_get_cb(SSL *ssl, const unsigned char *id, int idlen,
                                int *copy) {
  auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
  auto handler = static_cast<ClientHandler *>(conn->data);
  auto worker = handler->get_worker();
  auto dispatcher = worker->get_session_cache_memcached_dispatcher();
  auto &balloc = handler->get_block_allocator();

  if (idlen == 0) {
    return nullptr;
  }

  if (conn->tls.cached_session) {
    if (LOG_ENABLED(INFO)) {
      LOG(INFO) << "Memcached: found cached session, id="
                << util::format_hex(std::span{id, static_cast<size_t>(idlen)});
    }

    // This is required, without this, memory leak occurs.
    *copy = 0;

    auto session = conn->tls.cached_session;
    conn->tls.cached_session = nullptr;
    return session;
  }

  if (LOG_ENABLED(INFO)) {
    LOG(INFO) << "Memcached: get cached session, id="
              << util::format_hex(std::span{id, static_cast<size_t>(idlen)});
  }

  auto req = std::make_unique<MemcachedRequest>();
  req->op = MemcachedOp::GET;
  req->key = MEMCACHED_SESSION_CACHE_KEY_PREFIX;
  req->key +=
      util::format_hex(balloc, std::span{id, static_cast<size_t>(idlen)});
  req->cb = [conn](MemcachedRequest *, MemcachedResult res) {
    if (LOG_ENABLED(INFO)) {
      LOG(INFO) << "Memcached: returned status code "
                << static_cast<uint16_t>(res.status_code);
    }

    // We might stop reading, so start it again
    conn->rlimit.startw();
    ev_timer_again(conn->loop, &conn->rt);

    conn->wlimit.startw();
    ev_timer_again(conn->loop, &conn->wt);

    conn->tls.cached_session_lookup_req = nullptr;
    if (res.status_code != MemcachedStatusCode::NO_ERROR) {
      conn->tls.handshake_state = TLSHandshakeState::CANCEL_SESSION_CACHE;
      return;
    }

    const uint8_t *p = res.value.data();

    auto session = d2i_SSL_SESSION(nullptr, &p, res.value.size());
    if (!session) {
      if (LOG_ENABLED(INFO)) {
        LOG(INFO) << "cannot materialize session";
      }
      conn->tls.handshake_state = TLSHandshakeState::CANCEL_SESSION_CACHE;
      return;
    }

    conn->tls.cached_session = session;
    conn->tls.handshake_state = TLSHandshakeState::GOT_SESSION_CACHE;
  };

  conn->tls.handshake_state = TLSHandshakeState::WAIT_FOR_SESSION_CACHE;
  conn->tls.cached_session_lookup_req = req.get();

  dispatcher->add_request(std::move(req));

  return nullptr;
}
} // namespace

namespace {
int ticket_key_cb(SSL *ssl, unsigned char *key_name, unsigned char *iv,
                  EVP_CIPHER_CTX *ctx,
#if OPENSSL_3_0_0_API
                  EVP_MAC_CTX *hctx,
#else  // !OPENSSL_3_0_0_API
                  HMAC_CTX *hctx,
#endif // !OPENSSL_3_0_0_API
                  int enc) {
  auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
  auto handler = static_cast<ClientHandler *>(conn->data);
  auto worker = handler->get_worker();
  auto ticket_keys = worker->get_ticket_keys();

  if (!ticket_keys) {
    // No ticket keys available.
    return -1;
  }

  auto &keys = ticket_keys->keys;
  assert(!keys.empty());

  if (enc) {
    if (RAND_bytes(iv, EVP_MAX_IV_LENGTH) == 0) {
      if (LOG_ENABLED(INFO)) {
        CLOG(INFO, handler) << "session ticket key: RAND_bytes failed";
      }
      return -1;
    }

    auto &key = keys[0];

    if (LOG_ENABLED(INFO)) {
      CLOG(INFO, handler) << "encrypt session ticket key: "
                          << util::format_hex(key.data.name);
    }

    std::copy(std::begin(key.data.name), std::end(key.data.name), key_name);

    EVP_EncryptInit_ex(ctx, get_config()->tls.ticket.cipher, nullptr,
                       key.data.enc_key.data(), iv);
#if OPENSSL_3_0_0_API
    auto params = std::to_array({
        OSSL_PARAM_construct_octet_string(
            OSSL_MAC_PARAM_KEY, key.data.hmac_key.data(), key.hmac_keylen),
        OSSL_PARAM_construct_utf8_string(
            OSSL_MAC_PARAM_DIGEST,
            const_cast<char *>(EVP_MD_get0_name(key.hmac)), 0),
        OSSL_PARAM_construct_end(),
    });
    if (!EVP_MAC_CTX_set_params(hctx, params.data())) {
      if (LOG_ENABLED(INFO)) {
        CLOG(INFO, handler) << "EVP_MAC_CTX_set_params failed";
      }
      return -1;
    }
#else  // !OPENSSL_3_0_0_API
    HMAC_Init_ex(hctx, key.data.hmac_key.data(), key.hmac_keylen, key.hmac,
                 nullptr);
#endif // !OPENSSL_3_0_0_API
    return 1;
  }

  size_t i;
  for (i = 0; i < keys.size(); ++i) {
    auto &key = keys[i];
    if (std::equal(std::begin(key.data.name), std::end(key.data.name),
                   key_name)) {
      break;
    }
  }

  if (i == keys.size()) {
    if (LOG_ENABLED(INFO)) {
      CLOG(INFO, handler) << "session ticket key "
                          << util::format_hex(std::span{key_name, 16})
                          << " not found";
    }
    return 0;
  }

  if (LOG_ENABLED(INFO)) {
    CLOG(INFO, handler) << "decrypt session ticket key: "
                        << util::format_hex(std::span{key_name, 16});
  }

  auto &key = keys[i];
#if OPENSSL_3_0_0_API
  auto params = std::to_array({
      OSSL_PARAM_construct_octet_string(
          OSSL_MAC_PARAM_KEY, key.data.hmac_key.data(), key.hmac_keylen),
      OSSL_PARAM_construct_utf8_string(
          OSSL_MAC_PARAM_DIGEST, const_cast<char *>(EVP_MD_get0_name(key.hmac)),
          0),
      OSSL_PARAM_construct_end(),
  });
  if (!EVP_MAC_CTX_set_params(hctx, params.data())) {
    if (LOG_ENABLED(INFO)) {
      CLOG(INFO, handler) << "EVP_MAC_CTX_set_params failed";
    }
    return -1;
  }
#else  // !OPENSSL_3_0_0_API
  HMAC_Init_ex(hctx, key.data.hmac_key.data(), key.hmac_keylen, key.hmac,
               nullptr);
#endif // !OPENSSL_3_0_0_API
  EVP_DecryptInit_ex(ctx, key.cipher, nullptr, key.data.enc_key.data(), iv);

#ifdef TLS1_3_VERSION
  // If ticket_key_cb is not set, OpenSSL always renew ticket for
  // TLSv1.3.
  if (SSL_version(ssl) == TLS1_3_VERSION) {
    return 2;
  }
#endif // TLS1_3_VERSION

  return i == 0 ? 1 : 2;
}
} // namespace

namespace {
void info_callback(const SSL *ssl, int where, int ret) {
#ifdef TLS1_3_VERSION
  // TLSv1.3 has no renegotiation.
  if (SSL_version(ssl) == TLS1_3_VERSION) {
    return;
  }
#endif // TLS1_3_VERSION

  // To mitigate possible DOS attack using lots of renegotiations, we
  // disable renegotiation. Since OpenSSL does not provide an easy way
  // to disable it, we check that renegotiation is started in this
  // callback.
  if (where & SSL_CB_HANDSHAKE_START) {
    auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
    if (conn && conn->tls.initial_handshake_done) {
      auto handler = static_cast<ClientHandler *>(conn->data);
      if (LOG_ENABLED(INFO)) {
        CLOG(INFO, handler) << "TLS renegotiation started";
      }
      handler->start_immediate_shutdown();
    }
  }
}
} // namespace

namespace {
int alpn_select_proto_cb(SSL *ssl, const unsigned char **out,
                         unsigned char *outlen, const unsigned char *in,
                         unsigned int inlen, void *arg) {
  // We assume that get_config()->alpn_list contains ALPN protocol
  // identifier sorted by preference order.  So we just break when we
  // found the first overlap.
  for (const auto &target_proto_id : get_config()->tls.alpn_list) {
    for (auto p = in, end = in + inlen; p < end;) {
      auto proto_id = p + 1;
      auto proto_len = *p;

      if (proto_id + proto_len <= end &&
          target_proto_id == StringRef{proto_id, proto_len}) {

        *out = reinterpret_cast<const unsigned char *>(proto_id);
        *outlen = proto_len;

        return SSL_TLSEXT_ERR_OK;
      }

      p += 1 + proto_len;
    }
  }

  return SSL_TLSEXT_ERR_NOACK;
}
} // namespace

#ifdef ENABLE_HTTP3
namespace {
int quic_alpn_select_proto_cb(SSL *ssl, const unsigned char **out,
                              unsigned char *outlen, const unsigned char *in,
                              unsigned int inlen, void *arg) {
  constexpr StringRef alpnlist[] = {
      "h3"_sr,
      "h3-29"_sr,
  };

  for (auto &alpn : alpnlist) {
    for (auto p = in, end = in + inlen; p < end;) {
      auto proto_id = p + 1;
      auto proto_len = *p;

      if (alpn.size() == proto_len &&
          memcmp(alpn.byte(), proto_id, alpn.size()) == 0) {
        *out = proto_id;
        *outlen = proto_len;

        return SSL_TLSEXT_ERR_OK;
      }

      p += 1 + proto_len;
    }
  }

  return SSL_TLSEXT_ERR_ALERT_FATAL;
}
} // namespace
#endif // ENABLE_HTTP3

#ifdef NGHTTP2_GENUINE_OPENSSL
namespace {
int sct_add_cb(SSL *ssl, unsigned int ext_type, unsigned int context,
               const unsigned char **out, size_t *outlen, X509 *x,
               size_t chainidx, int *al, void *add_arg) {
  assert(ext_type == TLSEXT_TYPE_signed_certificate_timestamp);

  auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
  if (!conn->tls.sct_requested) {
    return 0;
  }

  if (LOG_ENABLED(INFO)) {
    LOG(INFO) << "sct_add_cb is called, chainidx=" << chainidx << ", x=" << x
              << ", context=" << log::hex << context;
  }

  // We only have SCTs for leaf certificate.
  if (chainidx != 0) {
    return 0;
  }

  auto ssl_ctx = SSL_get_SSL_CTX(ssl);
  auto tls_ctx_data =
      static_cast<TLSContextData *>(SSL_CTX_get_app_data(ssl_ctx));

  *out = tls_ctx_data->sct_data.data();
  *outlen = tls_ctx_data->sct_data.size();

  return 1;
}
} // namespace

namespace {
void sct_free_cb(SSL *ssl, unsigned int ext_type, unsigned int context,
                 const unsigned char *out, void *add_arg) {
  assert(ext_type == TLSEXT_TYPE_signed_certificate_timestamp);
}
} // namespace

namespace {
int sct_parse_cb(SSL *ssl, unsigned int ext_type, unsigned int context,
                 const unsigned char *in, size_t inlen, X509 *x,
                 size_t chainidx, int *al, void *parse_arg) {
  assert(ext_type == TLSEXT_TYPE_signed_certificate_timestamp);
  // client SHOULD send 0 length extension_data, but it is still
  // SHOULD, and not MUST.

  // For TLSv1.3 Certificate message, sct_add_cb is called even if
  // client has not sent signed_certificate_timestamp extension in its
  // ClientHello.  Explicitly remember that client has included it
  // here.
  auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
  conn->tls.sct_requested = true;

  return 1;
}
} // namespace

#endif // NGHTTP2_GENUINE_OPENSSL

#ifndef OPENSSL_NO_PSK
namespace {
unsigned int psk_server_cb(SSL *ssl, const char *identity, unsigned char *psk,
                           unsigned int max_psk_len) {
  auto config = get_config();
  auto &tlsconf = config->tls;

  auto it = tlsconf.psk_secrets.find(StringRef{identity});
  if (it == std::end(tlsconf.psk_secrets)) {
    return 0;
  }

  auto &secret = (*it).second;
  if (secret.size() > max_psk_len) {
    LOG(ERROR) << "The size of PSK secret is " << secret.size()
               << ", but the acceptable maximum size is" << max_psk_len;
    return 0;
  }

  std::copy(std::begin(secret), std::end(secret), psk);

  return static_cast<unsigned int>(secret.size());
}
} // namespace
#endif // !OPENSSL_NO_PSK

#ifndef OPENSSL_NO_PSK
namespace {
unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity_out,
                           unsigned int max_identity_len, unsigned char *psk,
                           unsigned int max_psk_len) {
  auto config = get_config();
  auto &tlsconf = config->tls;

  auto &identity = tlsconf.client.psk.identity;
  auto &secret = tlsconf.client.psk.secret;

  if (identity.empty()) {
    return 0;
  }

  if (identity.size() + 1 > max_identity_len) {
    LOG(ERROR) << "The size of PSK identity is " << identity.size()
               << ", but the acceptable maximum size is " << max_identity_len;
    return 0;
  }

  if (secret.size() > max_psk_len) {
    LOG(ERROR) << "The size of PSK secret is " << secret.size()
               << ", but the acceptable maximum size is " << max_psk_len;
    return 0;
  }

  *std::copy(std::begin(identity), std::end(identity), identity_out) = '\0';
  std::copy(std::begin(secret), std::end(secret), psk);

  return static_cast<unsigned int>(secret.size());
}
} // namespace
#endif // !OPENSSL_NO_PSK

#if defined(NGHTTP2_OPENSSL_IS_BORINGSSL) && defined(HAVE_LIBBROTLI)
namespace {
int cert_compress(SSL *ssl, CBB *out, const uint8_t *in, size_t in_len) {
  uint8_t *dest;

  size_t compressed_size = BrotliEncoderMaxCompressedSize(in_len);
  if (compressed_size == 0) {
    LOG(ERROR) << "BrotliEncoderMaxCompressedSize failed";

    return 0;
  }

  if (LOG_ENABLED(INFO)) {
    LOG(INFO) << "Maximum compressed size is " << compressed_size
              << " bytes against input " << in_len << " bytes";
  }

  if (!CBB_reserve(out, &dest, compressed_size)) {
    LOG(ERROR) << "CBB_reserve failed";

    return 0;
  }

  if (BrotliEncoderCompress(BROTLI_MAX_QUALITY, BROTLI_DEFAULT_WINDOW,
                            BROTLI_MODE_GENERIC, in_len, in, &compressed_size,
                            dest) != BROTLI_TRUE) {
    LOG(ERROR) << "BrotliEncoderCompress failed";

    return 0;
  }

  if (LOG_ENABLED(INFO)) {
    LOG(INFO) << "BrotliEncoderCompress succeeded, produced " << compressed_size
              << " bytes, " << (in_len - compressed_size) * 100 / in_len
              << "% reduction";
  }

  if (!CBB_did_write(out, compressed_size)) {
    LOG(ERROR) << "CBB_did_write failed";

    return 0;
  }

  return 1;
}

int cert_decompress(SSL *ssl, CRYPTO_BUFFER **out, size_t uncompressed_len,
                    const uint8_t *in, size_t in_len) {
  uint8_t *dest;
  auto buf = CRYPTO_BUFFER_alloc(&dest, uncompressed_len);
  auto len = uncompressed_len;

  if (BrotliDecoderDecompress(in_len, in, &len, dest) !=
      BROTLI_DECODER_RESULT_SUCCESS) {
    LOG(ERROR) << "BrotliDecoderDecompress failed";

    CRYPTO_BUFFER_free(buf);

    return 0;
  }

  if (uncompressed_len != len) {
    LOG(ERROR) << "Unexpected uncompressed length: expected "
               << uncompressed_len << " bytes, actual " << len << " bytes";

    CRYPTO_BUFFER_free(buf);

    return 0;
  }

  *out = buf;

  return 1;
}
} // namespace
#endif // NGHTTP2_OPENSSL_IS_BORINGSSL && HAVE_LIBBROTLI

struct TLSProtocol {
  StringRef name;
  long int mask;
};

constexpr TLSProtocol TLS_PROTOS[] = {
    TLSProtocol{"TLSv1.2"_sr, SSL_OP_NO_TLSv1_2},
    TLSProtocol{"TLSv1.1"_sr, SSL_OP_NO_TLSv1_1},
    TLSProtocol{"TLSv1.0"_sr, SSL_OP_NO_TLSv1}};

long int create_tls_proto_mask(const std::vector<StringRef> &tls_proto_list) {
  long int res = 0;

  for (auto &supported : TLS_PROTOS) {
    auto ok = false;
    for (auto &name : tls_proto_list) {
      if (util::strieq(supported.name, name)) {
        ok = true;
        break;
      }
    }
    if (!ok) {
      res |= supported.mask;
    }
  }
  return res;
}

SSL_CTX *create_ssl_context(const char *private_key_file, const char *cert_file,
                            const std::vector<uint8_t> &sct_data
#ifdef HAVE_NEVERBLEED
                            ,
                            neverbleed_t *nb
#endif // HAVE_NEVERBLEED
) {
  auto ssl_ctx = SSL_CTX_new(TLS_server_method());
  if (!ssl_ctx) {
    LOG(FATAL) << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }

  auto ssl_opts = (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
                  SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION |
                  SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
                  SSL_OP_SINGLE_ECDH_USE | SSL_OP_SINGLE_DH_USE |
                  SSL_OP_CIPHER_SERVER_PREFERENCE
#ifdef NGHTTP2_GENUINE_OPENSSL
                  // The reason for disabling built-in anti-replay in
                  // OpenSSL is that it only works if client gets back
                  // to the same server.  The freshness check
                  // described in
                  // https://tools.ietf.org/html/rfc8446#section-8.3
                  // is still performed.
                  | SSL_OP_NO_ANTI_REPLAY
#endif // NGHTTP2_GENUINE_OPENSSL
      ;

  auto config = mod_config();
  auto &tlsconf = config->tls;

#ifdef SSL_OP_ENABLE_KTLS
  if (tlsconf.ktls) {
    ssl_opts |= SSL_OP_ENABLE_KTLS;
  }
#endif // SSL_OP_ENABLE_KTLS

  SSL_CTX_set_options(ssl_ctx, ssl_opts | tlsconf.tls_proto_mask);

  if (nghttp2::tls::ssl_ctx_set_proto_versions(
          ssl_ctx, tlsconf.min_proto_version, tlsconf.max_proto_version) != 0) {
    LOG(FATAL) << "Could not set TLS protocol version";
    DIE();
  }

  const unsigned char sid_ctx[] = "shrpx";
  SSL_CTX_set_session_id_context(ssl_ctx, sid_ctx, sizeof(sid_ctx) - 1);
  SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_SERVER);

  if (!tlsconf.session_cache.memcached.host.empty()) {
    SSL_CTX_sess_set_new_cb(ssl_ctx, tls_session_new_cb);
    SSL_CTX_sess_set_get_cb(ssl_ctx, tls_session_get_cb);
  }

  SSL_CTX_set_timeout(ssl_ctx, tlsconf.session_timeout.count());

  if (SSL_CTX_set_cipher_list(ssl_ctx, tlsconf.ciphers.data()) == 0) {
    LOG(FATAL) << "SSL_CTX_set_cipher_list " << tlsconf.ciphers
               << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }

#if defined(NGHTTP2_GENUINE_OPENSSL) || defined(NGHTTP2_OPENSSL_IS_LIBRESSL)
  if (SSL_CTX_set_ciphersuites(ssl_ctx, tlsconf.tls13_ciphers.data()) == 0) {
    LOG(FATAL) << "SSL_CTX_set_ciphersuites " << tlsconf.tls13_ciphers
               << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }
#endif // NGHTTP2_GENUINE_OPENSSL || NGHTTP2_OPENSSL_IS_LIBRESSL

#ifndef OPENSSL_NO_EC
  if (SSL_CTX_set1_curves_list(ssl_ctx, tlsconf.ecdh_curves.data()) != 1) {
    LOG(FATAL) << "SSL_CTX_set1_curves_list " << tlsconf.ecdh_curves
               << " failed";
    DIE();
  }
#endif // OPENSSL_NO_EC

  if (!tlsconf.dh_param_file.empty()) {
    // Read DH parameters from file
    auto bio = BIO_new_file(tlsconf.dh_param_file.data(), "rb");
    if (bio == nullptr) {
      LOG(FATAL) << "BIO_new_file() failed: "
                 << ERR_error_string(ERR_get_error(), nullptr);
      DIE();
    }
#if OPENSSL_3_0_0_API
    EVP_PKEY *dh = nullptr;
    auto dctx = OSSL_DECODER_CTX_new_for_pkey(
        &dh, "PEM", nullptr, "DH", OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
        nullptr, nullptr);

    if (!OSSL_DECODER_from_bio(dctx, bio)) {
      LOG(FATAL) << "OSSL_DECODER_from_bio() failed: "
                 << ERR_error_string(ERR_get_error(), nullptr);
      DIE();
    }

    if (SSL_CTX_set0_tmp_dh_pkey(ssl_ctx, dh) != 1) {
      LOG(FATAL) << "SSL_CTX_set0_tmp_dh_pkey failed: "
                 << ERR_error_string(ERR_get_error(), nullptr);
      DIE();
    }
#else  // !OPENSSL_3_0_0_API
    auto dh = PEM_read_bio_DHparams(bio, nullptr, nullptr, nullptr);
    if (dh == nullptr) {
      LOG(FATAL) << "PEM_read_bio_DHparams() failed: "
                 << ERR_error_string(ERR_get_error(), nullptr);
      DIE();
    }
    SSL_CTX_set_tmp_dh(ssl_ctx, dh);
    DH_free(dh);
#endif // !OPENSSL_3_0_0_API
    BIO_free(bio);
  }

  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);

  if (SSL_CTX_set_default_verify_paths(ssl_ctx) != 1) {
    LOG(WARN) << "Could not load system trusted ca certificates: "
              << ERR_error_string(ERR_get_error(), nullptr);
  }

  if (!tlsconf.cacert.empty()) {
    if (SSL_CTX_load_verify_locations(ssl_ctx, tlsconf.cacert.data(),
                                      nullptr) != 1) {
      LOG(FATAL) << "Could not load trusted ca certificates from "
                 << tlsconf.cacert << ": "
                 << ERR_error_string(ERR_get_error(), nullptr);
      DIE();
    }
  }

  if (!tlsconf.private_key_passwd.empty()) {
    SSL_CTX_set_default_passwd_cb(ssl_ctx, ssl_pem_passwd_cb);
    SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, config);
  }

#ifndef HAVE_NEVERBLEED
  if (SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key_file,
                                  SSL_FILETYPE_PEM) != 1) {
    LOG(FATAL) << "SSL_CTX_use_PrivateKey_file failed: "
               << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }
#else  // HAVE_NEVERBLEED
  std::array<char, NEVERBLEED_ERRBUF_SIZE> errbuf;
  if (neverbleed_load_private_key_file(nb, ssl_ctx, private_key_file,
                                       errbuf.data()) != 1) {
    LOG(FATAL) << "neverbleed_load_private_key_file failed: " << errbuf.data();
    DIE();
  }
#endif // HAVE_NEVERBLEED

  if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_file) != 1) {
    LOG(FATAL) << "SSL_CTX_use_certificate_file failed: "
               << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }
  if (SSL_CTX_check_private_key(ssl_ctx) != 1) {
    LOG(FATAL) << "SSL_CTX_check_private_key failed: "
               << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }
  if (tlsconf.client_verify.enabled) {
    if (!tlsconf.client_verify.cacert.empty()) {
      if (SSL_CTX_load_verify_locations(
              ssl_ctx, tlsconf.client_verify.cacert.data(), nullptr) != 1) {

        LOG(FATAL) << "Could not load trusted ca certificates from "
                   << tlsconf.client_verify.cacert << ": "
                   << ERR_error_string(ERR_get_error(), nullptr);
        DIE();
      }
      // It is heard that SSL_CTX_load_verify_locations() may leave
      // error even though it returns success. See
      // http://forum.nginx.org/read.php?29,242540
      ERR_clear_error();
      auto list = SSL_load_client_CA_file(tlsconf.client_verify.cacert.data());
      if (!list) {
        LOG(FATAL) << "Could not load ca certificates from "
                   << tlsconf.client_verify.cacert << ": "
                   << ERR_error_string(ERR_get_error(), nullptr);
        DIE();
      }
      SSL_CTX_set_client_CA_list(ssl_ctx, list);
    }
    SSL_CTX_set_verify(ssl_ctx,
                       SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE |
                           SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
                       verify_callback);
  }
  SSL_CTX_set_tlsext_servername_callback(ssl_ctx, servername_callback);
#if OPENSSL_3_0_0_API
  SSL_CTX_set_tlsext_ticket_key_evp_cb(ssl_ctx, ticket_key_cb);
#else  // !OPENSSL_3_0_0_API
  SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx, ticket_key_cb);
#endif // !OPENSSL_3_0_0_API
#ifndef NGHTTP2_OPENSSL_IS_BORINGSSL
  SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
#endif // NGHTTP2_OPENSSL_IS_BORINGSSL
  SSL_CTX_set_info_callback(ssl_ctx, info_callback);

#ifdef NGHTTP2_OPENSSL_IS_BORINGSSL
  SSL_CTX_set_early_data_enabled(ssl_ctx, 1);
#endif // NGHTTP2_OPENSSL_IS_BORINGSSL

  // ALPN selection callback
  SSL_CTX_set_alpn_select_cb(ssl_ctx, alpn_select_proto_cb, nullptr);

  auto tls_ctx_data = new TLSContextData();
  tls_ctx_data->cert_file = cert_file;
  tls_ctx_data->sct_data = sct_data;

  SSL_CTX_set_app_data(ssl_ctx, tls_ctx_data);

#ifdef NGHTTP2_GENUINE_OPENSSL
  // SSL_extension_supported(TLSEXT_TYPE_signed_certificate_timestamp)
  // returns 1, which means OpenSSL internally handles it.  But
  // OpenSSL handles signed_certificate_timestamp extension specially,
  // and it lets custom handler to process the extension.
  if (!sct_data.empty()) {
    // It is not entirely clear to me that SSL_EXT_CLIENT_HELLO is
    // required here.  sct_parse_cb is called without
    // SSL_EXT_CLIENT_HELLO being set.  But the passed context value
    // is SSL_EXT_CLIENT_HELLO.
    if (SSL_CTX_add_custom_ext(
            ssl_ctx, TLSEXT_TYPE_signed_certificate_timestamp,
            SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO |
                SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_IGNORE_ON_RESUMPTION,
            sct_add_cb, sct_free_cb, nullptr, sct_parse_cb, nullptr) != 1) {
      LOG(FATAL) << "SSL_CTX_add_custom_ext failed: "
                 << ERR_error_string(ERR_get_error(), nullptr);
      DIE();
    }
  }
#elif defined(NGHTTP2_OPENSSL_IS_BORINGSSL)
  if (!tls_ctx_data->sct_data.empty() &&
      SSL_CTX_set_signed_cert_timestamp_list(
          ssl_ctx, tls_ctx_data->sct_data.data(),
          tls_ctx_data->sct_data.size()) != 1) {
    LOG(FATAL) << "SSL_CTX_set_signed_cert_timestamp_list failed: "
               << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }
#endif // NGHTTP2_OPENSSL_IS_BORINGSSL

#ifdef NGHTTP2_GENUINE_OPENSSL
  if (SSL_CTX_set_max_early_data(ssl_ctx, tlsconf.max_early_data) != 1) {
    LOG(FATAL) << "SSL_CTX_set_max_early_data failed: "
               << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }
  if (SSL_CTX_set_recv_max_early_data(ssl_ctx, tlsconf.max_early_data) != 1) {
    LOG(FATAL) << "SSL_CTX_set_recv_max_early_data failed: "
               << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }
#endif // NGHTTP2_GENUINE_OPENSSL

#ifndef OPENSSL_NO_PSK
  SSL_CTX_set_psk_server_callback(ssl_ctx, psk_server_cb);
#endif // !LIBRESSL_NO_PSK

#if defined(NGHTTP2_OPENSSL_IS_BORINGSSL) && defined(HAVE_LIBBROTLI)
  if (!SSL_CTX_add_cert_compression_alg(
          ssl_ctx, nghttp2::tls::CERTIFICATE_COMPRESSION_ALGO_BROTLI,
          cert_compress, cert_decompress)) {
    LOG(FATAL) << "SSL_CTX_add_cert_compression_alg failed";
    DIE();
  }
#endif // NGHTTP2_OPENSSL_IS_BORINGSSL && HAVE_LIBBROTLI

  return ssl_ctx;
}

#ifdef ENABLE_HTTP3
SSL_CTX *create_quic_ssl_context(const char *private_key_file,
                                 const char *cert_file,
                                 const std::vector<uint8_t> &sct_data
#  ifdef HAVE_NEVERBLEED
                                 ,
                                 neverbleed_t *nb
#  endif // HAVE_NEVERBLEED
) {
  auto ssl_ctx = SSL_CTX_new(TLS_server_method());
  if (!ssl_ctx) {
    LOG(FATAL) << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }

  constexpr auto ssl_opts =
      (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
      SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_SINGLE_ECDH_USE |
      SSL_OP_SINGLE_DH_USE |
      SSL_OP_CIPHER_SERVER_PREFERENCE
#  ifdef NGHTTP2_GENUINE_OPENSSL
      // The reason for disabling built-in anti-replay in OpenSSL is
      // that it only works if client gets back to the same server.
      // The freshness check described in
      // https://tools.ietf.org/html/rfc8446#section-8.3 is still
      // performed.
      | SSL_OP_NO_ANTI_REPLAY
#  endif // NGHTTP2_GENUINE_OPENSSL
      ;

  auto config = mod_config();
  auto &tlsconf = config->tls;

  SSL_CTX_set_options(ssl_ctx, ssl_opts);

#  ifdef HAVE_LIBNGTCP2_CRYPTO_QUICTLS
  if (ngtcp2_crypto_quictls_configure_server_context(ssl_ctx) != 0) {
    LOG(FATAL) << "ngtcp2_crypto_quictls_configure_server_context failed";
    DIE();
  }
#  endif // HAVE_LIBNGTCP2_CRYPTO_QUICTLS
#  ifdef HAVE_LIBNGTCP2_CRYPTO_BORINGSSL
  if (ngtcp2_crypto_boringssl_configure_server_context(ssl_ctx) != 0) {
    LOG(FATAL) << "ngtcp2_crypto_boringssl_configure_server_context failed";
    DIE();
  }
#  endif // HAVE_LIBNGTCP2_CRYPTO_BORINGSSL

  const unsigned char sid_ctx[] = "shrpx";
  SSL_CTX_set_session_id_context(ssl_ctx, sid_ctx, sizeof(sid_ctx) - 1);
  SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_OFF);

  SSL_CTX_set_timeout(ssl_ctx, tlsconf.session_timeout.count());

  if (SSL_CTX_set_cipher_list(ssl_ctx, tlsconf.ciphers.data()) == 0) {
    LOG(FATAL) << "SSL_CTX_set_cipher_list " << tlsconf.ciphers
               << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }

#  if defined(NGHTTP2_GENUINE_OPENSSL) || defined(NGHTTP2_OPENSSL_IS_LIBRESSL)
  if (SSL_CTX_set_ciphersuites(ssl_ctx, tlsconf.tls13_ciphers.data()) == 0) {
    LOG(FATAL) << "SSL_CTX_set_ciphersuites " << tlsconf.tls13_ciphers
               << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }
#  endif // NGHTTP2_GENUINE_OPENSSL || NGHTTP2_OPENSSL_IS_LIBRESSL

#  ifndef OPENSSL_NO_EC
  if (SSL_CTX_set1_curves_list(ssl_ctx, tlsconf.ecdh_curves.data()) != 1) {
    LOG(FATAL) << "SSL_CTX_set1_curves_list " << tlsconf.ecdh_curves
               << " failed";
    DIE();
  }
#  endif // OPENSSL_NO_EC

  if (!tlsconf.dh_param_file.empty()) {
    // Read DH parameters from file
    auto bio = BIO_new_file(tlsconf.dh_param_file.data(), "rb");
    if (bio == nullptr) {
      LOG(FATAL) << "BIO_new_file() failed: "
                 << ERR_error_string(ERR_get_error(), nullptr);
      DIE();
    }
#  if OPENSSL_3_0_0_API
    EVP_PKEY *dh = nullptr;
    auto dctx = OSSL_DECODER_CTX_new_for_pkey(
        &dh, "PEM", nullptr, "DH", OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
        nullptr, nullptr);

    if (!OSSL_DECODER_from_bio(dctx, bio)) {
      LOG(FATAL) << "OSSL_DECODER_from_bio() failed: "
                 << ERR_error_string(ERR_get_error(), nullptr);
      DIE();
    }

    if (SSL_CTX_set0_tmp_dh_pkey(ssl_ctx, dh) != 1) {
      LOG(FATAL) << "SSL_CTX_set0_tmp_dh_pkey failed: "
                 << ERR_error_string(ERR_get_error(), nullptr);
      DIE();
    }
#  else  // !OPENSSL_3_0_0_API
    auto dh = PEM_read_bio_DHparams(bio, nullptr, nullptr, nullptr);
    if (dh == nullptr) {
      LOG(FATAL) << "PEM_read_bio_DHparams() failed: "
                 << ERR_error_string(ERR_get_error(), nullptr);
      DIE();
    }
    SSL_CTX_set_tmp_dh(ssl_ctx, dh);
    DH_free(dh);
#  endif // !OPENSSL_3_0_0_API
    BIO_free(bio);
  }

  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);

  if (SSL_CTX_set_default_verify_paths(ssl_ctx) != 1) {
    LOG(WARN) << "Could not load system trusted ca certificates: "
              << ERR_error_string(ERR_get_error(), nullptr);
  }

  if (!tlsconf.cacert.empty()) {
    if (SSL_CTX_load_verify_locations(ssl_ctx, tlsconf.cacert.data(),
                                      nullptr) != 1) {
      LOG(FATAL) << "Could not load trusted ca certificates from "
                 << tlsconf.cacert << ": "
                 << ERR_error_string(ERR_get_error(), nullptr);
      DIE();
    }
  }

  if (!tlsconf.private_key_passwd.empty()) {
    SSL_CTX_set_default_passwd_cb(ssl_ctx, ssl_pem_passwd_cb);
    SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, config);
  }

#  ifndef HAVE_NEVERBLEED
  if (SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key_file,
                                  SSL_FILETYPE_PEM) != 1) {
    LOG(FATAL) << "SSL_CTX_use_PrivateKey_file failed: "
               << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }
#  else  // HAVE_NEVERBLEED
  std::array<char, NEVERBLEED_ERRBUF_SIZE> errbuf;
  if (neverbleed_load_private_key_file(nb, ssl_ctx, private_key_file,
                                       errbuf.data()) != 1) {
    LOG(FATAL) << "neverbleed_load_private_key_file failed: " << errbuf.data();
    DIE();
  }
#  endif // HAVE_NEVERBLEED

  if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_file) != 1) {
    LOG(FATAL) << "SSL_CTX_use_certificate_file failed: "
               << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }
  if (SSL_CTX_check_private_key(ssl_ctx) != 1) {
    LOG(FATAL) << "SSL_CTX_check_private_key failed: "
               << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }
  if (tlsconf.client_verify.enabled) {
    if (!tlsconf.client_verify.cacert.empty()) {
      if (SSL_CTX_load_verify_locations(
              ssl_ctx, tlsconf.client_verify.cacert.data(), nullptr) != 1) {

        LOG(FATAL) << "Could not load trusted ca certificates from "
                   << tlsconf.client_verify.cacert << ": "
                   << ERR_error_string(ERR_get_error(), nullptr);
        DIE();
      }
      // It is heard that SSL_CTX_load_verify_locations() may leave
      // error even though it returns success. See
      // http://forum.nginx.org/read.php?29,242540
      ERR_clear_error();
      auto list = SSL_load_client_CA_file(tlsconf.client_verify.cacert.data());
      if (!list) {
        LOG(FATAL) << "Could not load ca certificates from "
                   << tlsconf.client_verify.cacert << ": "
                   << ERR_error_string(ERR_get_error(), nullptr);
        DIE();
      }
      SSL_CTX_set_client_CA_list(ssl_ctx, list);
    }
    SSL_CTX_set_verify(ssl_ctx,
                       SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE |
                           SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
                       verify_callback);
  }
  SSL_CTX_set_tlsext_servername_callback(ssl_ctx, servername_callback);
#  if OPENSSL_3_0_0_API
  SSL_CTX_set_tlsext_ticket_key_evp_cb(ssl_ctx, ticket_key_cb);
#  else  // !OPENSSL_3_0_0_API
  SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx, ticket_key_cb);
#  endif // !OPENSSL_3_0_0_API
#  ifndef NGHTTP2_OPENSSL_IS_BORINGSSL
  SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
#  endif // NGHTTP2_OPENSSL_IS_BORINGSSL

  // ALPN selection callback
  SSL_CTX_set_alpn_select_cb(ssl_ctx, quic_alpn_select_proto_cb, nullptr);

  auto tls_ctx_data = new TLSContextData();
  tls_ctx_data->cert_file = cert_file;
  tls_ctx_data->sct_data = sct_data;

  SSL_CTX_set_app_data(ssl_ctx, tls_ctx_data);

#  ifdef NGHTTP2_GENUINE_OPENSSL
  // SSL_extension_supported(TLSEXT_TYPE_signed_certificate_timestamp)
  // returns 1, which means OpenSSL internally handles it.  But
  // OpenSSL handles signed_certificate_timestamp extension specially,
  // and it lets custom handler to process the extension.
  if (!sct_data.empty()) {
    // It is not entirely clear to me that SSL_EXT_CLIENT_HELLO is
    // required here.  sct_parse_cb is called without
    // SSL_EXT_CLIENT_HELLO being set.  But the passed context value
    // is SSL_EXT_CLIENT_HELLO.
    if (SSL_CTX_add_custom_ext(
            ssl_ctx, TLSEXT_TYPE_signed_certificate_timestamp,
            SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO |
                SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_IGNORE_ON_RESUMPTION,
            sct_add_cb, sct_free_cb, nullptr, sct_parse_cb, nullptr) != 1) {
      LOG(FATAL) << "SSL_CTX_add_custom_ext failed: "
                 << ERR_error_string(ERR_get_error(), nullptr);
      DIE();
    }
  }
#  elif defined(NGHTTP2_OPENSSL_IS_BORINGSSL)
  if (!tls_ctx_data->sct_data.empty() &&
      SSL_CTX_set_signed_cert_timestamp_list(
          ssl_ctx, tls_ctx_data->sct_data.data(),
          tls_ctx_data->sct_data.size()) != 1) {
    LOG(FATAL) << "SSL_CTX_set_signed_cert_timestamp_list failed: "
               << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }
#  endif // NGHTTP2_OPENSSL_IS_BORINGSSL

#  ifdef NGHTTP2_GENUINE_OPENSSL
  auto &quicconf = config->quic;

  if (quicconf.upstream.early_data &&
      SSL_CTX_set_max_early_data(ssl_ctx,
                                 std::numeric_limits<uint32_t>::max()) != 1) {
    LOG(FATAL) << "SSL_CTX_set_max_early_data failed: "
               << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }
#  endif // NGHTTP2_GENUINE_OPENSSL

#  ifndef OPENSSL_NO_PSK
  SSL_CTX_set_psk_server_callback(ssl_ctx, psk_server_cb);
#  endif // !LIBRESSL_NO_PSK

#  if defined(NGHTTP2_OPENSSL_IS_BORINGSSL) && defined(HAVE_LIBBROTLI)
  if (!SSL_CTX_add_cert_compression_alg(
          ssl_ctx, nghttp2::tls::CERTIFICATE_COMPRESSION_ALGO_BROTLI,
          cert_compress, cert_decompress)) {
    LOG(FATAL) << "SSL_CTX_add_cert_compression_alg failed";
    DIE();
  }
#  endif // NGHTTP2_OPENSSL_IS_BORINGSSL && HAVE_LIBBROTLI

  return ssl_ctx;
}
#endif // ENABLE_HTTP3

SSL_CTX *create_ssl_client_context(
#ifdef HAVE_NEVERBLEED
    neverbleed_t *nb,
#endif // HAVE_NEVERBLEED
    const StringRef &cacert, const StringRef &cert_file,
    const StringRef &private_key_file) {
  auto ssl_ctx = SSL_CTX_new(TLS_client_method());
  if (!ssl_ctx) {
    LOG(FATAL) << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }

  auto ssl_opts = (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
                  SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION |
                  SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION;

  auto &tlsconf = get_config()->tls;

#ifdef SSL_OP_ENABLE_KTLS
  if (tlsconf.ktls) {
    ssl_opts |= SSL_OP_ENABLE_KTLS;
  }
#endif // SSL_OP_ENABLE_KTLS

  SSL_CTX_set_options(ssl_ctx, ssl_opts | tlsconf.tls_proto_mask);

  SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_CLIENT |
                                              SSL_SESS_CACHE_NO_INTERNAL_STORE);
  SSL_CTX_sess_set_new_cb(ssl_ctx, tls_session_client_new_cb);

  if (nghttp2::tls::ssl_ctx_set_proto_versions(
          ssl_ctx, tlsconf.min_proto_version, tlsconf.max_proto_version) != 0) {
    LOG(FATAL) << "Could not set TLS protocol version";
    DIE();
  }

  if (SSL_CTX_set_cipher_list(ssl_ctx, tlsconf.client.ciphers.data()) == 0) {
    LOG(FATAL) << "SSL_CTX_set_cipher_list " << tlsconf.client.ciphers
               << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }

#if defined(NGHTTP2_GENUINE_OPENSSL) || defined(NGHTTP2_OPENSSL_IS_LIBRESSL)
  if (SSL_CTX_set_ciphersuites(ssl_ctx, tlsconf.client.tls13_ciphers.data()) ==
      0) {
    LOG(FATAL) << "SSL_CTX_set_ciphersuites " << tlsconf.client.tls13_ciphers
               << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
    DIE();
  }
#endif // NGHTTP2_GENUINE_OPENSSL || NGHTTP2_OPENSSL_IS_LIBRESSL

  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);

  if (SSL_CTX_set_default_verify_paths(ssl_ctx) != 1) {
    LOG(WARN) << "Could not load system trusted ca certificates: "
              << ERR_error_string(ERR_get_error(), nullptr);
  }

  if (!cacert.empty()) {
    if (SSL_CTX_load_verify_locations(ssl_ctx, cacert.data(), nullptr) != 1) {

      LOG(FATAL) << "Could not load trusted ca certificates from " << cacert
                 << ": " << ERR_error_string(ERR_get_error(), nullptr);
      DIE();
    }
  }

  if (!tlsconf.insecure) {
    SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  }

  if (!cert_file.empty()) {
    if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_file.data()) != 1) {

      LOG(FATAL) << "Could not load client certificate from " << cert_file
                 << ": " << ERR_error_string(ERR_get_error(), nullptr);
      DIE();
    }
  }

  if (!private_key_file.empty()) {
#ifndef HAVE_NEVERBLEED
    if (SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key_file.data(),
                                    SSL_FILETYPE_PEM) != 1) {
      LOG(FATAL) << "Could not load client private key from "
                 << private_key_file << ": "
                 << ERR_error_string(ERR_get_error(), nullptr);
      DIE();
    }
#else  // HAVE_NEVERBLEED
    std::array<char, NEVERBLEED_ERRBUF_SIZE> errbuf;
    if (neverbleed_load_private_key_file(nb, ssl_ctx, private_key_file.data(),
                                         errbuf.data()) != 1) {
      LOG(FATAL) << "neverbleed_load_private_key_file: could not load client "
                    "private key from "
                 << private_key_file << ": " << errbuf.data();
      DIE();
    }
#endif // HAVE_NEVERBLEED
  }

#ifndef OPENSSL_NO_PSK
  SSL_CTX_set_psk_client_callback(ssl_ctx, psk_client_cb);
#endif // !OPENSSL_NO_PSK

#if defined(NGHTTP2_OPENSSL_IS_BORINGSSL) && defined(HAVE_LIBBROTLI)
  if (!SSL_CTX_add_cert_compression_alg(
          ssl_ctx, nghttp2::tls::CERTIFICATE_COMPRESSION_ALGO_BROTLI,
          cert_compress, cert_decompress)) {
    LOG(FATAL) << "SSL_CTX_add_cert_compression_alg failed";
    DIE();
  }
#endif // NGHTTP2_OPENSSL_IS_BORINGSSL && HAVE_LIBBROTLI

  return ssl_ctx;
}

SSL *create_ssl(SSL_CTX *ssl_ctx) {
  auto ssl = SSL_new(ssl_ctx);
  if (!ssl) {
    LOG(ERROR) << "SSL_new() failed: "
               << ERR_error_string(ERR_get_error(), nullptr);
    return nullptr;
  }

  return ssl;
}

ClientHandler *accept_connection(Worker *worker, int fd, sockaddr *addr,
                                 int addrlen, const UpstreamAddr *faddr) {
  std::array<char, NI_MAXHOST> host;
  std::array<char, NI_MAXSERV> service;
  int rv;

  if (addr->sa_family == AF_UNIX) {
    std::copy_n("localhost", sizeof("localhost"), std::begin(host));
    service[0] = '\0';
  } else {
    rv = getnameinfo(addr, addrlen, host.data(), host.size(), service.data(),
                     service.size(), NI_NUMERICHOST | NI_NUMERICSERV);
    if (rv != 0) {
      LOG(ERROR) << "getnameinfo() failed: " << gai_strerror(rv);

      return nullptr;
    }

    rv = util::make_socket_nodelay(fd);
    if (rv == -1) {
      LOG(WARN) << "Setting option TCP_NODELAY failed: errno=" << errno;
    }
  }
  SSL *ssl = nullptr;
  if (faddr->tls) {
    auto ssl_ctx = worker->get_sv_ssl_ctx();

    assert(ssl_ctx);

    ssl = create_ssl(ssl_ctx);
    if (!ssl) {
      return nullptr;
    }
    // Disable TLS session ticket if we don't have working ticket
    // keys.
    if (!worker->get_ticket_keys()) {
      SSL_set_options(ssl, SSL_OP_NO_TICKET);
    }
  }

  return new ClientHandler(worker, fd, ssl, StringRef{host.data()},
                           StringRef{service.data()}, addr->sa_family, faddr);
}

bool tls_hostname_match(const StringRef &pattern, const StringRef &hostname) {
  auto ptWildcard = std::find(std::begin(pattern), std::end(pattern), '*');
  if (ptWildcard == std::end(pattern)) {
    return util::strieq(pattern, hostname);
  }

  auto ptLeftLabelEnd = std::find(std::begin(pattern), std::end(pattern), '.');
  auto wildcardEnabled = true;
  // Do case-insensitive match. At least 2 dots are required to enable
  // wildcard match. Also wildcard must be in the left-most label.
  // Don't attempt to match a presented identifier where the wildcard
  // character is embedded within an A-label.
  if (ptLeftLabelEnd == std::end(pattern) ||
      std::find(ptLeftLabelEnd + 1, std::end(pattern), '.') ==
          std::end(pattern) ||
      ptLeftLabelEnd < ptWildcard || util::istarts_with(pattern, "xn--"_sr)) {
    wildcardEnabled = false;
  }

  if (!wildcardEnabled) {
    return util::strieq(pattern, hostname);
  }

  auto hnLeftLabelEnd =
      std::find(std::begin(hostname), std::end(hostname), '.');
  if (hnLeftLabelEnd == std::end(hostname) ||
      !util::strieq(StringRef{ptLeftLabelEnd, std::end(pattern)},
                    StringRef{hnLeftLabelEnd, std::end(hostname)})) {
    return false;
  }
  // Perform wildcard match. Here '*' must match at least one
  // character.
  if (hnLeftLabelEnd - std::begin(hostname) <
      ptLeftLabelEnd - std::begin(pattern)) {
    return false;
  }
  return util::istarts_with(StringRef{std::begin(hostname), hnLeftLabelEnd},
                            StringRef{std::begin(pattern), ptWildcard}) &&
         util::iends_with(StringRef{std::begin(hostname), hnLeftLabelEnd},
                          StringRef{ptWildcard + 1, ptLeftLabelEnd});
}

namespace {
// if return value is not empty, StringRef.c_str() must be freed using
// OPENSSL_free().
StringRef get_common_name(X509 *cert) {
  auto subjectname = X509_get_subject_name(cert);
  if (!subjectname) {
    LOG(WARN) << "Could not get X509 name object from the certificate.";
    return StringRef{};
  }
  int lastpos = -1;
  for (;;) {
    lastpos = X509_NAME_get_index_by_NID(subjectname, NID_commonName, lastpos);
    if (lastpos == -1) {
      break;
    }
    auto entry = X509_NAME_get_entry(subjectname, lastpos);

    unsigned char *p;
    auto plen = ASN1_STRING_to_UTF8(&p, X509_NAME_ENTRY_get_data(entry));
    if (plen < 0) {
      continue;
    }
    if (std::find(p, p + plen, '\0') != p + plen) {
      // Embedded NULL is not permitted.
      continue;
    }
    if (plen == 0) {
      LOG(WARN) << "X509 name is empty";
      OPENSSL_free(p);
      continue;
    }

    return StringRef{p, static_cast<size_t>(plen)};
  }
  return StringRef{};
}
} // namespace

int verify_numeric_hostname(X509 *cert, const StringRef &hostname,
                            const Address *addr) {
  const void *saddr;
  size_t saddrlen;
  switch (addr->su.storage.ss_family) {
  case AF_INET:
    saddr = &addr->su.in.sin_addr;
    saddrlen = sizeof(addr->su.in.sin_addr);
    break;
  case AF_INET6:
    saddr = &addr->su.in6.sin6_addr;
    saddrlen = sizeof(addr->su.in6.sin6_addr);
    break;
  default:
    return -1;
  }

  auto altnames = static_cast<GENERAL_NAMES *>(
      X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
  if (altnames) {
    auto altnames_deleter = defer(GENERAL_NAMES_free, altnames);
    size_t n = sk_GENERAL_NAME_num(altnames);
    auto ip_found = false;
    for (size_t i = 0; i < n; ++i) {
      auto altname = sk_GENERAL_NAME_value(altnames, i);
      if (altname->type != GEN_IPADD) {
        continue;
      }

      auto ip_addr = altname->d.iPAddress->data;
      if (!ip_addr) {
        continue;
      }
      size_t ip_addrlen = altname->d.iPAddress->length;

      ip_found = true;
      if (saddrlen == ip_addrlen && memcmp(saddr, ip_addr, ip_addrlen) == 0) {
        return 0;
      }
    }

    if (ip_found) {
      return -1;
    }
  }

  auto cn = get_common_name(cert);
  if (cn.empty()) {
    return -1;
  }

  // cn is not NULL terminated
  auto rv = hostname == cn;
  OPENSSL_free(const_cast<char *>(cn.data()));

  if (rv) {
    return 0;
  }

  return -1;
}

int verify_dns_hostname(X509 *cert, const StringRef &hostname) {
  auto altnames = static_cast<GENERAL_NAMES *>(
      X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
  if (altnames) {
    auto dns_found = false;
    auto altnames_deleter = defer(GENERAL_NAMES_free, altnames);
    size_t n = sk_GENERAL_NAME_num(altnames);
    for (size_t i = 0; i < n; ++i) {
      auto altname = sk_GENERAL_NAME_value(altnames, i);
      if (altname->type != GEN_DNS) {
        continue;
      }

      auto name = ASN1_STRING_get0_data(altname->d.ia5);
      if (!name) {
        continue;
      }

      auto len = ASN1_STRING_length(altname->d.ia5);
      if (len == 0) {
        continue;
      }
      if (std::find(name, name + len, '\0') != name + len) {
        // Embedded NULL is not permitted.
        continue;
      }

      if (name[len - 1] == '.') {
        --len;
        if (len == 0) {
          continue;
        }
      }

      dns_found = true;

      if (tls_hostname_match(StringRef{name, static_cast<size_t>(len)},
                             hostname)) {
        return 0;
      }
    }

    // RFC 6125, section 6.4.4. says that client MUST not seek a match
    // for CN if a dns dNSName is found.
    if (dns_found) {
      return -1;
    }
  }

  auto cn = get_common_name(cert);
  if (cn.empty()) {
    return -1;
  }

  if (cn[cn.size() - 1] == '.') {
    if (cn.size() == 1) {
      OPENSSL_free(const_cast<char *>(cn.data()));

      return -1;
    }
    cn = StringRef{cn.data(), cn.size() - 1};
  }

  auto rv = tls_hostname_match(cn, hostname);
  OPENSSL_free(const_cast<char *>(cn.data()));

  return rv ? 0 : -1;
}

namespace {
int verify_hostname(X509 *cert, const StringRef &hostname,
                    const Address *addr) {
  if (util::numeric_host(hostname.data())) {
    return verify_numeric_hostname(cert, hostname, addr);
  }

  return verify_dns_hostname(cert, hostname);
}
} // namespace

int check_cert(SSL *ssl, const Address *addr, const StringRef &host) {
#if OPENSSL_3_0_0_API
  auto cert = SSL_get0_peer_certificate(ssl);
#else  // !OPENSSL_3_0_0_API
  auto cert = SSL_get_peer_certificate(ssl);
#endif // !OPENSSL_3_0_0_API
  if (!cert) {
    // By the protocol definition, TLS server always sends certificate
    // if it has.  If certificate cannot be retrieved, authentication
    // without certificate is used, such as PSK.
    return 0;
  }
#if !OPENSSL_3_0_0_API
  auto cert_deleter = defer(X509_free, cert);
#endif // !OPENSSL_3_0_0_API

  if (verify_hostname(cert, host, addr) != 0) {
    LOG(ERROR) << "Certificate verification failed: hostname does not match";
    return -1;
  }
  return 0;
}

int check_cert(SSL *ssl, const DownstreamAddr *addr, const Address *raddr) {
  auto hostname =
      addr->sni.empty() ? StringRef{addr->host} : StringRef{addr->sni};
  return check_cert(ssl, raddr, hostname);
}

CertLookupTree::CertLookupTree() {}

ssize_t CertLookupTree::add_cert(const StringRef &hostname, size_t idx) {
  std::array<char, NI_MAXHOST> buf;

  // NI_MAXHOST includes terminal NULL byte
  if (hostname.empty() || hostname.size() + 1 > buf.size()) {
    return -1;
  }

  auto wildcard_it = std::find(std::begin(hostname), std::end(hostname), '*');
  if (wildcard_it != std::end(hostname) &&
      wildcard_it + 1 != std::end(hostname)) {
    auto wildcard_prefix = StringRef{std::begin(hostname), wildcard_it};
    auto wildcard_suffix = StringRef{wildcard_it + 1, std::end(hostname)};

    auto rev_suffix = StringRef{std::begin(buf),
                                std::reverse_copy(std::begin(wildcard_suffix),
                                                  std::end(wildcard_suffix),
                                                  std::begin(buf))};

    WildcardPattern *wpat;

    if (wildcard_patterns_.size() !=
        rev_wildcard_router_.add_route(rev_suffix, wildcard_patterns_.size())) {
      auto wcidx = rev_wildcard_router_.match(rev_suffix);

      assert(wcidx != -1);

      wpat = &wildcard_patterns_[wcidx];
    } else {
      wildcard_patterns_.emplace_back();
      wpat = &wildcard_patterns_.back();
    }

    auto rev_prefix = StringRef{std::begin(buf),
                                std::reverse_copy(std::begin(wildcard_prefix),
                                                  std::end(wildcard_prefix),
                                                  std::begin(buf))};

    for (auto &p : wpat->rev_prefix) {
      if (p.prefix == rev_prefix) {
        return p.idx;
      }
    }

    wpat->rev_prefix.emplace_back(rev_prefix, idx);

    return idx;
  }

  return router_.add_route(hostname, idx);
}

ssize_t CertLookupTree::lookup(const StringRef &hostname) {
  std::array<char, NI_MAXHOST> buf;

  // NI_MAXHOST includes terminal NULL byte
  if (hostname.empty() || hostname.size() + 1 > buf.size()) {
    return -1;
  }

  // Always prefer exact match
  auto idx = router_.match(hostname);
  if (idx != -1) {
    return idx;
  }

  if (wildcard_patterns_.empty()) {
    return -1;
  }

  ssize_t best_idx = -1;
  size_t best_prefixlen = 0;
  const RNode *last_node = nullptr;

  auto rev_host = StringRef{
      std::begin(buf), std::reverse_copy(std::begin(hostname),
                                         std::end(hostname), std::begin(buf))};

  for (;;) {
    size_t nread = 0;

    auto wcidx =
        rev_wildcard_router_.match_prefix(&nread, &last_node, rev_host);
    if (wcidx == -1) {
      return best_idx;
    }

    // '*' must match at least one byte
    if (nread == rev_host.size()) {
      return best_idx;
    }

    rev_host = StringRef{std::begin(rev_host) + nread, std::end(rev_host)};

    auto rev_prefix = StringRef{std::begin(rev_host) + 1, std::end(rev_host)};

    auto &wpat = wildcard_patterns_[wcidx];
    for (auto &wprefix : wpat.rev_prefix) {
      if (!util::ends_with(rev_prefix, wprefix.prefix)) {
        continue;
      }

      auto prefixlen = wprefix.prefix.size() + (&rev_host[0] - &buf[0]);

      // Breaking a tie with longer suffix
      if (prefixlen < best_prefixlen) {
        continue;
      }

      best_idx = wprefix.idx;
      best_prefixlen = prefixlen;
    }
  }
}

void CertLookupTree::dump() const {
  std::cerr << "exact:" << std::endl;
  router_.dump();
  std::cerr << "wildcard suffix (reversed):" << std::endl;
  rev_wildcard_router_.dump();
}

int cert_lookup_tree_add_ssl_ctx(
    CertLookupTree *lt, std::vector<std::vector<SSL_CTX *>> &indexed_ssl_ctx,
    SSL_CTX *ssl_ctx) {
  std::array<char, NI_MAXHOST> buf;

  auto cert = SSL_CTX_get0_certificate(ssl_ctx);
  auto altnames = static_cast<GENERAL_NAMES *>(
      X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
  if (altnames) {
    auto altnames_deleter = defer(GENERAL_NAMES_free, altnames);
    size_t n = sk_GENERAL_NAME_num(altnames);
    auto dns_found = false;
    for (size_t i = 0; i < n; ++i) {
      auto altname = sk_GENERAL_NAME_value(altnames, i);
      if (altname->type != GEN_DNS) {
        continue;
      }

      auto name = ASN1_STRING_get0_data(altname->d.ia5);
      if (!name) {
        continue;
      }

      auto len = ASN1_STRING_length(altname->d.ia5);
      if (len == 0) {
        continue;
      }
      if (std::find(name, name + len, '\0') != name + len) {
        // Embedded NULL is not permitted.
        continue;
      }

      if (name[len - 1] == '.') {
        --len;
        if (len == 0) {
          continue;
        }
      }

      dns_found = true;

      if (static_cast<size_t>(len) + 1 > buf.size()) {
        continue;
      }

      auto end_buf = std::copy_n(name, len, std::begin(buf));
      util::inp_strlower(std::begin(buf), end_buf);

      auto idx = lt->add_cert(StringRef{std::begin(buf), end_buf},
                              indexed_ssl_ctx.size());
      if (idx == -1) {
        continue;
      }

      if (static_cast<size_t>(idx) < indexed_ssl_ctx.size()) {
        indexed_ssl_ctx[idx].push_back(ssl_ctx);
      } else {
        assert(static_cast<size_t>(idx) == indexed_ssl_ctx.size());
        indexed_ssl_ctx.emplace_back(std::vector<SSL_CTX *>{ssl_ctx});
      }
    }

    // Don't bother CN if we have dNSName.
    if (dns_found) {
      return 0;
    }
  }

  auto cn = get_common_name(cert);
  if (cn.empty()) {
    return 0;
  }

  if (cn[cn.size() - 1] == '.') {
    if (cn.size() == 1) {
      OPENSSL_free(const_cast<char *>(cn.data()));

      return 0;
    }

    cn = StringRef{cn.data(), cn.size() - 1};
  }

  auto end_buf = std::copy(std::begin(cn), std::end(cn), std::begin(buf));

  OPENSSL_free(const_cast<char *>(cn.data()));

  util::inp_strlower(std::begin(buf), end_buf);

  auto idx =
      lt->add_cert(StringRef{std::begin(buf), end_buf}, indexed_ssl_ctx.size());
  if (idx == -1) {
    return 0;
  }

  if (static_cast<size_t>(idx) < indexed_ssl_ctx.size()) {
    indexed_ssl_ctx[idx].push_back(ssl_ctx);
  } else {
    assert(static_cast<size_t>(idx) == indexed_ssl_ctx.size());
    indexed_ssl_ctx.emplace_back(std::vector<SSL_CTX *>{ssl_ctx});
  }

  return 0;
}

bool in_proto_list(const std::vector<StringRef> &protos,
                   const StringRef &needle) {
  for (auto &proto : protos) {
    if (proto == needle) {
      return true;
    }
  }
  return false;
}

bool upstream_tls_enabled(const ConnectionConfig &connconf) {
#ifdef ENABLE_HTTP3
  if (connconf.quic_listener.addrs.size()) {
    return true;
  }
#endif // ENABLE_HTTP3

  const auto &faddrs = connconf.listener.addrs;
  return std::any_of(std::begin(faddrs), std::end(faddrs),
                     [](const UpstreamAddr &faddr) { return faddr.tls; });
}

X509 *load_certificate(const char *filename) {
  auto bio = BIO_new(BIO_s_file());
  if (!bio) {
    fprintf(stderr, "BIO_new() failed\n");
    return nullptr;
  }
  auto bio_deleter = defer(BIO_vfree, bio);
  if (!BIO_read_filename(bio, filename)) {
    fprintf(stderr, "Could not read certificate file '%s'\n", filename);
    return nullptr;
  }
  auto cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  if (!cert) {
    fprintf(stderr, "Could not read X509 structure from file '%s'\n", filename);
    return nullptr;
  }

  return cert;
}

SSL_CTX *
setup_server_ssl_context(std::vector<SSL_CTX *> &all_ssl_ctx,
                         std::vector<std::vector<SSL_CTX *>> &indexed_ssl_ctx,
                         CertLookupTree *cert_tree
#ifdef HAVE_NEVERBLEED
                         ,
                         neverbleed_t *nb
#endif // HAVE_NEVERBLEED
) {
  auto config = get_config();

  if (!upstream_tls_enabled(config->conn)) {
    return nullptr;
  }

  auto &tlsconf = config->tls;

  auto ssl_ctx = create_ssl_context(tlsconf.private_key_file.data(),
                                    tlsconf.cert_file.data(), tlsconf.sct_data
#ifdef HAVE_NEVERBLEED
                                    ,
                                    nb
#endif // HAVE_NEVERBLEED
  );

  all_ssl_ctx.push_back(ssl_ctx);

  assert(cert_tree);

  if (cert_lookup_tree_add_ssl_ctx(cert_tree, indexed_ssl_ctx, ssl_ctx) == -1) {
    LOG(FATAL) << "Failed to add default certificate.";
    DIE();
  }

  for (auto &c : tlsconf.subcerts) {
    auto ssl_ctx = create_ssl_context(c.private_key_file.data(),
                                      c.cert_file.data(), c.sct_data
#ifdef HAVE_NEVERBLEED
                                      ,
                                      nb
#endif // HAVE_NEVERBLEED
    );
    all_ssl_ctx.push_back(ssl_ctx);

    if (cert_lookup_tree_add_ssl_ctx(cert_tree, indexed_ssl_ctx, ssl_ctx) ==
        -1) {
      LOG(FATAL) << "Failed to add sub certificate.";
      DIE();
    }
  }

  return ssl_ctx;
}

#ifdef ENABLE_HTTP3
SSL_CTX *setup_quic_server_ssl_context(
    std::vector<SSL_CTX *> &all_ssl_ctx,
    std::vector<std::vector<SSL_CTX *>> &indexed_ssl_ctx,
    CertLookupTree *cert_tree
#  ifdef HAVE_NEVERBLEED
    ,
    neverbleed_t *nb
#  endif // HAVE_NEVERBLEED
) {
  auto config = get_config();

  if (!upstream_tls_enabled(config->conn)) {
    return nullptr;
  }

  auto &tlsconf = config->tls;

  auto ssl_ctx =
      create_quic_ssl_context(tlsconf.private_key_file.data(),
                              tlsconf.cert_file.data(), tlsconf.sct_data
#  ifdef HAVE_NEVERBLEED
                              ,
                              nb
#  endif // HAVE_NEVERBLEED
      );

  all_ssl_ctx.push_back(ssl_ctx);

  assert(cert_tree);

  if (cert_lookup_tree_add_ssl_ctx(cert_tree, indexed_ssl_ctx, ssl_ctx) == -1) {
    LOG(FATAL) << "Failed to add default certificate.";
    DIE();
  }

  for (auto &c : tlsconf.subcerts) {
    auto ssl_ctx = create_quic_ssl_context(c.private_key_file.data(),
                                           c.cert_file.data(), c.sct_data
#  ifdef HAVE_NEVERBLEED
                                           ,
                                           nb
#  endif // HAVE_NEVERBLEED
    );
    all_ssl_ctx.push_back(ssl_ctx);

    if (cert_lookup_tree_add_ssl_ctx(cert_tree, indexed_ssl_ctx, ssl_ctx) ==
        -1) {
      LOG(FATAL) << "Failed to add sub certificate.";
      DIE();
    }
  }

  return ssl_ctx;
}
#endif // ENABLE_HTTP3

SSL_CTX *setup_downstream_client_ssl_context(
#ifdef HAVE_NEVERBLEED
    neverbleed_t *nb
#endif // HAVE_NEVERBLEED
) {
  auto &tlsconf = get_config()->tls;

  return create_ssl_client_context(
#ifdef HAVE_NEVERBLEED
      nb,
#endif // HAVE_NEVERBLEED
      tlsconf.cacert, tlsconf.client.cert_file,
      tlsconf.client.private_key_file);
}

void setup_downstream_http2_alpn(SSL *ssl) {
  // ALPN advertisement
  auto alpn = util::get_default_alpn();
  SSL_set_alpn_protos(ssl, alpn.data(), alpn.size());
}

void setup_downstream_http1_alpn(SSL *ssl) {
  // ALPN advertisement
  SSL_set_alpn_protos(ssl, NGHTTP2_H1_1_ALPN.byte(), NGHTTP2_H1_1_ALPN.size());
}

std::unique_ptr<CertLookupTree> create_cert_lookup_tree() {
  auto config = get_config();
  if (!upstream_tls_enabled(config->conn)) {
    return nullptr;
  }
  return std::make_unique<CertLookupTree>();
}

namespace {
std::vector<uint8_t> serialize_ssl_session(SSL_SESSION *session) {
  auto len = i2d_SSL_SESSION(session, nullptr);
  auto buf = std::vector<uint8_t>(len);
  auto p = buf.data();
  i2d_SSL_SESSION(session, &p);

  return buf;
}
} // namespace

void try_cache_tls_session(TLSSessionCache *cache, SSL_SESSION *session,
                           const std::chrono::steady_clock::time_point &t) {
  if (cache->last_updated + 1min > t) {
    if (LOG_ENABLED(INFO)) {
      LOG(INFO) << "Client session cache entry is still fresh.";
    }
    return;
  }

  if (LOG_ENABLED(INFO)) {
    LOG(INFO) << "Update client cache entry "
              << "timestamp = " << t.time_since_epoch().count();
  }

  cache->session_data = serialize_ssl_session(session);
  cache->last_updated = t;
}

SSL_SESSION *reuse_tls_session(const TLSSessionCache &cache) {
  if (cache.session_data.empty()) {
    return nullptr;
  }

  auto p = cache.session_data.data();
  return d2i_SSL_SESSION(nullptr, &p, cache.session_data.size());
}

int proto_version_from_string(const StringRef &v) {
#ifdef TLS1_3_VERSION
  if (util::strieq("TLSv1.3"_sr, v)) {
    return TLS1_3_VERSION;
  }
#endif // TLS1_3_VERSION
  if (util::strieq("TLSv1.2"_sr, v)) {
    return TLS1_2_VERSION;
  }
  if (util::strieq("TLSv1.1"_sr, v)) {
    return TLS1_1_VERSION;
  }
  if (util::strieq("TLSv1.0"_sr, v)) {
    return TLS1_VERSION;
  }
  return -1;
}

int verify_ocsp_response(SSL_CTX *ssl_ctx, const uint8_t *ocsp_resp,
                         size_t ocsp_resplen) {
#ifndef OPENSSL_NO_OCSP
  int rv;

  STACK_OF(X509) * chain_certs;
  SSL_CTX_get0_chain_certs(ssl_ctx, &chain_certs);

  auto resp = d2i_OCSP_RESPONSE(nullptr, &ocsp_resp, ocsp_resplen);
  if (resp == nullptr) {
    LOG(ERROR) << "d2i_OCSP_RESPONSE failed";
    return -1;
  }
  auto resp_deleter = defer(OCSP_RESPONSE_free, resp);

  if (OCSP_response_status(resp) != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
    LOG(ERROR) << "OCSP response status is not successful";
    return -1;
  }

  ERR_clear_error();

  auto bs = OCSP_response_get1_basic(resp);
  if (bs == nullptr) {
    LOG(ERROR) << "OCSP_response_get1_basic failed: "
               << ERR_error_string(ERR_get_error(), nullptr);
    return -1;
  }
  auto bs_deleter = defer(OCSP_BASICRESP_free, bs);

  auto store = SSL_CTX_get_cert_store(ssl_ctx);

  ERR_clear_error();

  rv = OCSP_basic_verify(bs, chain_certs, store, 0);

  if (rv != 1) {
    LOG(ERROR) << "OCSP_basic_verify failed: "
               << ERR_error_string(ERR_get_error(), nullptr);
    return -1;
  }

  auto sresp = OCSP_resp_get0(bs, 0);
  if (sresp == nullptr) {
    LOG(ERROR) << "OCSP response verification failed: no single response";
    return -1;
  }

  auto certid = OCSP_SINGLERESP_get0_id(sresp);
  assert(certid != nullptr);

  ASN1_INTEGER *serial;
  rv = OCSP_id_get0_info(nullptr, nullptr, nullptr, &serial,
                         const_cast<OCSP_CERTID *>(certid));
  if (rv != 1) {
    LOG(ERROR) << "OCSP_id_get0_info failed";
    return -1;
  }

  if (serial == nullptr) {
    LOG(ERROR) << "OCSP response does not contain serial number";
    return -1;
  }

  auto cert = SSL_CTX_get0_certificate(ssl_ctx);
  auto cert_serial = X509_get_serialNumber(cert);

  if (ASN1_INTEGER_cmp(cert_serial, serial)) {
    LOG(ERROR) << "OCSP verification serial numbers do not match";
    return -1;
  }

  if (LOG_ENABLED(INFO)) {
    LOG(INFO) << "OCSP verification succeeded";
  }
#endif // !OPENSSL_NO_OCSP

  return 0;
}

ssize_t get_x509_fingerprint(uint8_t *dst, size_t dstlen, const X509 *x,
                             const EVP_MD *md) {
  unsigned int len = dstlen;
  if (X509_digest(x, md, dst, &len) != 1) {
    return -1;
  }
  return len;
}

namespace {
StringRef get_x509_name(BlockAllocator &balloc, X509_NAME *nm) {
  auto b = BIO_new(BIO_s_mem());
  if (!b) {
    return StringRef{};
  }

  auto b_deleter = defer(BIO_free, b);

  // Not documented, but it seems that X509_NAME_print_ex returns the
  // number of bytes written into b.
  auto slen = X509_NAME_print_ex(b, nm, 0, XN_FLAG_RFC2253);
  if (slen <= 0) {
    return StringRef{};
  }

  auto iov = make_byte_ref(balloc, slen + 1);
  BIO_read(b, iov.data(), slen);
  iov[slen] = '\0';
  return StringRef{iov.data(), static_cast<size_t>(slen)};
}
} // namespace

StringRef get_x509_subject_name(BlockAllocator &balloc, X509 *x) {
  return get_x509_name(balloc, X509_get_subject_name(x));
}

StringRef get_x509_issuer_name(BlockAllocator &balloc, X509 *x) {
  return get_x509_name(balloc, X509_get_issuer_name(x));
}

StringRef get_x509_serial(BlockAllocator &balloc, X509 *x) {
  auto sn = X509_get_serialNumber(x);
  auto bn = BN_new();
  auto bn_d = defer(BN_free, bn);
  if (!ASN1_INTEGER_to_BN(sn, bn) || BN_num_bytes(bn) > 20) {
    return StringRef{};
  }

  std::array<uint8_t, 20> b;
  auto n = BN_bn2bin(bn, b.data());
  assert(n <= 20);

  return util::format_hex(balloc, std::span{b.data(), static_cast<size_t>(n)});
}

namespace {
// Performs conversion from |at| to time_t.  The result is stored in
// |t|.  This function returns 0 if it succeeds, or -1.
int time_t_from_asn1_time(time_t &t, const ASN1_TIME *at) {
  int rv;

#if defined(NGHTTP2_GENUINE_OPENSSL) || defined(NGHTTP2_OPENSSL_IS_LIBRESSL)
  struct tm tm;
  rv = ASN1_TIME_to_tm(at, &tm);
  if (rv != 1) {
    return -1;
  }

  t = nghttp2_timegm(&tm);
#else // !NGHTTP2_GENUINE_OPENSSL && !NGHTTP2_OPENSSL_IS_LIBRESSL
  auto b = BIO_new(BIO_s_mem());
  if (!b) {
    return -1;
  }

  auto bio_deleter = defer(BIO_free, b);

  rv = ASN1_TIME_print(b, at);
  if (rv != 1) {
    return -1;
  }

#  ifdef NGHTTP2_OPENSSL_IS_BORINGSSL
  char *s;
#  else
  unsigned char *s;
#  endif
  auto slen = BIO_get_mem_data(b, &s);
  auto tt = util::parse_openssl_asn1_time_print(
      StringRef{s, static_cast<size_t>(slen)});
  if (tt == 0) {
    return -1;
  }

  t = tt;
#endif // !NGHTTP2_GENUINE_OPENSSL && !NGHTTP2_OPENSSL_IS_LIBRESSL

  return 0;
}
} // namespace

int get_x509_not_before(time_t &t, X509 *x) {
  auto at = X509_get0_notBefore(x);
  if (!at) {
    return -1;
  }

  return time_t_from_asn1_time(t, at);
}

int get_x509_not_after(time_t &t, X509 *x) {
  auto at = X509_get0_notAfter(x);
  if (!at) {
    return -1;
  }

  return time_t_from_asn1_time(t, at);
}

} // namespace tls

} // namespace shrpx