summaryrefslogtreecommitdiff
path: root/libs/libcurl/src/vtls/wolfssl.c
blob: 9a05f829461d87b01cbc63fcc7dd40961bd2783f (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
/***************************************************************************
 *                                  _   _ ____  _
 *  Project                     ___| | | |  _ \| |
 *                             / __| | | | |_) | |
 *                            | (__| |_| |  _ <| |___
 *                             \___|\___/|_| \_\_____|
 *
 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution. The terms
 * are also available at https://curl.se/docs/copyright.html.
 *
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
 * copies of the Software, and permit persons to whom the Software is
 * furnished to do so, under the terms of the COPYING file.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 * SPDX-License-Identifier: curl
 *
 ***************************************************************************/

/*
 * Source file for all wolfSSL specific code for the TLS/SSL layer. No code
 * but vtls.c should ever call or use these functions.
 *
 */

#include "curl_setup.h"

#ifdef USE_WOLFSSL

#define WOLFSSL_OPTIONS_IGNORE_SYS
#include <wolfssl/version.h>
#include <wolfssl/options.h>

#if LIBWOLFSSL_VERSION_HEX < 0x03004006 /* wolfSSL 3.4.6 (2015) */
#error "wolfSSL version should be at least 3.4.6"
#endif

/* To determine what functions are available we rely on one or both of:
   - the user's options.h generated by wolfSSL
   - the symbols detected by curl's configure
   Since they are markedly different from one another, and one or the other may
   not be available, we do some checking below to bring things in sync. */

/* HAVE_ALPN is wolfSSL's build time symbol for enabling ALPN in options.h. */
#ifndef HAVE_ALPN
#ifdef HAVE_WOLFSSL_USEALPN
#define HAVE_ALPN
#endif
#endif

#include <limits.h>

#include "urldata.h"
#include "sendf.h"
#include "inet_pton.h"
#include "vtls.h"
#include "vtls_int.h"
#include "keylog.h"
#include "parsedate.h"
#include "connect.h" /* for the connect timeout */
#include "select.h"
#include "strcase.h"
#include "x509asn1.h"
#include "curl_printf.h"
#include "multiif.h"

#include <wolfssl/openssl/ssl.h>
#include <wolfssl/ssl.h>
#include <wolfssl/error-ssl.h>
#include "wolfssl.h"

/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"

#ifdef USE_ECH
# include "curl_base64.h"
# define ECH_ENABLED(__data__) \
    (__data__->set.tls_ech && \
     !(__data__->set.tls_ech & CURLECH_DISABLE)\
    )
#endif /* USE_ECH */

/* KEEP_PEER_CERT is a product of the presence of build time symbol
   OPENSSL_EXTRA without NO_CERTS, depending on the version. KEEP_PEER_CERT is
   in wolfSSL's settings.h, and the latter two are build time symbols in
   options.h. */
#ifndef KEEP_PEER_CERT
#if defined(HAVE_WOLFSSL_GET_PEER_CERTIFICATE) || \
    (defined(OPENSSL_EXTRA) && !defined(NO_CERTS))
#define KEEP_PEER_CERT
#endif
#endif

#ifdef HAVE_WOLFSSL_BIO
#define USE_BIO_CHAIN
#ifdef HAVE_WOLFSSL_FULL_BIO
#define USE_FULL_BIO
#else /* HAVE_WOLFSSL_FULL_BIO */
#undef USE_FULL_BIO
#endif
/* wolfSSL 5.7.4 and older do not have these symbols, but only the
 * OpenSSL ones. */
#ifndef WOLFSSL_BIO_CTRL_GET_CLOSE
#define WOLFSSL_BIO_CTRL_GET_CLOSE    BIO_CTRL_GET_CLOSE
#define WOLFSSL_BIO_CTRL_SET_CLOSE    BIO_CTRL_SET_CLOSE
#define WOLFSSL_BIO_CTRL_FLUSH        BIO_CTRL_FLUSH
#define WOLFSSL_BIO_CTRL_DUP          BIO_CTRL_DUP
#define wolfSSL_BIO_set_retry_write   BIO_set_retry_write
#define wolfSSL_BIO_set_retry_read    BIO_set_retry_read
#endif /* !WOLFSSL_BIO_CTRL_GET_CLOSE */

#else /* HAVE_WOLFSSL_BIO */
#undef USE_BIO_CHAIN
#endif

#ifdef OPENSSL_EXTRA
/*
 * Availability note:
 * The TLS 1.3 secret callback (wolfSSL_set_tls13_secret_cb) was added in
 * wolfSSL 4.4.0, but requires the -DHAVE_SECRET_CALLBACK build option. If that
 * option is not set, then TLS 1.3 will not be logged.
 * For TLS 1.2 and before, we use wolfSSL_get_keys().
 * SSL_get_client_random and wolfSSL_get_keys require OPENSSL_EXTRA
 * (--enable-opensslextra or --enable-all).
 */
#if defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13)
static int
wolfssl_tls13_secret_callback(SSL *ssl, int id, const unsigned char *secret,
                              int secretSz, void *ctx)
{
  const char *label;
  unsigned char client_random[SSL3_RANDOM_SIZE];
  (void)ctx;

  if(!ssl || !Curl_tls_keylog_enabled()) {
    return 0;
  }

  switch(id) {
  case CLIENT_EARLY_TRAFFIC_SECRET:
    label = "CLIENT_EARLY_TRAFFIC_SECRET";
    break;
  case CLIENT_HANDSHAKE_TRAFFIC_SECRET:
    label = "CLIENT_HANDSHAKE_TRAFFIC_SECRET";
    break;
  case SERVER_HANDSHAKE_TRAFFIC_SECRET:
    label = "SERVER_HANDSHAKE_TRAFFIC_SECRET";
    break;
  case CLIENT_TRAFFIC_SECRET:
    label = "CLIENT_TRAFFIC_SECRET_0";
    break;
  case SERVER_TRAFFIC_SECRET:
    label = "SERVER_TRAFFIC_SECRET_0";
    break;
  case EARLY_EXPORTER_SECRET:
    label = "EARLY_EXPORTER_SECRET";
    break;
  case EXPORTER_SECRET:
    label = "EXPORTER_SECRET";
    break;
  default:
    return 0;
  }

  if(SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE) == 0) {
    /* Should never happen as wolfSSL_KeepArrays() was called before. */
    return 0;
  }

  Curl_tls_keylog_write(label, client_random, secret, secretSz);
  return 0;
}
#endif /* defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13) */

static void
wolfssl_log_tls12_secret(WOLFSSL *ssl)
{
  unsigned char *ms, *sr, *cr;
  unsigned int msLen, srLen, crLen, i, x = 0;

#if LIBWOLFSSL_VERSION_HEX >= 0x0300d000 /* >= 3.13.0 */
  /* wolfSSL_GetVersion is available since 3.13, we use it instead of
   * SSL_version since the latter relies on OPENSSL_ALL (--enable-opensslall or
   * --enable-all). Failing to perform this check could result in an unusable
   * key log line when TLS 1.3 is actually negotiated. */
  switch(wolfSSL_GetVersion(ssl)) {
  case WOLFSSL_SSLV3:
  case WOLFSSL_TLSV1:
  case WOLFSSL_TLSV1_1:
  case WOLFSSL_TLSV1_2:
    break;
  default:
    /* TLS 1.3 does not use this mechanism, the "master secret" returned below
     * is not directly usable. */
    return;
  }
#endif

  if(wolfSSL_get_keys(ssl, &ms, &msLen, &sr, &srLen, &cr, &crLen) !=
     WOLFSSL_SUCCESS) {
    return;
  }

  /* Check for a missing master secret and skip logging. That can happen if
   * curl rejects the server certificate and aborts the handshake.
   */
  for(i = 0; i < msLen; i++) {
    x |= ms[i];
  }
  if(x == 0) {
    return;
  }

  Curl_tls_keylog_write("CLIENT_RANDOM", cr, ms, msLen);
}
#endif /* OPENSSL_EXTRA */

static int wolfssl_do_file_type(const char *type)
{
  if(!type || !type[0])
    return WOLFSSL_FILETYPE_PEM;
  if(strcasecompare(type, "PEM"))
    return WOLFSSL_FILETYPE_PEM;
  if(strcasecompare(type, "DER"))
    return WOLFSSL_FILETYPE_ASN1;
  return -1;
}

#ifdef WOLFSSL_HAVE_KYBER
struct group_name_map {
  const word16 group;
  const char   *name;
};

static const struct group_name_map gnm[] = {
  { WOLFSSL_KYBER_LEVEL1, "KYBER_LEVEL1" },
  { WOLFSSL_KYBER_LEVEL3, "KYBER_LEVEL3" },
  { WOLFSSL_KYBER_LEVEL5, "KYBER_LEVEL5" },
  { WOLFSSL_P256_KYBER_LEVEL1, "P256_KYBER_LEVEL1" },
  { WOLFSSL_P384_KYBER_LEVEL3, "P384_KYBER_LEVEL3" },
  { WOLFSSL_P521_KYBER_LEVEL5, "P521_KYBER_LEVEL5" },
  { 0, NULL }
};
#endif

#ifdef USE_BIO_CHAIN

static int wolfssl_bio_cf_create(WOLFSSL_BIO *bio)
{
#ifdef USE_FULL_BIO
  wolfSSL_BIO_set_shutdown(bio, 1);
#endif
  wolfSSL_BIO_set_data(bio, NULL);
  return 1;
}

static int wolfssl_bio_cf_destroy(WOLFSSL_BIO *bio)
{
  if(!bio)
    return 0;
  return 1;
}

static long wolfssl_bio_cf_ctrl(WOLFSSL_BIO *bio, int cmd, long num, void *ptr)
{
  struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio);
  long ret = 1;

  (void)cf;
  (void)ptr;
  (void)num;
  switch(cmd) {
  case WOLFSSL_BIO_CTRL_GET_CLOSE:
#ifdef USE_FULL_BIO
    ret = (long)wolfSSL_BIO_get_shutdown(bio);
#else
    ret = 0;
#endif
    break;
  case WOLFSSL_BIO_CTRL_SET_CLOSE:
#ifdef USE_FULL_BIO
    wolfSSL_BIO_set_shutdown(bio, (int)num);
#endif
    break;
  case WOLFSSL_BIO_CTRL_FLUSH:
    /* we do no delayed writes, but if we ever would, this
     * needs to trigger it. */
    ret = 1;
    break;
  case WOLFSSL_BIO_CTRL_DUP:
    ret = 1;
    break;
#ifdef WOLFSSL_BIO_CTRL_EOF
  case WOLFSSL_BIO_CTRL_EOF:
    /* EOF has been reached on input? */
    return (!cf->next || !cf->next->connected);
#endif
  default:
    ret = 0;
    break;
  }
  return ret;
}

static int wolfssl_bio_cf_out_write(WOLFSSL_BIO *bio,
                                    const char *buf, int blen)
{
  struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio);
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;
  struct Curl_easy *data = CF_DATA_CURRENT(cf);
  ssize_t nwritten, skiplen = 0;
  CURLcode result = CURLE_OK;

  DEBUGASSERT(data);
  if(backend->shutting_down && backend->io_send_blocked_len &&
     (backend->io_send_blocked_len < blen)) {
    /* bug in wolfSSL: <https://github.com/wolfSSL/wolfssl/issues/7784>
     * It adds the close notify message again every time we retry
     * sending during shutdown. */
    CURL_TRC_CF(data, cf, "bio_write, shutdown restrict send of %d"
                " to %d bytes", blen, backend->io_send_blocked_len);
    skiplen = (ssize_t)(blen - backend->io_send_blocked_len);
    blen = backend->io_send_blocked_len;
  }
  nwritten = Curl_conn_cf_send(cf->next, data, buf, blen, FALSE, &result);
  backend->io_result = result;
  CURL_TRC_CF(data, cf, "bio_write(len=%d) -> %zd, %d",
              blen, nwritten, result);
#ifdef USE_FULL_BIO
  wolfSSL_BIO_clear_retry_flags(bio);
#endif
  if(nwritten < 0 && CURLE_AGAIN == result) {
    wolfSSL_BIO_set_retry_write(bio);
    if(backend->shutting_down && !backend->io_send_blocked_len)
      backend->io_send_blocked_len = blen;
  }
  else if(!result && skiplen)
    nwritten += skiplen;
  return (int)nwritten;
}

static int wolfssl_bio_cf_in_read(WOLFSSL_BIO *bio, char *buf, int blen)
{
  struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio);
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;
  struct Curl_easy *data = CF_DATA_CURRENT(cf);
  ssize_t nread;
  CURLcode result = CURLE_OK;

  DEBUGASSERT(data);
  /* OpenSSL catches this case, so should we. */
  if(!buf)
    return 0;

  nread = Curl_conn_cf_recv(cf->next, data, buf, blen, &result);
  backend->io_result = result;
  CURL_TRC_CF(data, cf, "bio_read(len=%d) -> %zd, %d", blen, nread, result);
#ifdef USE_FULL_BIO
  wolfSSL_BIO_clear_retry_flags(bio);
#endif
  if(nread < 0 && CURLE_AGAIN == result)
    wolfSSL_BIO_set_retry_read(bio);
  else if(nread == 0)
    connssl->peer_closed = TRUE;
  return (int)nread;
}

static WOLFSSL_BIO_METHOD *wolfssl_bio_cf_method = NULL;

static void wolfssl_bio_cf_init_methods(void)
{
  wolfssl_bio_cf_method = wolfSSL_BIO_meth_new(WOLFSSL_BIO_MEMORY,
                                               "wolfSSL CF BIO");
  wolfSSL_BIO_meth_set_write(wolfssl_bio_cf_method, &wolfssl_bio_cf_out_write);
  wolfSSL_BIO_meth_set_read(wolfssl_bio_cf_method, &wolfssl_bio_cf_in_read);
  wolfSSL_BIO_meth_set_ctrl(wolfssl_bio_cf_method, &wolfssl_bio_cf_ctrl);
  wolfSSL_BIO_meth_set_create(wolfssl_bio_cf_method, &wolfssl_bio_cf_create);
  wolfSSL_BIO_meth_set_destroy(wolfssl_bio_cf_method, &wolfssl_bio_cf_destroy);
}

static void wolfssl_bio_cf_free_methods(void)
{
  wolfSSL_BIO_meth_free(wolfssl_bio_cf_method);
}

#else /* USE_BIO_CHAIN */

#define wolfssl_bio_cf_init_methods() Curl_nop_stmt
#define wolfssl_bio_cf_free_methods() Curl_nop_stmt

#endif /* !USE_BIO_CHAIN */

static void wolfssl_session_free(void *sdata, size_t slen)
{
  (void)slen;
  free(sdata);
}

CURLcode wssl_cache_session(struct Curl_cfilter *cf,
                            struct Curl_easy *data,
                            struct ssl_peer *peer,
                            WOLFSSL_SESSION *session)
{
  CURLcode result = CURLE_OK;
  unsigned char *sdata = NULL;
  unsigned int slen;

  if(!session)
    goto out;

  slen = wolfSSL_i2d_SSL_SESSION(session, NULL);
  if(slen <= 0) {
    CURL_TRC_CF(data, cf, "fail to assess session length: %u", slen);
    result = CURLE_FAILED_INIT;
    goto out;
  }
  sdata = calloc(1, slen);
  if(!sdata) {
    failf(data, "unable to allocate session buffer of %u bytes", slen);
    result = CURLE_OUT_OF_MEMORY;
    goto out;
  }
  slen = wolfSSL_i2d_SSL_SESSION(session, &sdata);
  if(slen <= 0) {
    CURL_TRC_CF(data, cf, "fail to serialize session: %u", slen);
    result = CURLE_FAILED_INIT;
    goto out;
  }

  Curl_ssl_sessionid_lock(data);
  result = Curl_ssl_set_sessionid(cf, data, peer, NULL,
                                  sdata, slen, wolfssl_session_free);
  Curl_ssl_sessionid_unlock(data);
  if(result)
    failf(data, "failed to add new ssl session to cache (%d)", result);
  else {
    CURL_TRC_CF(data, cf, "added new session to cache");
    sdata = NULL;
  }

out:
  free(sdata);
  return 0;
}

static int wssl_vtls_new_session_cb(WOLFSSL *ssl, WOLFSSL_SESSION *session)
{
  struct Curl_cfilter *cf;

  cf = (struct Curl_cfilter*)wolfSSL_get_app_data(ssl);
  DEBUGASSERT(cf != NULL);
  if(cf && session) {
    struct ssl_connect_data *connssl = cf->ctx;
    struct Curl_easy *data = CF_DATA_CURRENT(cf);
    DEBUGASSERT(connssl);
    DEBUGASSERT(data);
    if(connssl && data) {
      (void)wssl_cache_session(cf, data, &connssl->peer, session);
    }
  }
  return 0;
}

CURLcode wssl_setup_session(struct Curl_cfilter *cf,
                            struct Curl_easy *data,
                            struct wolfssl_ctx *wss,
                            struct ssl_peer *peer)
{
  void *psdata;
  const unsigned char *sdata = NULL;
  size_t slen = 0;
  CURLcode result = CURLE_OK;

  Curl_ssl_sessionid_lock(data);
  if(!Curl_ssl_getsessionid(cf, data, peer, &psdata, &slen, NULL)) {
    WOLFSSL_SESSION *session;
    sdata = psdata;
    session = wolfSSL_d2i_SSL_SESSION(NULL, &sdata, (long)slen);
    if(session) {
      int ret = wolfSSL_set_session(wss->handle, session);
      if(ret != WOLFSSL_SUCCESS) {
        Curl_ssl_delsessionid(data, psdata);
        infof(data, "previous session not accepted (%d), "
              "removing from cache", ret);
      }
      else
        infof(data, "SSL reusing session ID");
      wolfSSL_SESSION_free(session);
    }
    else {
      failf(data, "could not decode previous session");
    }
  }
  Curl_ssl_sessionid_unlock(data);
  return result;
}

static CURLcode populate_x509_store(struct Curl_cfilter *cf,
                                    struct Curl_easy *data,
                                    WOLFSSL_X509_STORE *store,
                                    struct wolfssl_ctx *wssl)
{
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  const struct curl_blob *ca_info_blob = conn_config->ca_info_blob;
  const char * const ssl_cafile =
    /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
    (ca_info_blob ? NULL : conn_config->CAfile);
  const char * const ssl_capath = conn_config->CApath;
  struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  bool imported_native_ca = FALSE;

#if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SYS_CA_CERTS)
  /* load native CA certificates */
  if(ssl_config->native_ca_store) {
    if(wolfSSL_CTX_load_system_CA_certs(wssl->ctx) != WOLFSSL_SUCCESS) {
      infof(data, "error importing native CA store, continuing anyway");
    }
    else {
      imported_native_ca = TRUE;
      infof(data, "successfully imported native CA store");
      wssl->x509_store_setup = TRUE;
    }
  }
#endif /* !NO_FILESYSTEM */

  /* load certificate blob */
  if(ca_info_blob) {
    if(wolfSSL_CTX_load_verify_buffer(wssl->ctx, ca_info_blob->data,
                                      (long)ca_info_blob->len,
                                      WOLFSSL_FILETYPE_PEM) !=
       WOLFSSL_SUCCESS) {
      if(imported_native_ca) {
        infof(data, "error importing CA certificate blob, continuing anyway");
      }
      else {
        failf(data, "error importing CA certificate blob");
        return CURLE_SSL_CACERT_BADFILE;
      }
    }
    else {
      infof(data, "successfully imported CA certificate blob");
      wssl->x509_store_setup = TRUE;
    }
  }

#ifndef NO_FILESYSTEM
  /* load trusted cacert from file if not blob */

  CURL_TRC_CF(data, cf, "populate_x509_store, path=%s, blob=%d",
              ssl_cafile ? ssl_cafile : "none", !!ca_info_blob);
  if(!store)
    return CURLE_OUT_OF_MEMORY;

  if((ssl_cafile || ssl_capath) && (!wssl->x509_store_setup)) {
    int rc =
      wolfSSL_CTX_load_verify_locations_ex(wssl->ctx,
                                           ssl_cafile,
                                           ssl_capath,
                                           WOLFSSL_LOAD_FLAG_IGNORE_ERR);
    if(WOLFSSL_SUCCESS != rc) {
      if(conn_config->verifypeer) {
        /* Fail if we insist on successfully verifying the server. */
        failf(data, "error setting certificate verify locations:"
              " CAfile: %s CApath: %s",
              ssl_cafile ? ssl_cafile : "none",
              ssl_capath ? ssl_capath : "none");
        return CURLE_SSL_CACERT_BADFILE;
      }
      else {
        /* Just continue with a warning if no strict certificate
           verification is required. */
        infof(data, "error setting certificate verify locations,"
              " continuing anyway:");
      }
    }
    else {
      /* Everything is fine. */
      infof(data, "successfully set certificate verify locations:");
    }
    infof(data, " CAfile: %s", ssl_cafile ? ssl_cafile : "none");
    infof(data, " CApath: %s", ssl_capath ? ssl_capath : "none");
  }
#endif
  (void)store;
  wssl->x509_store_setup = TRUE;
  return CURLE_OK;
}

/* key to use at `multi->proto_hash` */
#define MPROTO_WSSL_X509_KEY   "tls:wssl:x509:share"

struct wssl_x509_share {
  char *CAfile;         /* CAfile path used to generate X509 store */
  WOLFSSL_X509_STORE *store; /* cached X509 store or NULL if none */
  struct curltime time; /* when the cached store was created */
};

static void wssl_x509_share_free(void *key, size_t key_len, void *p)
{
  struct wssl_x509_share *share = p;
  DEBUGASSERT(key_len == (sizeof(MPROTO_WSSL_X509_KEY)-1));
  DEBUGASSERT(!memcmp(MPROTO_WSSL_X509_KEY, key, key_len));
  (void)key;
  (void)key_len;
  if(share->store) {
    wolfSSL_X509_STORE_free(share->store);
  }
  free(share->CAfile);
  free(share);
}

static bool
cached_x509_store_expired(const struct Curl_easy *data,
                          const struct wssl_x509_share *mb)
{
  const struct ssl_general_config *cfg = &data->set.general_ssl;
  struct curltime now = Curl_now();
  timediff_t elapsed_ms = Curl_timediff(now, mb->time);
  timediff_t timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000;

  if(timeout_ms < 0)
    return FALSE;

  return elapsed_ms >= timeout_ms;
}

static bool
cached_x509_store_different(struct Curl_cfilter *cf,
                            const struct wssl_x509_share *mb)
{
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  if(!mb->CAfile || !conn_config->CAfile)
    return mb->CAfile != conn_config->CAfile;

  return strcmp(mb->CAfile, conn_config->CAfile);
}

static WOLFSSL_X509_STORE *get_cached_x509_store(struct Curl_cfilter *cf,
                                                 const struct Curl_easy *data)
{
  struct Curl_multi *multi = data->multi;
  struct wssl_x509_share *share;
  WOLFSSL_X509_STORE *store = NULL;

  DEBUGASSERT(multi);
  share = multi ? Curl_hash_pick(&multi->proto_hash,
                                 (void *)MPROTO_WSSL_X509_KEY,
                                 sizeof(MPROTO_WSSL_X509_KEY)-1) : NULL;
  if(share && share->store &&
     !cached_x509_store_expired(data, share) &&
     !cached_x509_store_different(cf, share)) {
    store = share->store;
  }

  return store;
}

static void set_cached_x509_store(struct Curl_cfilter *cf,
                                  const struct Curl_easy *data,
                                  WOLFSSL_X509_STORE *store)
{
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  struct Curl_multi *multi = data->multi;
  struct wssl_x509_share *share;

  DEBUGASSERT(multi);
  if(!multi)
    return;
  share = Curl_hash_pick(&multi->proto_hash,
                         (void *)MPROTO_WSSL_X509_KEY,
                         sizeof(MPROTO_WSSL_X509_KEY)-1);

  if(!share) {
    share = calloc(1, sizeof(*share));
    if(!share)
      return;
    if(!Curl_hash_add2(&multi->proto_hash,
                       (void *)MPROTO_WSSL_X509_KEY,
                       sizeof(MPROTO_WSSL_X509_KEY)-1,
                       share, wssl_x509_share_free)) {
      free(share);
      return;
    }
  }

  if(wolfSSL_X509_STORE_up_ref(store)) {
    char *CAfile = NULL;

    if(conn_config->CAfile) {
      CAfile = strdup(conn_config->CAfile);
      if(!CAfile) {
        wolfSSL_X509_STORE_free(store);
        return;
      }
    }

    if(share->store) {
      wolfSSL_X509_STORE_free(share->store);
      free(share->CAfile);
    }

    share->time = Curl_now();
    share->store = store;
    share->CAfile = CAfile;
  }
}

CURLcode Curl_wssl_setup_x509_store(struct Curl_cfilter *cf,
                                    struct Curl_easy *data,
                                    struct wolfssl_ctx *wssl)
{
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  CURLcode result = CURLE_OK;
  WOLFSSL_X509_STORE *cached_store;
  bool cache_criteria_met;

  /* Consider the X509 store cacheable if it comes exclusively from a CAfile,
     or no source is provided and we are falling back to wolfSSL's built-in
     default. */
  cache_criteria_met = (data->set.general_ssl.ca_cache_timeout != 0) &&
    conn_config->verifypeer &&
    !conn_config->CApath &&
    !conn_config->ca_info_blob &&
    !ssl_config->primary.CRLfile &&
    !ssl_config->native_ca_store;

  cached_store = cache_criteria_met ? get_cached_x509_store(cf, data) : NULL;
  if(cached_store && wolfSSL_CTX_get_cert_store(wssl->ctx) == cached_store) {
    /* The cached store is already in use, do nothing. */
  }
  else if(cached_store && wolfSSL_X509_STORE_up_ref(cached_store)) {
    wolfSSL_CTX_set_cert_store(wssl->ctx, cached_store);
  }
  else if(cache_criteria_met) {
    /* wolfSSL's initial store in CTX is not shareable by default.
     * Make a new one, suitable for adding to the cache. See #14278 */
    WOLFSSL_X509_STORE *store = wolfSSL_X509_STORE_new();
    if(!store) {
      failf(data, "SSL: could not create a X509 store");
      return CURLE_OUT_OF_MEMORY;
    }
    wolfSSL_CTX_set_cert_store(wssl->ctx, store);

    result = populate_x509_store(cf, data, store, wssl);
    if(!result) {
      set_cached_x509_store(cf, data, store);
    }
  }
  else {
   /* We never share the CTX's store, use it. */
   WOLFSSL_X509_STORE *store = wolfSSL_CTX_get_cert_store(wssl->ctx);
   result = populate_x509_store(cf, data, store, wssl);
  }

  return result;
}

#ifdef WOLFSSL_TLS13
static CURLcode
wssl_add_default_ciphers(bool tls13, struct dynbuf *buf)
{
  int i;
  char *str;

  for(i = 0; (str = wolfSSL_get_cipher_list(i)); i++) {
    size_t n;
    if((strncmp(str, "TLS13", 5) == 0) != tls13)
      continue;

    /* if there already is data in the string, add colon separator */
    if(Curl_dyn_len(buf)) {
      CURLcode result = Curl_dyn_addn(buf, ":", 1);
      if(result)
        return result;
    }

    n = strlen(str);
    if(Curl_dyn_addn(buf, str, n))
      return CURLE_OUT_OF_MEMORY;
  }

  return CURLE_OK;
}
#endif

/* 4.2.0 (2019) */
#if LIBWOLFSSL_VERSION_HEX < 0x04002000 || !defined(OPENSSL_EXTRA)
static int
wssl_legacy_CTX_set_min_proto_version(WOLFSSL_CTX* ctx, int version)
{
  int res;
  switch(version) {
  default:
  case TLS1_VERSION:
    res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1);
    if(res == WOLFSSL_SUCCESS)
      return res;
    FALLTHROUGH();
  case TLS1_1_VERSION:
    res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_1);
    if(res == WOLFSSL_SUCCESS)
      return res;
    FALLTHROUGH();
  case TLS1_2_VERSION:
    res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_2);
#ifdef WOLFSSL_TLS13
    if(res == WOLFSSL_SUCCESS)
      return res;
    FALLTHROUGH();
  case TLS1_3_VERSION:
    res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_3);
#endif
  }
  return res;
}
static int
wssl_legacy_CTX_set_max_proto_version(WOLFSSL_CTX* ctx, int version)
{
  (void) ctx, (void) version;
  return WOLFSSL_NOT_IMPLEMENTED;
}
#define wolfSSL_CTX_set_min_proto_version wssl_legacy_CTX_set_min_proto_version
#define wolfSSL_CTX_set_max_proto_version wssl_legacy_CTX_set_max_proto_version
#endif

/*
 * This function loads all the client/CA certificates and CRLs. Setup the TLS
 * layer and do all necessary magic.
 */
static CURLcode
wolfssl_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data)
{
  int res;
  char *curves;
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  const struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  WOLFSSL_METHOD* req_method = NULL;
#ifdef WOLFSSL_HAVE_KYBER
  word16 pqkem = 0;
  size_t idx = 0;
#endif

  DEBUGASSERT(backend);

  if(connssl->state == ssl_connection_complete)
    return CURLE_OK;

#if LIBWOLFSSL_VERSION_HEX < 0x04002000 /* 4.2.0 (2019) */
  req_method = wolfSSLv23_client_method();
#else
  req_method = wolfTLS_client_method();
#endif
  if(!req_method) {
    failf(data, "wolfSSL: could not create a client method");
    return CURLE_OUT_OF_MEMORY;
  }

  if(backend->ctx)
    wolfSSL_CTX_free(backend->ctx);

  backend->ctx = wolfSSL_CTX_new(req_method);
  if(!backend->ctx) {
    failf(data, "wolfSSL: could not create a context");
    return CURLE_OUT_OF_MEMORY;
  }

  switch(conn_config->version) {
  case CURL_SSLVERSION_DEFAULT:
  case CURL_SSLVERSION_TLSv1:
  case CURL_SSLVERSION_TLSv1_0:
    res = wolfSSL_CTX_set_min_proto_version(backend->ctx, TLS1_VERSION);
    break;
  case CURL_SSLVERSION_TLSv1_1:
    res = wolfSSL_CTX_set_min_proto_version(backend->ctx, TLS1_1_VERSION);
    break;
  case CURL_SSLVERSION_TLSv1_2:
    res = wolfSSL_CTX_set_min_proto_version(backend->ctx, TLS1_2_VERSION);
    break;
#ifdef WOLFSSL_TLS13
  case CURL_SSLVERSION_TLSv1_3:
    res = wolfSSL_CTX_set_min_proto_version(backend->ctx, TLS1_3_VERSION);
    break;
#endif
  default:
    failf(data, "wolfSSL: unsupported minimum TLS version value");
    return CURLE_SSL_CONNECT_ERROR;
  }
  if(res != WOLFSSL_SUCCESS) {
    failf(data, "wolfSSL: failed set the minimum TLS version");
    return CURLE_SSL_CONNECT_ERROR;
  }

  switch(conn_config->version_max) {
#ifdef WOLFSSL_TLS13
  case CURL_SSLVERSION_MAX_TLSv1_3:
    res = wolfSSL_CTX_set_max_proto_version(backend->ctx, TLS1_3_VERSION);
    break;
#endif
  case CURL_SSLVERSION_MAX_TLSv1_2:
    res = wolfSSL_CTX_set_max_proto_version(backend->ctx, TLS1_2_VERSION);
    break;
  case CURL_SSLVERSION_MAX_TLSv1_1:
    res = wolfSSL_CTX_set_max_proto_version(backend->ctx, TLS1_1_VERSION);
    break;
  case CURL_SSLVERSION_MAX_TLSv1_0:
    res = wolfSSL_CTX_set_max_proto_version(backend->ctx, TLS1_VERSION);
    break;
  case CURL_SSLVERSION_MAX_DEFAULT:
  case CURL_SSLVERSION_MAX_NONE:
    res = WOLFSSL_SUCCESS;
    break;
  default:
    failf(data, "wolfSSL: unsupported maximum TLS version value");
    return CURLE_SSL_CONNECT_ERROR;
  }
  if(res != WOLFSSL_SUCCESS) {
    failf(data, "wolfSSL: failed set the maximum TLS version");
    return CURLE_SSL_CONNECT_ERROR;
  }

#ifndef WOLFSSL_TLS13
  {
    char *ciphers = conn_config->cipher_list;
    if(ciphers) {
      if(!SSL_CTX_set_cipher_list(backend->ctx, ciphers)) {
        failf(data, "failed setting cipher list: %s", ciphers);
        return CURLE_SSL_CIPHER;
      }
      infof(data, "Cipher selection: %s", ciphers);
    }
  }
#else
#define MAX_CIPHER_LEN 4096
  if(conn_config->cipher_list || conn_config->cipher_list13) {
    const char *ciphers12 = conn_config->cipher_list;
    const char *ciphers13 = conn_config->cipher_list13;
    struct dynbuf c;
    CURLcode result;
    Curl_dyn_init(&c, MAX_CIPHER_LEN);

    if(ciphers13)
      result = Curl_dyn_add(&c, ciphers13);
    else
      result = wssl_add_default_ciphers(TRUE, &c);

    if(!result) {
      if(ciphers12) {
        if(Curl_dyn_len(&c))
          result = Curl_dyn_addn(&c, ":", 1);
        if(!result)
          result = Curl_dyn_add(&c, ciphers12);
      }
      else
        result = wssl_add_default_ciphers(FALSE, &c);
    }
    if(result)
      return result;

    if(!wolfSSL_CTX_set_cipher_list(backend->ctx, Curl_dyn_ptr(&c))) {
      failf(data, "failed setting cipher list: %s", Curl_dyn_ptr(&c));
      Curl_dyn_free(&c);
      return CURLE_SSL_CIPHER;
    }
    infof(data, "Cipher selection: %s", Curl_dyn_ptr(&c));
    Curl_dyn_free(&c);
  }
#endif

  curves = conn_config->curves;
  if(curves) {

#ifdef WOLFSSL_HAVE_KYBER
    for(idx = 0; gnm[idx].name != NULL; idx++) {
      if(strncmp(curves, gnm[idx].name, strlen(gnm[idx].name)) == 0) {
        pqkem = gnm[idx].group;
        break;
      }
    }

    if(pqkem == 0)
#endif
    {
      if(!wolfSSL_CTX_set1_curves_list(backend->ctx, curves)) {
        failf(data, "failed setting curves list: '%s'", curves);
        return CURLE_SSL_CIPHER;
      }
    }
  }

  /* Load the client certificate, and private key */
#ifndef NO_FILESYSTEM
  if(ssl_config->primary.cert_blob || ssl_config->primary.clientcert) {
    const char *cert_file = ssl_config->primary.clientcert;
    const char *key_file = ssl_config->key;
    const struct curl_blob *cert_blob = ssl_config->primary.cert_blob;
    const struct curl_blob *key_blob = ssl_config->key_blob;
    int file_type = wolfssl_do_file_type(ssl_config->cert_type);
    int rc;

    switch(file_type) {
    case WOLFSSL_FILETYPE_PEM:
      rc = cert_blob ?
        wolfSSL_CTX_use_certificate_chain_buffer(backend->ctx,
                                                 cert_blob->data,
                                                 (long)cert_blob->len) :
        wolfSSL_CTX_use_certificate_chain_file(backend->ctx, cert_file);
      break;
    case WOLFSSL_FILETYPE_ASN1:
      rc = cert_blob ?
        wolfSSL_CTX_use_certificate_buffer(backend->ctx, cert_blob->data,
                                           (long)cert_blob->len, file_type) :
        wolfSSL_CTX_use_certificate_file(backend->ctx, cert_file, file_type);
      break;
    default:
      failf(data, "unknown cert type");
      return CURLE_BAD_FUNCTION_ARGUMENT;
    }
    if(rc != 1) {
      failf(data, "unable to use client certificate");
      return CURLE_SSL_CONNECT_ERROR;
    }

    if(!key_blob && !key_file) {
      key_blob = cert_blob;
      key_file = cert_file;
    }
    else
      file_type = wolfssl_do_file_type(ssl_config->key_type);

    rc = key_blob ?
      wolfSSL_CTX_use_PrivateKey_buffer(backend->ctx, key_blob->data,
                                        (long)key_blob->len, file_type) :
      wolfSSL_CTX_use_PrivateKey_file(backend->ctx, key_file, file_type);
    if(rc != 1) {
      failf(data, "unable to set private key");
      return CURLE_SSL_CONNECT_ERROR;
    }
  }
#else /* NO_FILESYSTEM */
  if(ssl_config->primary.cert_blob) {
    const struct curl_blob *cert_blob = ssl_config->primary.cert_blob;
    const struct curl_blob *key_blob = ssl_config->key_blob;
    int file_type = wolfssl_do_file_type(ssl_config->cert_type);
    int rc;

    switch(file_type) {
    case WOLFSSL_FILETYPE_PEM:
      rc = wolfSSL_CTX_use_certificate_chain_buffer(backend->ctx,
                                                    cert_blob->data,
                                                    (long)cert_blob->len);
      break;
    case WOLFSSL_FILETYPE_ASN1:
      rc = wolfSSL_CTX_use_certificate_buffer(backend->ctx, cert_blob->data,
                                              (long)cert_blob->len, file_type);
      break;
    default:
      failf(data, "unknown cert type");
      return CURLE_BAD_FUNCTION_ARGUMENT;
    }
    if(rc != 1) {
      failf(data, "unable to use client certificate");
      return CURLE_SSL_CONNECT_ERROR;
    }

    if(!key_blob)
      key_blob = cert_blob;
    else
      file_type = wolfssl_do_file_type(ssl_config->key_type);

    if(wolfSSL_CTX_use_PrivateKey_buffer(backend->ctx, key_blob->data,
                                         (long)key_blob->len,
                                         file_type) != 1) {
      failf(data, "unable to set private key");
      return CURLE_SSL_CONNECT_ERROR;
    }
  }
#endif /* !NO_FILESYSTEM */

  /* SSL always tries to verify the peer, this only says whether it should
   * fail to connect if the verification fails, or if it should continue
   * anyway. In the latter case the result of the verification is checked with
   * SSL_get_verify_result() below. */
  wolfSSL_CTX_set_verify(backend->ctx,
                         conn_config->verifypeer ? WOLFSSL_VERIFY_PEER :
                         WOLFSSL_VERIFY_NONE, NULL);

#ifdef HAVE_SNI
  if(connssl->peer.sni) {
    size_t sni_len = strlen(connssl->peer.sni);
    if((sni_len < USHRT_MAX)) {
      if(wolfSSL_CTX_UseSNI(backend->ctx, WOLFSSL_SNI_HOST_NAME,
                            connssl->peer.sni,
                            (unsigned short)sni_len) != 1) {
        failf(data, "Failed to set SNI");
        return CURLE_SSL_CONNECT_ERROR;
      }
    }
  }
#endif

  /* give application a chance to interfere with SSL set up. */
  if(data->set.ssl.fsslctx) {
    CURLcode result;
    if(!backend->x509_store_setup) {
      result = Curl_wssl_setup_x509_store(cf, data, backend);
      if(result)
        return result;
    }
    result = (*data->set.ssl.fsslctx)(data, backend->ctx,
                                      data->set.ssl.fsslctxp);
    if(result) {
      failf(data, "error signaled by ssl ctx callback");
      return result;
    }
  }
#ifdef NO_FILESYSTEM
  else if(conn_config->verifypeer) {
    failf(data, "SSL: Certificates cannot be loaded because wolfSSL was built"
          " with \"no filesystem\". Either disable peer verification"
          " (insecure) or if you are building an application with libcurl you"
          " can load certificates via CURLOPT_SSL_CTX_FUNCTION.");
    return CURLE_SSL_CONNECT_ERROR;
  }
#endif

  /* Let's make an SSL structure */
  if(backend->handle)
    wolfSSL_free(backend->handle);
  backend->handle = wolfSSL_new(backend->ctx);
  if(!backend->handle) {
    failf(data, "SSL: could not create a handle");
    return CURLE_OUT_OF_MEMORY;
  }

#ifdef WOLFSSL_HAVE_KYBER
  if(pqkem) {
    if(wolfSSL_UseKeyShare(backend->handle, pqkem) != WOLFSSL_SUCCESS) {
      failf(data, "unable to use PQ KEM");
    }
  }
#endif

#ifdef HAVE_ALPN
  if(connssl->alpn) {
    struct alpn_proto_buf proto;
    CURLcode result;

    result = Curl_alpn_to_proto_str(&proto, connssl->alpn);
    if(result ||
       wolfSSL_UseALPN(backend->handle,
                       (char *)proto.data, (unsigned int)proto.len,
                       WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) != WOLFSSL_SUCCESS) {
      failf(data, "SSL: failed setting ALPN protocols");
      return CURLE_SSL_CONNECT_ERROR;
    }
    infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
  }
#endif /* HAVE_ALPN */

#ifdef OPENSSL_EXTRA
  if(Curl_tls_keylog_enabled()) {
    /* Ensure the Client Random is preserved. */
    wolfSSL_KeepArrays(backend->handle);
#if defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13)
    wolfSSL_set_tls13_secret_cb(backend->handle,
                                wolfssl_tls13_secret_callback, NULL);
#endif
  }
#endif /* OPENSSL_EXTRA */

#ifdef HAVE_SECURE_RENEGOTIATION
  if(wolfSSL_UseSecureRenegotiation(backend->handle) != SSL_SUCCESS) {
    failf(data, "SSL: failed setting secure renegotiation");
    return CURLE_SSL_CONNECT_ERROR;
  }
#endif /* HAVE_SECURE_RENEGOTIATION */

  /* Check if there is a cached ID we can/should use here! */
  if(ssl_config->primary.cache_session) {
    /* Set session from cache if there is one */
    (void)wssl_setup_session(cf, data, backend, &connssl->peer);
    /* Register to get notified when a new session is received */
    wolfSSL_set_app_data(backend->handle, cf);
    wolfSSL_CTX_sess_set_new_cb(backend->ctx, wssl_vtls_new_session_cb);
  }

#ifdef USE_ECH
  if(ECH_ENABLED(data)) {
    int trying_ech_now = 0;

    if(data->set.str[STRING_ECH_PUBLIC]) {
      infof(data, "ECH: outername not (yet) supported with wolfSSL");
      return CURLE_SSL_CONNECT_ERROR;
    }
    if(data->set.tls_ech == CURLECH_GREASE) {
      infof(data, "ECH: GREASE'd ECH not yet supported for wolfSSL");
      return CURLE_SSL_CONNECT_ERROR;
    }
    if(data->set.tls_ech & CURLECH_CLA_CFG
       && data->set.str[STRING_ECH_CONFIG]) {
      char *b64val = data->set.str[STRING_ECH_CONFIG];
      word32 b64len = 0;

      b64len = (word32) strlen(b64val);
      if(b64len
         && wolfSSL_SetEchConfigsBase64(backend->handle, b64val, b64len)
              != WOLFSSL_SUCCESS) {
        if(data->set.tls_ech & CURLECH_HARD)
          return CURLE_SSL_CONNECT_ERROR;
      }
      else {
       trying_ech_now = 1;
       infof(data, "ECH: ECHConfig from command line");
      }
    }
    else {
      struct Curl_dns_entry *dns = NULL;

      dns = Curl_fetch_addr(data, connssl->peer.hostname, connssl->peer.port);
      if(!dns) {
        infof(data, "ECH: requested but no DNS info available");
        if(data->set.tls_ech & CURLECH_HARD)
          return CURLE_SSL_CONNECT_ERROR;
      }
      else {
        struct Curl_https_rrinfo *rinfo = NULL;

        rinfo = dns->hinfo;
        if(rinfo && rinfo->echconfiglist) {
          unsigned char *ecl = rinfo->echconfiglist;
          size_t elen = rinfo->echconfiglist_len;

          infof(data, "ECH: ECHConfig from DoH HTTPS RR");
          if(wolfSSL_SetEchConfigs(backend->handle, ecl, (word32) elen) !=
                WOLFSSL_SUCCESS) {
            infof(data, "ECH: wolfSSL_SetEchConfigs failed");
            if(data->set.tls_ech & CURLECH_HARD)
              return CURLE_SSL_CONNECT_ERROR;
          }
          else {
            trying_ech_now = 1;
            infof(data, "ECH: imported ECHConfigList of length %ld", elen);
          }
        }
        else {
          infof(data, "ECH: requested but no ECHConfig available");
          if(data->set.tls_ech & CURLECH_HARD)
            return CURLE_SSL_CONNECT_ERROR;
        }
        Curl_resolv_unlink(data, &dns);
      }
    }

    if(trying_ech_now
       && SSL_set_min_proto_version(backend->handle, TLS1_3_VERSION) != 1) {
      infof(data, "ECH: cannot force TLSv1.3 [ERROR]");
      return CURLE_SSL_CONNECT_ERROR;
    }

  }
#endif  /* USE_ECH */

#ifdef USE_BIO_CHAIN
  {
    WOLFSSL_BIO *bio;

    bio = wolfSSL_BIO_new(wolfssl_bio_cf_method);
    if(!bio)
      return CURLE_OUT_OF_MEMORY;

    wolfSSL_BIO_set_data(bio, cf);
    wolfSSL_set_bio(backend->handle, bio, bio);
  }
#else /* USE_BIO_CHAIN */
  /* pass the raw socket into the SSL layer */
  if(!wolfSSL_set_fd(backend->handle,
                     (int)Curl_conn_cf_get_socket(cf, data))) {
    failf(data, "SSL: SSL_set_fd failed");
    return CURLE_SSL_CONNECT_ERROR;
  }
#endif /* !USE_BIO_CHAIN */

  connssl->connecting_state = ssl_connect_2;
  return CURLE_OK;
}


static char *wolfssl_strerror(unsigned long error, char *buf,
                              unsigned long size)
{
  DEBUGASSERT(size > 40);
  *buf = '\0';

  wolfSSL_ERR_error_string_n(error, buf, size);

  if(!*buf) {
    const char *msg = error ? "Unknown error" : "No error";
    /* the string fits because the assert above assures this */
    strcpy(buf, msg);
  }

  return buf;
}


static CURLcode
wolfssl_connect_step2(struct Curl_cfilter *cf, struct Curl_easy *data)
{
  int ret = -1;
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
#ifndef CURL_DISABLE_PROXY
  const char * const pinnedpubkey = Curl_ssl_cf_is_proxy(cf) ?
    data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
    data->set.str[STRING_SSL_PINNEDPUBLICKEY];
#else
  const char * const pinnedpubkey = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
#endif

  DEBUGASSERT(backend);

  wolfSSL_ERR_clear_error();

  /* Enable RFC2818 checks */
  if(conn_config->verifyhost) {
    char *snihost = connssl->peer.sni ?
      connssl->peer.sni : connssl->peer.hostname;
    if(wolfSSL_check_domain_name(backend->handle, snihost) == WOLFSSL_FAILURE)
      return CURLE_SSL_CONNECT_ERROR;
  }

  if(!backend->x509_store_setup) {
    /* After having send off the ClientHello, we prepare the x509
     * store to verify the coming certificate from the server */
    CURLcode result;
    result = Curl_wssl_setup_x509_store(cf, data, backend);
    if(result)
      return result;
  }

  connssl->io_need = CURL_SSL_IO_NEED_NONE;
  ret = wolfSSL_connect(backend->handle);

#ifdef OPENSSL_EXTRA
  if(Curl_tls_keylog_enabled()) {
    /* If key logging is enabled, wait for the handshake to complete and then
     * proceed with logging secrets (for TLS 1.2 or older).
     *
     * During the handshake (ret==-1), wolfSSL_want_read() is true as it waits
     * for the server response. At that point the master secret is not yet
     * available, so we must not try to read it.
     * To log the secret on completion with a handshake failure, detect
     * completion via the observation that there is nothing to read or write.
     * Note that OpenSSL SSL_want_read() is always true here. If wolfSSL ever
     * changes, the worst case is that no key is logged on error.
     */
    if(ret == WOLFSSL_SUCCESS ||
       (!wolfSSL_want_read(backend->handle) &&
        !wolfSSL_want_write(backend->handle))) {
      wolfssl_log_tls12_secret(backend->handle);
      /* Client Random and master secrets are no longer needed, erase these.
       * Ignored while the handshake is still in progress. */
      wolfSSL_FreeArrays(backend->handle);
    }
  }
#endif  /* OPENSSL_EXTRA */

  if(ret != 1) {
    int detail = wolfSSL_get_error(backend->handle, ret);

    if(WOLFSSL_ERROR_WANT_READ == detail) {
      connssl->io_need = CURL_SSL_IO_NEED_RECV;
      return CURLE_OK;
    }
    else if(WOLFSSL_ERROR_WANT_WRITE == detail) {
      connssl->io_need = CURL_SSL_IO_NEED_SEND;
      return CURLE_OK;
    }
    /* There is no easy way to override only the CN matching.
     * This will enable the override of both mismatching SubjectAltNames
     * as also mismatching CN fields */
    else if(DOMAIN_NAME_MISMATCH == detail) {
#if 1
      failf(data, " subject alt name(s) or common name do not match \"%s\"",
            connssl->peer.dispname);
      return CURLE_PEER_FAILED_VERIFICATION;
#else
      /* When the wolfssl_check_domain_name() is used and you desire to
       * continue on a DOMAIN_NAME_MISMATCH, i.e. 'ssl_config.verifyhost
       * == 0', CyaSSL version 2.4.0 will fail with an INCOMPLETE_DATA
       * error. The only way to do this is currently to switch the
       * Wolfssl_check_domain_name() in and out based on the
       * 'ssl_config.verifyhost' value. */
      if(conn_config->verifyhost) {
        failf(data,
              " subject alt name(s) or common name do not match \"%s\"\n",
              connssl->dispname);
        return CURLE_PEER_FAILED_VERIFICATION;
      }
      else {
        infof(data,
              " subject alt name(s) and/or common name do not match \"%s\"",
              connssl->dispname);
        return CURLE_OK;
      }
#endif
    }
    else if(ASN_NO_SIGNER_E == detail) {
      if(conn_config->verifypeer) {
        failf(data, " CA signer not available for verification");
        return CURLE_SSL_CACERT_BADFILE;
      }
      else {
        /* Just continue with a warning if no strict certificate
           verification is required. */
        infof(data, "CA signer not available for verification, "
                    "continuing anyway");
      }
    }
    else if(ASN_AFTER_DATE_E == detail) {
      failf(data, "server verification failed: certificate has expired.");
      return CURLE_PEER_FAILED_VERIFICATION;
    }
    else if(ASN_BEFORE_DATE_E == detail) {
      failf(data, "server verification failed: certificate not valid yet.");
      return CURLE_PEER_FAILED_VERIFICATION;
    }
#ifdef USE_ECH
    else if(-1 == detail) {
      /* try access a retry_config ECHConfigList for tracing */
      byte echConfigs[1000];
      word32 echConfigsLen = 1000;
      int rv = 0;

      /* this currently does not produce the retry_configs */
      rv = wolfSSL_GetEchConfigs(backend->handle, echConfigs,
                                 &echConfigsLen);
      if(rv != WOLFSSL_SUCCESS) {
        infof(data, "Failed to get ECHConfigs");
      }
      else {
        char *b64str = NULL;
        size_t blen = 0;

        rv = Curl_base64_encode((const char *)echConfigs, echConfigsLen,
                                &b64str, &blen);
        if(!rv && b64str)
          infof(data, "ECH: (not yet) retry_configs %s", b64str);
        free(b64str);
      }
    }
#endif
    else if(backend->io_result == CURLE_AGAIN) {
      return CURLE_OK;
    }
    else {
      char error_buffer[256];
      failf(data, "SSL_connect failed with error %d: %s", detail,
            wolfssl_strerror((unsigned long)detail, error_buffer,
                             sizeof(error_buffer)));
      return CURLE_SSL_CONNECT_ERROR;
    }
  }

  if(pinnedpubkey) {
#ifdef KEEP_PEER_CERT
    WOLFSSL_X509 *x509;
    const char *x509_der;
    int x509_der_len;
    struct Curl_X509certificate x509_parsed;
    struct Curl_asn1Element *pubkey;
    CURLcode result;

    x509 = wolfSSL_get_peer_certificate(backend->handle);
    if(!x509) {
      failf(data, "SSL: failed retrieving server certificate");
      return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
    }

    x509_der = (const char *)wolfSSL_X509_get_der(x509, &x509_der_len);
    if(!x509_der) {
      failf(data, "SSL: failed retrieving ASN.1 server certificate");
      return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
    }

    memset(&x509_parsed, 0, sizeof(x509_parsed));
    if(Curl_parseX509(&x509_parsed, x509_der, x509_der + x509_der_len))
      return CURLE_SSL_PINNEDPUBKEYNOTMATCH;

    pubkey = &x509_parsed.subjectPublicKeyInfo;
    if(!pubkey->header || pubkey->end <= pubkey->header) {
      failf(data, "SSL: failed retrieving public key from server certificate");
      return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
    }

    result = Curl_pin_peer_pubkey(data,
                                  pinnedpubkey,
                                  (const unsigned char *)pubkey->header,
                                  (size_t)(pubkey->end - pubkey->header));
    wolfSSL_FreeX509(x509);
    if(result) {
      failf(data, "SSL: public key does not match pinned public key");
      return result;
    }
#else
    failf(data, "Library lacks pinning support built-in");
    return CURLE_NOT_BUILT_IN;
#endif
  }

#ifdef HAVE_ALPN
  if(connssl->alpn) {
    int rc;
    char *protocol = NULL;
    unsigned short protocol_len = 0;

    rc = wolfSSL_ALPN_GetProtocol(backend->handle, &protocol, &protocol_len);

    if(rc == WOLFSSL_SUCCESS) {
      Curl_alpn_set_negotiated(cf, data, connssl,
                               (const unsigned char *)protocol, protocol_len);
    }
    else if(rc == WOLFSSL_ALPN_NOT_FOUND)
      Curl_alpn_set_negotiated(cf, data, connssl, NULL, 0);
    else {
      failf(data, "ALPN, failure getting protocol, error %d", rc);
      return CURLE_SSL_CONNECT_ERROR;
    }
  }
#endif /* HAVE_ALPN */

  connssl->connecting_state = ssl_connect_3;
#if (LIBWOLFSSL_VERSION_HEX >= 0x03009010)
  infof(data, "SSL connection using %s / %s",
        wolfSSL_get_version(backend->handle),
        wolfSSL_get_cipher_name(backend->handle));
#else
  infof(data, "SSL connected");
#endif

  return CURLE_OK;
}

static ssize_t wolfssl_send(struct Curl_cfilter *cf,
                            struct Curl_easy *data,
                            const void *mem,
                            size_t len,
                            CURLcode *curlcode)
{
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;
  int memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
  int rc;

  DEBUGASSERT(backend);

  wolfSSL_ERR_clear_error();

  rc = wolfSSL_write(backend->handle, mem, memlen);
  if(rc <= 0) {
    int err = wolfSSL_get_error(backend->handle, rc);

    switch(err) {
    case WOLFSSL_ERROR_WANT_READ:
    case WOLFSSL_ERROR_WANT_WRITE:
      /* there is data pending, re-invoke SSL_write() */
      CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> AGAIN", len);
      *curlcode = CURLE_AGAIN;
      return -1;
    default:
      if(backend->io_result == CURLE_AGAIN) {
        CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> AGAIN", len);
        *curlcode = CURLE_AGAIN;
        return -1;
      }
      CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> %d, %d", len, rc, err);
      {
        char error_buffer[256];
        failf(data, "SSL write: %s, errno %d",
              wolfssl_strerror((unsigned long)err, error_buffer,
                               sizeof(error_buffer)),
              SOCKERRNO);
      }
      *curlcode = CURLE_SEND_ERROR;
      return -1;
    }
  }
  CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> %d", len, rc);
  return rc;
}

static CURLcode wolfssl_shutdown(struct Curl_cfilter *cf,
                                 struct Curl_easy *data,
                                 bool send_shutdown, bool *done)
{
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *wctx = (struct wolfssl_ctx *)connssl->backend;
  CURLcode result = CURLE_OK;
  char buf[1024];
  char error_buffer[256];
  int nread = -1, err;
  size_t i;
  int detail;

  DEBUGASSERT(wctx);
  if(!wctx->handle || cf->shutdown) {
    *done = TRUE;
    goto out;
  }

  wctx->shutting_down = TRUE;
  connssl->io_need = CURL_SSL_IO_NEED_NONE;
  *done = FALSE;
  if(!(wolfSSL_get_shutdown(wctx->handle) & WOLFSSL_SENT_SHUTDOWN)) {
    /* We have not started the shutdown from our side yet. Check
     * if the server already sent us one. */
    wolfSSL_ERR_clear_error();
    nread = wolfSSL_read(wctx->handle, buf, (int)sizeof(buf));
    err = wolfSSL_get_error(wctx->handle, nread);
    CURL_TRC_CF(data, cf, "wolfSSL_read, nread=%d, err=%d", nread, err);
    if(!nread && err == WOLFSSL_ERROR_ZERO_RETURN) {
      bool input_pending;
      /* Yes, it did. */
      if(!send_shutdown) {
        CURL_TRC_CF(data, cf, "SSL shutdown received, not sending");
        *done = TRUE;
        goto out;
      }
      else if(!cf->next->cft->is_alive(cf->next, data, &input_pending)) {
        /* Server closed the connection after its closy notify. It
         * seems not interested to see our close notify, so do not
         * send it. We are done. */
        CURL_TRC_CF(data, cf, "peer closed connection");
        connssl->peer_closed = TRUE;
        *done = TRUE;
        goto out;
      }
    }
  }

  /* SSL should now have started the shutdown from our side. Since it
   * was not complete, we are lacking the close notify from the server. */
  if(send_shutdown) {
    wolfSSL_ERR_clear_error();
    if(wolfSSL_shutdown(wctx->handle) == 1) {
      CURL_TRC_CF(data, cf, "SSL shutdown finished");
      *done = TRUE;
      goto out;
    }
    if(WOLFSSL_ERROR_WANT_WRITE == wolfSSL_get_error(wctx->handle, nread)) {
      CURL_TRC_CF(data, cf, "SSL shutdown still wants to send");
      connssl->io_need = CURL_SSL_IO_NEED_SEND;
      goto out;
    }
    /* Having sent the close notify, we use wolfSSL_read() to get the
     * missing close notify from the server. */
  }

  for(i = 0; i < 10; ++i) {
    wolfSSL_ERR_clear_error();
    nread = wolfSSL_read(wctx->handle, buf, (int)sizeof(buf));
    if(nread <= 0)
      break;
  }
  err = wolfSSL_get_error(wctx->handle, nread);
  switch(err) {
  case WOLFSSL_ERROR_ZERO_RETURN: /* no more data */
    CURL_TRC_CF(data, cf, "SSL shutdown received");
    *done = TRUE;
    break;
  case WOLFSSL_ERROR_NONE: /* just did not get anything */
  case WOLFSSL_ERROR_WANT_READ:
    /* SSL has send its notify and now wants to read the reply
     * from the server. We are not really interested in that. */
    CURL_TRC_CF(data, cf, "SSL shutdown sent, want receive");
    connssl->io_need = CURL_SSL_IO_NEED_RECV;
    break;
  case WOLFSSL_ERROR_WANT_WRITE:
    CURL_TRC_CF(data, cf, "SSL shutdown send blocked");
    connssl->io_need = CURL_SSL_IO_NEED_SEND;
    break;
  default:
    detail = wolfSSL_get_error(wctx->handle, err);
    CURL_TRC_CF(data, cf, "SSL shutdown, error: '%s'(%d)",
                wolfssl_strerror((unsigned long)err, error_buffer,
                                 sizeof(error_buffer)),
                detail);
    result = CURLE_RECV_ERROR;
    break;
  }

out:
  cf->shutdown = (result || *done);
  return result;
}

static void wolfssl_close(struct Curl_cfilter *cf, struct Curl_easy *data)
{
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;

  (void) data;

  DEBUGASSERT(backend);

  if(backend->handle) {
    wolfSSL_free(backend->handle);
    backend->handle = NULL;
  }
  if(backend->ctx) {
    wolfSSL_CTX_free(backend->ctx);
    backend->ctx = NULL;
  }
}

static ssize_t wolfssl_recv(struct Curl_cfilter *cf,
                            struct Curl_easy *data,
                            char *buf, size_t blen,
                            CURLcode *curlcode)
{
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;
  int buffsize = (blen > (size_t)INT_MAX) ? INT_MAX : (int)blen;
  int nread;

  DEBUGASSERT(backend);

  wolfSSL_ERR_clear_error();
  *curlcode = CURLE_OK;

  nread = wolfSSL_read(backend->handle, buf, buffsize);

  if(nread <= 0) {
    int err = wolfSSL_get_error(backend->handle, nread);

    switch(err) {
    case WOLFSSL_ERROR_ZERO_RETURN: /* no more data */
      CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> CLOSED", blen);
      *curlcode = CURLE_OK;
      return 0;
    case WOLFSSL_ERROR_NONE:
    case WOLFSSL_ERROR_WANT_READ:
    case WOLFSSL_ERROR_WANT_WRITE:
      if(!backend->io_result && connssl->peer_closed) {
        CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> CLOSED", blen);
        *curlcode = CURLE_OK;
        return 0;
      }
      /* there is data pending, re-invoke wolfSSL_read() */
      CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> AGAIN", blen);
      *curlcode = CURLE_AGAIN;
      return -1;
    default:
      if(backend->io_result == CURLE_AGAIN) {
        CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> AGAIN", blen);
        *curlcode = CURLE_AGAIN;
        return -1;
      }
      else if(!backend->io_result && connssl->peer_closed) {
        CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> CLOSED", blen);
        *curlcode = CURLE_OK;
        return 0;
      }
      else {
        char error_buffer[256];
        failf(data, "SSL read: %s, errno %d",
              wolfssl_strerror((unsigned long)err, error_buffer,
                               sizeof(error_buffer)),
              SOCKERRNO);
      }
      *curlcode = CURLE_RECV_ERROR;
      return -1;
    }
  }
  CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> %d", blen, nread);
  return nread;
}


static size_t wolfssl_version(char *buffer, size_t size)
{
#if LIBWOLFSSL_VERSION_HEX >= 0x03006000
  return msnprintf(buffer, size, "wolfSSL/%s", wolfSSL_lib_version());
#elif defined(WOLFSSL_VERSION)
  return msnprintf(buffer, size, "wolfSSL/%s", WOLFSSL_VERSION);
#endif
}


static int wolfssl_init(void)
{
  int ret;

#ifdef OPENSSL_EXTRA
  Curl_tls_keylog_open();
#endif
  ret = (wolfSSL_Init() == WOLFSSL_SUCCESS);
  wolfssl_bio_cf_init_methods();
  return ret;
}


static void wolfssl_cleanup(void)
{
  wolfssl_bio_cf_free_methods();
  wolfSSL_Cleanup();
#ifdef OPENSSL_EXTRA
  Curl_tls_keylog_close();
#endif
}


static bool wolfssl_data_pending(struct Curl_cfilter *cf,
                                 const struct Curl_easy *data)
{
  struct ssl_connect_data *ctx = cf->ctx;
  struct wolfssl_ctx *backend;

  (void)data;
  DEBUGASSERT(ctx && ctx->backend);

  backend = (struct wolfssl_ctx *)ctx->backend;
  if(backend->handle)   /* SSL is in use */
    return wolfSSL_pending(backend->handle);
  else
    return FALSE;
}

static CURLcode
wolfssl_connect_common(struct Curl_cfilter *cf,
                       struct Curl_easy *data,
                       bool nonblocking,
                       bool *done)
{
  CURLcode result;
  struct ssl_connect_data *connssl = cf->ctx;
  curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data);

  /* check if the connection has already been established */
  if(ssl_connection_complete == connssl->state) {
    *done = TRUE;
    return CURLE_OK;
  }

  if(ssl_connect_1 == connssl->connecting_state) {
    /* Find out how much more time we are allowed */
    const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);

    if(timeout_ms < 0) {
      /* no need to continue if time already is up */
      failf(data, "SSL connection timeout");
      return CURLE_OPERATION_TIMEDOUT;
    }

    result = wolfssl_connect_step1(cf, data);
    if(result)
      return result;
  }

  while(ssl_connect_2 == connssl->connecting_state) {

    /* check allowed time left */
    const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);

    if(timeout_ms < 0) {
      /* no need to continue if time already is up */
      failf(data, "SSL connection timeout");
      return CURLE_OPERATION_TIMEDOUT;
    }

    /* if ssl is expecting something, check if it is available. */
    if(connssl->io_need) {
      curl_socket_t writefd = (connssl->io_need & CURL_SSL_IO_NEED_SEND) ?
        sockfd : CURL_SOCKET_BAD;
      curl_socket_t readfd = (connssl->io_need & CURL_SSL_IO_NEED_RECV) ?
        sockfd : CURL_SOCKET_BAD;
      int what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
                                   nonblocking ? 0 : timeout_ms);
      if(what < 0) {
        /* fatal error */
        failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
        return CURLE_SSL_CONNECT_ERROR;
      }
      else if(0 == what) {
        if(nonblocking) {
          *done = FALSE;
          return CURLE_OK;
        }
        else {
          /* timeout */
          failf(data, "SSL connection timeout");
          return CURLE_OPERATION_TIMEDOUT;
        }
      }
      /* socket is readable or writable */
    }

    /* Run transaction, and return to the caller if it failed or if
     * this connection is part of a multi handle and this loop would
     * execute again. This permits the owner of a multi handle to
     * abort a connection attempt before step2 has completed while
     * ensuring that a client using select() or epoll() will always
     * have a valid fdset to wait on.
     */
    result = wolfssl_connect_step2(cf, data);
    if(result || (nonblocking && (ssl_connect_2 == connssl->connecting_state)))
      return result;
  } /* repeat step2 until all transactions are done. */

  if(ssl_connect_3 == connssl->connecting_state) {
    /* In other backends, this is where we verify the certificate, but
     * wolfSSL already does that as part of the handshake. */
    connssl->connecting_state = ssl_connect_done;
  }

  if(ssl_connect_done == connssl->connecting_state) {
    connssl->state = ssl_connection_complete;
    *done = TRUE;
  }
  else
    *done = FALSE;

  /* Reset our connect state machine */
  connssl->connecting_state = ssl_connect_1;

  return CURLE_OK;
}


static CURLcode wolfssl_connect_nonblocking(struct Curl_cfilter *cf,
                                            struct Curl_easy *data,
                                            bool *done)
{
  return wolfssl_connect_common(cf, data, TRUE, done);
}


static CURLcode wolfssl_connect(struct Curl_cfilter *cf,
                                struct Curl_easy *data)
{
  CURLcode result;
  bool done = FALSE;

  result = wolfssl_connect_common(cf, data, FALSE, &done);
  if(result)
    return result;

  DEBUGASSERT(done);

  return CURLE_OK;
}

static CURLcode wolfssl_random(struct Curl_easy *data,
                               unsigned char *entropy, size_t length)
{
  WC_RNG rng;
  (void)data;
  if(wc_InitRng(&rng))
    return CURLE_FAILED_INIT;
  if(length > UINT_MAX)
    return CURLE_FAILED_INIT;
  if(wc_RNG_GenerateBlock(&rng, entropy, (unsigned)length))
    return CURLE_FAILED_INIT;
  if(wc_FreeRng(&rng))
    return CURLE_FAILED_INIT;
  return CURLE_OK;
}

static CURLcode wolfssl_sha256sum(const unsigned char *tmp, /* input */
                                  size_t tmplen,
                                  unsigned char *sha256sum /* output */,
                                  size_t unused)
{
  wc_Sha256 SHA256pw;
  (void)unused;
  if(wc_InitSha256(&SHA256pw))
    return CURLE_FAILED_INIT;
  wc_Sha256Update(&SHA256pw, tmp, (word32)tmplen);
  wc_Sha256Final(&SHA256pw, sha256sum);
  return CURLE_OK;
}

static void *wolfssl_get_internals(struct ssl_connect_data *connssl,
                                   CURLINFO info UNUSED_PARAM)
{
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;
  (void)info;
  DEBUGASSERT(backend);
  return backend->handle;
}

const struct Curl_ssl Curl_ssl_wolfssl = {
  { CURLSSLBACKEND_WOLFSSL, "wolfssl" }, /* info */

#ifdef KEEP_PEER_CERT
  SSLSUPP_PINNEDPUBKEY |
#endif
#ifdef USE_BIO_CHAIN
  SSLSUPP_HTTPS_PROXY |
#endif
  SSLSUPP_CA_PATH |
  SSLSUPP_CAINFO_BLOB |
#ifdef USE_ECH
  SSLSUPP_ECH |
#endif
  SSLSUPP_SSL_CTX |
#ifdef WOLFSSL_TLS13
  SSLSUPP_TLS13_CIPHERSUITES |
#endif
  SSLSUPP_CA_CACHE |
  SSLSUPP_CIPHER_LIST,

  sizeof(struct wolfssl_ctx),

  wolfssl_init,                    /* init */
  wolfssl_cleanup,                 /* cleanup */
  wolfssl_version,                 /* version */
  Curl_none_check_cxn,             /* check_cxn */
  wolfssl_shutdown,                /* shutdown */
  wolfssl_data_pending,            /* data_pending */
  wolfssl_random,                  /* random */
  Curl_none_cert_status_request,   /* cert_status_request */
  wolfssl_connect,                 /* connect */
  wolfssl_connect_nonblocking,     /* connect_nonblocking */
  Curl_ssl_adjust_pollset,         /* adjust_pollset */
  wolfssl_get_internals,           /* get_internals */
  wolfssl_close,                   /* close_one */
  Curl_none_close_all,             /* close_all */
  Curl_none_set_engine,            /* set_engine */
  Curl_none_set_engine_default,    /* set_engine_default */
  Curl_none_engines_list,          /* engines_list */
  Curl_none_false_start,           /* false_start */
  wolfssl_sha256sum,               /* sha256sum */
  NULL,                            /* associate_connection */
  NULL,                            /* disassociate_connection */
  wolfssl_recv,                    /* recv decrypted data */
  wolfssl_send,                    /* send data to encrypt */
  NULL,                            /* get_channel_binding */
};

#endif