summaryrefslogtreecommitdiffstats
path: root/src/network/ssl/qtlsbackend.cpp
blob: 2d01bdaa3c91e6b4b890e0b3b2bb948671392a55 (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
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qtlsbackend_p.h"

#if QT_CONFIG(ssl)
#include "qsslpresharedkeyauthenticator_p.h"
#include "qsslpresharedkeyauthenticator.h"
#include "qsslsocket_p.h"
#include "qsslcipher_p.h"
#include "qsslkey_p.h"
#include "qsslkey.h"
#endif

#include "qssl_p.h"

#include <QtCore/private/qfactoryloader_p.h>

#include "QtCore/qapplicationstatic.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmutex.h>

#include <algorithm>
#include <vector>

QT_BEGIN_NAMESPACE

using namespace Qt::StringLiterals;

Q_APPLICATION_STATIC(QFactoryLoader, loader, QTlsBackend_iid,
                     QStringLiteral("/tls"))

namespace {

class BackendCollection
{
public:
    void addBackend(QTlsBackend *backend)
    {
        Q_ASSERT(backend);
        Q_ASSERT(std::find(backends.begin(), backends.end(), backend) == backends.end());
        const QMutexLocker locker(&collectionMutex);
        backends.push_back(backend);
    }

    void removeBackend(QTlsBackend *backend)
    {
        Q_ASSERT(backend);
        const QMutexLocker locker(&collectionMutex);
        const auto it = std::find(backends.begin(), backends.end(), backend);
        Q_ASSERT(it != backends.end());
        backends.erase(it);
    }

    bool tryPopulateCollection()
    {
        if (!loader())
            return false;

        Q_CONSTINIT static QBasicMutex mutex;
        const QMutexLocker locker(&mutex);
        if (backends.size())
            return true;

#if QT_CONFIG(library)
        loader->update();
#endif
        int index = 0;
        while (loader->instance(index))
            ++index;

        return true;
    }

    QList<QString> backendNames()
    {
        QList<QString> names;
        if (!tryPopulateCollection())
            return names;

        const QMutexLocker locker(&collectionMutex);
        if (!backends.size())
            return names;

        names.reserve(backends.size());
        for (const auto *backend : backends) {
            if (backend->isValid())
                names.append(backend->backendName());
        }

        return names;
    }

    QTlsBackend *backend(const QString &name)
    {
        if (!tryPopulateCollection())
            return nullptr;

        const QMutexLocker locker(&collectionMutex);
        const auto it = std::find_if(backends.begin(), backends.end(),
                                     [&name](const auto *fct) {return fct->backendName() == name;});

        return it == backends.end()  ? nullptr : *it;
    }

private:
    std::vector<QTlsBackend *> backends;
    QMutex collectionMutex;
};

} // Unnamed namespace

Q_GLOBAL_STATIC(BackendCollection, backends);

/*!
    \class QTlsBackend
    \internal (Network-private)
    \brief QTlsBackend is a factory class, providing implementations
    for the QSsl classes.

    The purpose of QTlsBackend is to enable and simplify the addition
    of new TLS backends to be used by QSslSocket and related classes.
    Starting from Qt 6.1, these backends have plugin-based design (and
    thus can co-exist simultaneously, unlike pre 6.1 times), although
    any given run of a program can only use one of them.

    Inheriting from QTlsBackend and creating an object of such
    a class adds a new backend into the list of available TLS backends.

    A new backend must provide a list of classes, features and protocols
    it supports, and override the corresponding virtual functions that
    create backend-specific implementations for these QSsl-classes.

    The base abstract class - QTlsBackend - provides, where possible,
    default implementations of its virtual member functions. These
    default implementations can be overridden by a derived backend
    class, if needed.

    QTlsBackend also provides some auxiliary functions that a derived
    backend class can use to interact with the internals of network-private classes.

    \sa QSslSocket::availableBackends(), supportedFeatures(), supportedProtocols(), implementedClasses()
*/

/*!
    \fn QString QTlsBackend::backendName() const
    \internal
    Returns the name of this backend. The name will be reported by QSslSocket::availableBackends().
    Example of backend names: "openssl", "schannel", "securetransport".

    \sa QSslSocket::availableBackends(), isValid()
*/

const QString QTlsBackend::builtinBackendNames[] = {
    QStringLiteral("schannel"),
    QStringLiteral("securetransport"),
    QStringLiteral("openssl"),
    QStringLiteral("cert-only")
};

/*!
    \internal
    The default constructor, adds a new backend to the list of available backends.

    \sa ~QTlsBackend(), availableBackendNames(), QSslSocket::availableBackends()
*/
QTlsBackend::QTlsBackend()
{
    if (backends())
        backends->addBackend(this);

    if (QCoreApplication::instance()) {
        connect(QCoreApplication::instance(), &QCoreApplication::destroyed, this, [this] {
            delete this;
        });
    }
}

/*!
    \internal
    Removes this backend from the list of available backends.

    \sa QTlsBackend(), availableBackendNames(), QSslSocket::availableBackends()
*/
QTlsBackend::~QTlsBackend()
{
    if (backends())
        backends->removeBackend(this);
}

/*!
    \internal
    Returns \c true if this backend was initialised successfully. The default implementation
    always returns \c true.

    \note This function must be overridden if a particular backend has a non-trivial initialization
    that can fail. If reimplemented, returning \c false will exclude this backend from the list of
    backends, reported as available by QSslSocket.

    \sa QSslSocket::availableBackends()
*/

bool QTlsBackend::isValid() const
{
    return true;
}

/*!
    \internal
    Returns an implementations-specific integer value, representing the TLS library's
    version, that is currently used by this backend (i.e. runtime library version).
    The default implementation returns 0.

    \sa tlsLibraryBuildVersionNumber()
*/
long QTlsBackend::tlsLibraryVersionNumber() const
{
    return 0;
}

/*!
    \internal
    Returns an implementation-specific string, representing the TLS library's version,
    that is currently used by this backend (i.e. runtime library version). The default
    implementation returns an empty string.

    \sa tlsLibraryBuildVersionString()
*/

QString QTlsBackend::tlsLibraryVersionString() const
{
    return {};
}

/*!
    \internal
    Returns an implementation-specific integer value, representing the TLS library's
    version that this backend was built against (i.e. compile-time library version).
    The default implementation returns 0.

    \sa tlsLibraryVersionNumber()
*/

long QTlsBackend::tlsLibraryBuildVersionNumber() const
{
    return 0;
}

/*!
    \internal
    Returns an implementation-specific string, representing the TLS library's version
    that this backend was built against (i.e. compile-time version). The default
    implementation returns an empty string.

    \sa tlsLibraryVersionString()
*/
QString QTlsBackend::tlsLibraryBuildVersionString() const
{
    return {};
}

/*!
    \internal
    QSslSocket and related classes call this function to ensure that backend's internal
    resources - e.g. CA certificates, or ciphersuites - were properly initialized.
*/
void QTlsBackend::ensureInitialized() const
{
}

#define REPORT_MISSING_SUPPORT(message) \
    qCWarning(lcSsl) << "The backend" << backendName() << message

/*!
    \internal
    If QSsl::ImplementedClass::Key is present in this backend's implementedClasses(),
    the backend must reimplement this method to return a dynamically-allocated instance
    of an implementation-specific type, inheriting from the class QTlsPrivate::TlsKey.
    The default implementation of this function returns \nullptr.

    \sa QSslKey, implementedClasses(), QTlsPrivate::TlsKey
*/
QTlsPrivate::TlsKey *QTlsBackend::createKey() const
{
    REPORT_MISSING_SUPPORT("does not support QSslKey");
    return nullptr;
}

/*!
    \internal
    If QSsl::ImplementedClass::Certificate is present in this backend's implementedClasses(),
    the backend must reimplement this method to return a dynamically-allocated instance of an
    implementation-specific type, inheriting from the class QTlsPrivate::X509Certificate.
    The default implementation of this function returns \nullptr.

    \sa QSslCertificate, QTlsPrivate::X509Certificate, implementedClasses()
*/
QTlsPrivate::X509Certificate *QTlsBackend::createCertificate() const
{
    REPORT_MISSING_SUPPORT("does not support QSslCertificate");
    return nullptr;
}

/*!
    \internal
    This function returns a list of system CA certificates - e.g. certificates, loaded
    from a system store, if available. This function allows implementation of the class
    QSslConfiguration. The default implementation of this function returns an empty list.

    \sa QSslCertificate, QSslConfiguration
*/
QList<QSslCertificate> QTlsBackend::systemCaCertificates() const
{
    REPORT_MISSING_SUPPORT("does not provide system CA certificates");
    return {};
}

/*!
    \internal
    If QSsl::ImplementedClass::Socket is present in this backend's implementedClasses(),
    the backend must reimplement this method to return a dynamically-allocated instance of an
    implementation-specific type, inheriting from the class QTlsPrivate::TlsCryptograph.
    The default implementation of this function returns \nullptr.

    \sa QSslSocket, QTlsPrivate::TlsCryptograph, implementedClasses()
*/
QTlsPrivate::TlsCryptograph *QTlsBackend::createTlsCryptograph() const
{
    REPORT_MISSING_SUPPORT("does not support QSslSocket");
    return nullptr;
}

/*!
    \internal
    If QSsl::ImplementedClass::Dtls is present in this backend's implementedClasses(),
    the backend must reimplement this method to return a dynamically-allocated instance of an
    implementation-specific type, inheriting from the class QTlsPrivate::DtlsCryptograph.
    The default implementation of this function returns \nullptr.

    \sa QDtls, QTlsPrivate::DtlsCryptograph, implementedClasses()
*/
QTlsPrivate::DtlsCryptograph *QTlsBackend::createDtlsCryptograph(QDtls *qObject, int mode) const
{
    Q_UNUSED(qObject);
    Q_UNUSED(mode);
    REPORT_MISSING_SUPPORT("does not support QDtls");
    return nullptr;
}

/*!
    \internal
    If QSsl::ImplementedClass::DtlsCookie is present in this backend's implementedClasses(),
    the backend must reimplement this method to return a dynamically-allocated instance of an
    implementation-specific type, inheriting from the class QTlsPrivate::DtlsCookieVerifier. The
    default implementation returns \nullptr.

    \sa QDtlsClientVerifier, QTlsPrivate::DtlsCookieVerifier, implementedClasses()
*/
QTlsPrivate::DtlsCookieVerifier *QTlsBackend::createDtlsCookieVerifier() const
{
    REPORT_MISSING_SUPPORT("does not support DTLS cookies");
    return nullptr;
}

/*!
    \internal
    If QSsl::SupportedFeature::CertificateVerification is present in this backend's
    supportedFeatures(), the backend must reimplement this method to return a pointer
    to a function, that checks a certificate (or a chain of certificates) against available
    CA certificates. The default implementation returns \nullptr.

    \sa supportedFeatures(), QSslCertificate
*/

QTlsPrivate::X509ChainVerifyPtr QTlsBackend::X509Verifier() const
{
    REPORT_MISSING_SUPPORT("does not support (manual) certificate verification");
    return nullptr;
}

/*!
    \internal
    Returns a pointer to function, that reads certificates in PEM format. The
    default implementation returns \nullptr.

    \sa QSslCertificate
*/
QTlsPrivate::X509PemReaderPtr QTlsBackend::X509PemReader() const
{
    REPORT_MISSING_SUPPORT("cannot read PEM format");
    return nullptr;
}

/*!
    \internal
    Returns a pointer to function, that can read certificates in DER format.
    The default implementation returns \nullptr.

    \sa QSslCertificate
*/
QTlsPrivate::X509DerReaderPtr QTlsBackend::X509DerReader() const
{
    REPORT_MISSING_SUPPORT("cannot read DER format");
    return nullptr;
}

/*!
    \internal
    Returns a pointer to function, that can read certificates in PKCS 12 format.
    The default implementation returns \nullptr.

    \sa QSslCertificate
*/
QTlsPrivate::X509Pkcs12ReaderPtr QTlsBackend::X509Pkcs12Reader() const
{
    REPORT_MISSING_SUPPORT("cannot read PKCS12 format");
    return nullptr;
}

/*!
    \internal
    If QSsl::ImplementedClass::EllipticCurve is present in this backend's implementedClasses(),
    and the backend provides information about supported curves, it must reimplement this
    method to return a list of unique identifiers of the supported elliptic curves. The default
    implementation returns an empty list.

    \note The meaning of a curve identifier is implementation-specific.

    \sa implemenedClasses(), QSslEllipticCurve
*/
QList<int> QTlsBackend::ellipticCurvesIds() const
{
    REPORT_MISSING_SUPPORT("does not support QSslEllipticCurve");
    return {};
}

/*!
    \internal
    If this backend provides information about available elliptic curves, this
    function should return a unique integer identifier for a curve named \a name,
    which is a conventional short name for the curve. The default implementation
    returns 0.

    \note The meaning of a curve identifier is implementation-specific.

    \sa QSslEllipticCurve::shortName()
*/
int QTlsBackend::curveIdFromShortName(const QString &name) const
{
    Q_UNUSED(name);
    REPORT_MISSING_SUPPORT("does not support QSslEllipticCurve");
    return 0;
}

/*!
    \internal
    If this backend provides information about available elliptic curves, this
    function should return a unique integer identifier for a curve named \a name,
    which is a conventional long name for the curve. The default implementation
    returns 0.

    \note The meaning of a curve identifier is implementation-specific.

    \sa QSslElliptiCurve::longName()
*/
int QTlsBackend::curveIdFromLongName(const QString &name) const
{
    Q_UNUSED(name);
    REPORT_MISSING_SUPPORT("does not support QSslEllipticCurve");
    return 0;
}

/*!
    \internal
    If this backend provides information about available elliptic curves,
    this function should return a conventional short name for a curve identified
    by \a cid. The default implementation returns an empty string.

    \note The meaning of a curve identifier is implementation-specific.

    \sa ellipticCurvesIds(), QSslEllipticCurve::shortName()
*/
QString QTlsBackend::shortNameForId(int cid) const
{
    Q_UNUSED(cid);
    REPORT_MISSING_SUPPORT("does not support QSslEllipticCurve");
    return {};
}

/*!
    \internal
    If this backend provides information about available elliptic curves,
    this function should return a conventional long name for a curve identified
    by \a cid. The default implementation returns an empty string.

    \note The meaning of a curve identifier is implementation-specific.

    \sa ellipticCurvesIds(), QSslEllipticCurve::shortName()
*/
QString QTlsBackend::longNameForId(int cid) const
{
    Q_UNUSED(cid);
    REPORT_MISSING_SUPPORT("does not support QSslEllipticCurve");
    return {};
}

/*!
    \internal
    Returns true if the elliptic curve identified by \a cid is one of the named
    curves, that can be used in the key exchange when using an elliptic curve
    cipher with TLS; false otherwise. The default implementation returns false.

    \note The meaning of curve identifier is implementation-specific.
*/
bool QTlsBackend::isTlsNamedCurve(int cid) const
{
    Q_UNUSED(cid);
    REPORT_MISSING_SUPPORT("does not support QSslEllipticCurve");
    return false;
}

/*!
    \internal
    If this backend supports the class QSslDiffieHellmanParameters, this function is
    needed for construction of a QSslDiffieHellmanParameters from DER encoded data.
    This function is expected to return a value that matches an enumerator in
    QSslDiffieHellmanParameters::Error enumeration. The default implementation of this
    function returns 0 (equals to QSslDiffieHellmanParameters::NoError).

    \sa QSslDiffieHellmanParameters, implementedClasses()
*/
int QTlsBackend::dhParametersFromDer(const QByteArray &derData, QByteArray *data) const
{
    Q_UNUSED(derData);
    Q_UNUSED(data);
    REPORT_MISSING_SUPPORT("does not support QSslDiffieHellmanParameters in DER format");
    return {};
}

/*!
    \internal
    If this backend supports the class QSslDiffieHellmanParameters, this function is
    is needed for construction of a QSslDiffieHellmanParameters from PEM encoded data.
    This function is expected to return a value that matches an enumerator in
    QSslDiffieHellmanParameters::Error enumeration. The default implementation of this
    function returns 0 (equals to QSslDiffieHellmanParameters::NoError).

    \sa QSslDiffieHellmanParameters, implementedClasses()
*/
int QTlsBackend::dhParametersFromPem(const QByteArray &pemData, QByteArray *data) const
{
    Q_UNUSED(pemData);
    Q_UNUSED(data);
    REPORT_MISSING_SUPPORT("does not support QSslDiffieHellmanParameters in PEM format");
    return {};
}

/*!
    \internal
    Returns a list of names of available backends.

    \note This list contains only properly initialized backends.

    \sa QTlsBackend(), isValid()
*/
QList<QString> QTlsBackend::availableBackendNames()
{
    if (!backends())
        return {};

    return backends->backendNames();
}

/*!
    \internal
    Returns the name of the backend that QSslSocket() would use by default. If no
    backend was found, the function returns an empty string.
*/
QString QTlsBackend::defaultBackendName()
{
    // We prefer OpenSSL as default:
    const auto names = availableBackendNames();
    auto name = builtinBackendNames[nameIndexOpenSSL];
    if (names.contains(name))
        return name;
    name = builtinBackendNames[nameIndexSchannel];
    if (names.contains(name))
        return name;
    name = builtinBackendNames[nameIndexSecureTransport];
    if (names.contains(name))
        return name;

    const auto pos = std::find_if(names.begin(), names.end(), [](const auto &name) {
        return name != builtinBackendNames[nameIndexCertOnly];
    });

    if (pos != names.end())
        return *pos;

    if (names.size())
        return names[0];

    return {};
}

/*!
    \internal
    Returns a backend named \a backendName, if it exists.
    Otherwise, it returns \nullptr.

    \sa backendName(), QSslSocket::availableBackends()
*/
QTlsBackend *QTlsBackend::findBackend(const QString &backendName)
{
    if (!backends())
        return {};

    if (auto *fct = backends->backend(backendName))
        return fct;

    qCWarning(lcSsl) << "Cannot create unknown backend named" << backendName;
    return nullptr;
}

/*!
    \internal
    Returns the backend that QSslSocket is using. If Qt was built without TLS support,
    this function returns a minimal backend that only supports QSslCertificate.

    \sa defaultBackend()
*/
QTlsBackend *QTlsBackend::activeOrAnyBackend()
{
#if QT_CONFIG(ssl)
    return QSslSocketPrivate::tlsBackendInUse();
#else
    return findBackend(defaultBackendName());
#endif // QT_CONFIG(ssl)
}

/*!
    \internal
    Returns a list of TLS and DTLS protocol versions, that a backend named
    \a backendName supports.

    \note This list is supposed to also include range-based versions, which
    allows negotiation of protocols during the handshake, so that these versions
    can be used when configuring QSslSocket (e.g. QSsl::TlsV1_2OrLater).

    \sa QSsl::SslProtocol
*/
QList<QSsl::SslProtocol> QTlsBackend::supportedProtocols(const QString &backendName)
{
    if (!backends())
        return {};

    if (const auto *fct = backends->backend(backendName))
        return fct->supportedProtocols();

    return {};
}

/*!
    \internal
    Returns a list of features that a backend named \a backendName supports. E.g.
    a backend may support PSK (pre-shared keys, defined as QSsl::SupportedFeature::Psk)
    or ALPN (application layer protocol negotiation, identified by
    QSsl::SupportedFeature::ClientSideAlpn or QSsl::SupportedFeature::ServerSideAlpn).

    \sa QSsl::SupportedFeature
*/
QList<QSsl::SupportedFeature> QTlsBackend::supportedFeatures(const QString &backendName)
{
    if (!backends())
        return {};

    if (const auto *fct = backends->backend(backendName))
        return fct->supportedFeatures();

    return {};
}

/*!
    \internal
    Returns a list of classes that a backend named \a backendName supports. E.g. a backend
    may implement QSslSocket (QSsl::ImplementedClass::Socket), and QDtls
    (QSsl::ImplementedClass::Dtls).

    \sa QSsl::ImplementedClass
*/
QList<QSsl::ImplementedClass> QTlsBackend::implementedClasses(const QString &backendName)
{
    if (!backends())
        return {};

    if (const auto *fct = backends->backend(backendName))
        return fct->implementedClasses();

    return {};
}

/*!
    \internal
    Auxiliary function. Initializes \a key to use \a keyBackend.
*/
void QTlsBackend::resetBackend(QSslKey &key, QTlsPrivate::TlsKey *keyBackend)
{
#if QT_CONFIG(ssl)
    key.d->backend.reset(keyBackend);
#else
    Q_UNUSED(key);
    Q_UNUSED(keyBackend);
#endif // QT_CONFIG(ssl)
}

/*!
    \internal
    Auxiliary function. Initializes client-side \a auth using the \a hint, \a hintLength,
    \a maxIdentityLength and \a maxPskLen.
*/
void QTlsBackend::setupClientPskAuth(QSslPreSharedKeyAuthenticator *auth, const char *hint,
                                     int hintLength, unsigned maxIdentityLen, unsigned maxPskLen)
{
    Q_ASSERT(auth);
#if QT_CONFIG(ssl)
    if (hint)
        auth->d->identityHint = QByteArray::fromRawData(hint, hintLength); // it's NUL terminated, but do not include the NUL

    auth->d->maximumIdentityLength = int(maxIdentityLen) - 1; // needs to be NUL terminated
    auth->d->maximumPreSharedKeyLength = int(maxPskLen);
#else
    Q_UNUSED(auth);
    Q_UNUSED(hint);
    Q_UNUSED(hintLength);
    Q_UNUSED(maxIdentityLen);
    Q_UNUSED(maxPskLen);
#endif
}

/*!
    \internal
    Auxiliary function. Initializes server-side \a auth using the \a identity, \a identityHint and
    \a maxPskLen.
*/
void QTlsBackend::setupServerPskAuth(QSslPreSharedKeyAuthenticator *auth, const char *identity,
                                     const QByteArray &identityHint, unsigned int maxPskLen)
{
#if QT_CONFIG(ssl)
    Q_ASSERT(auth);
    auth->d->identityHint = identityHint;
    auth->d->identity = identity;
    auth->d->maximumIdentityLength = 0; // user cannot set an identity
    auth->d->maximumPreSharedKeyLength = int(maxPskLen);
#else
    Q_UNUSED(auth);
    Q_UNUSED(identity);
    Q_UNUSED(identityHint);
    Q_UNUSED(maxPskLen);
#endif
}

#if QT_CONFIG(ssl)
/*!
    \internal
    Auxiliary function. Creates a new QSslCipher from \a descriptionOneLine, \a bits
    and \a supportedBits. \a descriptionOneLine consists of several fields, separated by
    whitespace. These include: cipher name, protocol version, key exchange method,
    authentication method, encryption method, message digest (Mac). Example:
    "ECDHE-RSA-AES256-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(256) Mac=AEAD"
*/
QSslCipher QTlsBackend::createCiphersuite(const QString &descriptionOneLine, int bits, int supportedBits)
{
    QSslCipher ciph;

    const auto descriptionList = QStringView{descriptionOneLine}.split(u' ', Qt::SkipEmptyParts);
    if (descriptionList.size() > 5) {
        ciph.d->isNull = false;
        ciph.d->name = descriptionList.at(0).toString();

        QStringView protoString = descriptionList.at(1);
        ciph.d->protocolString = protoString.toString();
        ciph.d->protocol = QSsl::UnknownProtocol;
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
        if (protoString.startsWith(u"TLSv1")) {
            QStringView tail = protoString.sliced(5);
            if (tail.startsWith(u'.')) {
                tail = tail.sliced(1);
                if (tail == u"3")
                    ciph.d->protocol = QSsl::TlsV1_3;
                else if (tail == u"2")
                    ciph.d->protocol = QSsl::TlsV1_2;
                else if (tail == u"1")
                    ciph.d->protocol = QSsl::TlsV1_1;
            } else if (tail.isEmpty()) {
                ciph.d->protocol = QSsl::TlsV1_0;
            }
        }
QT_WARNING_POP

        if (descriptionList.at(2).startsWith("Kx="_L1))
            ciph.d->keyExchangeMethod = descriptionList.at(2).mid(3).toString();
        if (descriptionList.at(3).startsWith("Au="_L1))
            ciph.d->authenticationMethod = descriptionList.at(3).mid(3).toString();
        if (descriptionList.at(4).startsWith("Enc="_L1))
            ciph.d->encryptionMethod = descriptionList.at(4).mid(4).toString();
        ciph.d->exportable = (descriptionList.size() > 6 && descriptionList.at(6) == "export"_L1);

        ciph.d->bits = bits;
        ciph.d->supportedBits = supportedBits;
    }

    return ciph;
}

/*!
    \internal
    Auxiliary function. Creates a new QSslCipher from \a suiteName, \a protocol version and
    \a protocolString. For example:
    \code
    createCiphersuite("ECDHE-RSA-AES256-GCM-SHA256"_L1, QSsl::TlsV1_2, "TLSv1.2"_L1);
    \endcode
*/
QSslCipher QTlsBackend::createCiphersuite(const QString &suiteName, QSsl::SslProtocol protocol,
                                          const QString &protocolString)
{
    QSslCipher ciph;

    if (!suiteName.size())
        return ciph;

    ciph.d->isNull = false;
    ciph.d->name = suiteName;
    ciph.d->protocol = protocol;
    ciph.d->protocolString = protocolString;

    const auto bits = QStringView{ciph.d->name}.split(u'-');
    if (bits.size() >= 2) {
        if (bits.size() == 2 || bits.size() == 3)
            ciph.d->keyExchangeMethod = "RSA"_L1;
        else if (bits.front() == "DH"_L1 || bits.front() == "DHE"_L1)
            ciph.d->keyExchangeMethod = "DH"_L1;
        else if (bits.front() == "ECDH"_L1 || bits.front() == "ECDHE"_L1)
            ciph.d->keyExchangeMethod = "ECDH"_L1;
        else
            qCWarning(lcSsl) << "Unknown Kx" << ciph.d->name;

        if (bits.size() == 2 || bits.size() == 3)
            ciph.d->authenticationMethod = "RSA"_L1;
        else if (ciph.d->name.contains("-ECDSA-"_L1))
            ciph.d->authenticationMethod = "ECDSA"_L1;
        else if (ciph.d->name.contains("-RSA-"_L1))
            ciph.d->authenticationMethod = "RSA"_L1;
        else
            qCWarning(lcSsl) << "Unknown Au" << ciph.d->name;

        if (ciph.d->name.contains("RC4-"_L1)) {
            ciph.d->encryptionMethod = "RC4(128)"_L1;
            ciph.d->bits = 128;
            ciph.d->supportedBits = 128;
        } else if (ciph.d->name.contains("DES-CBC3-"_L1)) {
            ciph.d->encryptionMethod = "3DES(168)"_L1;
            ciph.d->bits = 168;
            ciph.d->supportedBits = 168;
        } else if (ciph.d->name.contains("AES128-"_L1)) {
            ciph.d->encryptionMethod = "AES(128)"_L1;
            ciph.d->bits = 128;
            ciph.d->supportedBits = 128;
        } else if (ciph.d->name.contains("AES256-GCM"_L1)) {
            ciph.d->encryptionMethod = "AESGCM(256)"_L1;
            ciph.d->bits = 256;
            ciph.d->supportedBits = 256;
        } else if (ciph.d->name.contains("AES256-"_L1)) {
            ciph.d->encryptionMethod = "AES(256)"_L1;
            ciph.d->bits = 256;
            ciph.d->supportedBits = 256;
        } else if (ciph.d->name.contains("CHACHA20-"_L1)) {
            ciph.d->encryptionMethod = "CHACHA20"_L1;
            ciph.d->bits = 256;
            ciph.d->supportedBits = 256;
        } else if (ciph.d->name.contains("NULL-"_L1)) {
            ciph.d->encryptionMethod = "NULL"_L1;
        } else {
            qCWarning(lcSsl) << "Unknown Enc" << ciph.d->name;
        }
    }
    return ciph;
}

/*!
    \internal
    Auxiliary function. Creates a new QSslCipher from \a name (which is an implementation-specific
    string), \a protocol and \a protocolString, e.g.:
    \code
    createCipher(QStringLiteral("schannel"), QSsl::TlsV1_2, "TLSv1.2"_L1);
    \endcode
*/
QSslCipher QTlsBackend::createCipher(const QString &name, QSsl::SslProtocol protocol,
                                     const QString &protocolString)
{
    // Note the name 'createCipher' (not 'ciphersuite'): we don't provide
    // information about Kx, Au, bits/supported etc.
    QSslCipher cipher;
    cipher.d->isNull = false;
    cipher.d->name = name;
    cipher.d->protocol = protocol;
    cipher.d->protocolString = protocolString;
    return cipher;
}

/*!
    \internal
    Returns an implementation-specific list of ciphersuites that can be used by QSslSocket.

    \sa QSslConfiguration::defaultCiphers()
*/
QList<QSslCipher> QTlsBackend::defaultCiphers()
{
    return QSslSocketPrivate::defaultCiphers();
}

/*!
    \internal
    Returns an implementation-specific list of ciphersuites that can be used by QDtls.
*/
QList<QSslCipher> QTlsBackend::defaultDtlsCiphers()
{
    return QSslSocketPrivate::defaultDtlsCiphers();
}

/*!
    \internal
    Sets \a ciphers as defaults ciphers that QSslSocket can use.

    \sa defaultCiphers()
*/
void QTlsBackend::setDefaultCiphers(const QList<QSslCipher> &ciphers)
{
    QSslSocketPrivate::setDefaultCiphers(ciphers);
}

/*!
    \internal
    Sets \a ciphers as defaults ciphers that QDtls can use.

    \sa defaultDtlsCiphers()
*/
void QTlsBackend::setDefaultDtlsCiphers(const QList<QSslCipher> &ciphers)
{
    QSslSocketPrivate::setDefaultDtlsCiphers(ciphers);
}

/*!
    \internal
    Sets \a ciphers as a list of supported ciphers.

    \sa QSslConfiguration::supportedCiphers()
*/
void QTlsBackend::setDefaultSupportedCiphers(const QList<QSslCipher> &ciphers)
{
    QSslSocketPrivate::setDefaultSupportedCiphers(ciphers);
}

/*!
    \internal
    Sets the list of QSslEllipticCurve objects, that QSslConfiguration::supportedEllipticCurves()
    returns, to ones that are supported by this backend.
*/
void QTlsBackend::resetDefaultEllipticCurves()
{
    QSslSocketPrivate::resetDefaultEllipticCurves();
}

/*!
    Sets \a certs as a list of certificates, that QSslConfiguration::caCertificates()
    reports.

    \sa QSslConfiguration::defaultConfiguration(), QSslConfiguration::caCertificates()
*/
void QTlsBackend::setDefaultCaCertificates(const QList<QSslCertificate> &certs)
{
    QSslSocketPrivate::setDefaultCaCertificates(certs);
}

/*!
    \internal
    Returns true if \a configuration allows loading root certificates on demand.
*/
bool QTlsBackend::rootLoadingOnDemandAllowed(const QSslConfiguration &configuration)
{
    return configuration.d->allowRootCertOnDemandLoading;
}

/*!
    \internal
    Stores \a peerCert in the \a configuration.
*/
void QTlsBackend::storePeerCertificate(QSslConfiguration &configuration,
                                       const QSslCertificate &peerCert)
{
    configuration.d->peerCertificate = peerCert;
}

/*!
    \internal
    Stores \a peerChain in the \a configuration.
*/
void QTlsBackend::storePeerCertificateChain(QSslConfiguration &configuration,
                                            const QList<QSslCertificate> &peerChain)
{
    configuration.d->peerCertificateChain = peerChain;
}

/*!
    \internal
    Clears the peer certificate chain in \a configuration.
*/
void QTlsBackend::clearPeerCertificates(QSslConfiguration &configuration)
{
    configuration.d->peerCertificate.clear();
    configuration.d->peerCertificateChain.clear();
}

/*!
    \internal
    Clears the peer certificate chain in \a d.
*/
void QTlsBackend::clearPeerCertificates(QSslSocketPrivate *d)
{
    Q_ASSERT(d);
    d->configuration.peerCertificate.clear();
    d->configuration.peerCertificateChain.clear();
}

/*!
    \internal
    Updates the configuration in \a d with \a shared value.
*/
void QTlsBackend::setPeerSessionShared(QSslSocketPrivate *d, bool shared)
{
    Q_ASSERT(d);
    d->configuration.peerSessionShared = shared;
}

/*!
    \internal
    Sets TLS session in \a d to \a asn1.
*/
void QTlsBackend::setSessionAsn1(QSslSocketPrivate *d, const QByteArray &asn1)
{
    Q_ASSERT(d);
    d->configuration.sslSession = asn1;
}

/*!
    \internal
    Sets TLS session lifetime hint in \a d to \a hint.
*/
void QTlsBackend::setSessionLifetimeHint(QSslSocketPrivate *d, int hint)
{
    Q_ASSERT(d);
    d->configuration.sslSessionTicketLifeTimeHint = hint;
}

/*!
    \internal
    Sets application layer protocol negotiation status in \a d to \a st.
*/
void QTlsBackend::setAlpnStatus(QSslSocketPrivate *d, AlpnNegotiationStatus st)
{
    Q_ASSERT(d);
    d->configuration.nextProtocolNegotiationStatus = st;
}

/*!
    \internal
    Sets \a protocol in \a d as a negotiated application layer protocol.
*/
void QTlsBackend::setNegotiatedProtocol(QSslSocketPrivate *d, const QByteArray &protocol)
{
    Q_ASSERT(d);
    d->configuration.nextNegotiatedProtocol = protocol;
}

/*!
    \internal
    Stores \a peerCert in the TLS configuration of \a d.
*/
void QTlsBackend::storePeerCertificate(QSslSocketPrivate *d, const QSslCertificate &peerCert)
{
    Q_ASSERT(d);
    d->configuration.peerCertificate = peerCert;
}

/*!
    \internal

    Stores \a peerChain in the TLS configuration of \a d.

    \note This is a helper function that TlsCryptograph and DtlsCryptograph
    call during a handshake.
*/
void QTlsBackend::storePeerCertificateChain(QSslSocketPrivate *d,
                                            const QList<QSslCertificate> &peerChain)
{
    Q_ASSERT(d);
    d->configuration.peerCertificateChain = peerChain;
}

/*!
    \internal

    Adds \a rootCert to the list of trusted root certificates in \a d.

    \note In Qt 6.1 it's only used on Windows, during so called 'CA fetch'.
*/
void QTlsBackend::addTustedRoot(QSslSocketPrivate *d, const QSslCertificate &rootCert)
{
    Q_ASSERT(d);
    if (!d->configuration.caCertificates.contains(rootCert))
        d->configuration.caCertificates += rootCert;
}

/*!
    \internal

    Saves ephemeral \a key in \a d.

    \sa QSslConfiguration::ephemeralKey()
*/
void QTlsBackend::setEphemeralKey(QSslSocketPrivate *d, const QSslKey &key)
{
    Q_ASSERT(d);
    d->configuration.ephemeralServerKey = key;
}

/*!
    \internal

    Implementation-specific. Sets the security level suitable for Qt's
    auto-tests.
*/
void QTlsBackend::forceAutotestSecurityLevel()
{
}

#endif // QT_CONFIG(ssl)

namespace QTlsPrivate {

/*!
    \internal (Network-private)
    \namespace QTlsPrivate
    \brief Namespace containing onternal types that TLS backends implement.

    This namespace is private to Qt and the backends that implement its TLS support.
*/

/*!
    \class TlsKey
    \internal (Network-private)
    \brief TlsKey is an abstract class, that allows a TLS plugin to provide
    an underlying implementation for the class QSslKey.

    Most functions in the class TlsKey are pure virtual and thus have to be
    reimplemented by a TLS backend that supports QSslKey. In many cases an
    empty implementation as an overrider is sufficient, albeit with some
    of QSslKey's functionality missing.

    \sa QTlsBackend::createKey(), QTlsBackend::implementedClasses(), QSslKey
*/

/*!
    \fn void TlsKey::decodeDer(KeyType type, KeyAlgorithm algorithm, const QByteArray &der, const QByteArray &passPhrase, bool deepClear)
    \internal

    If a support of public and private keys in DER format is required, this function
    must be overridden and should initialize this key using the \a type, \a algorithm, \a der
    and \a passPhrase. If this key was initialized previously, \a deepClear
    has an implementation-specific meaning (e.g., if an implementation is using
    reference-counting and can share internally some data structures, a value \c true may
    trigger decrementing a reference counter on some implementation-specific object).

    \note An empty overrider is sufficient, but then reading keys in QSsl::Der format
    will not be supported.

    \sa isNull(), QSsl::KeyType, QSsl::EncodingFormat, QSsl::KeyAlgorithm
*/

/*!
    \fn void TlsKey::decodePem(KeyType type, KeyAlgorithm algorithm, const QByteArray &pem, const QByteArray &passPhrase, bool deepClear)
    \internal

    If a support of public and private keys in PEM format is required, this function must
    be overridden and should initialize this key using the \a type, \a algorithm, \a pem and
    \a passPhrase. If this key was initialized previously, \a deepClear has an
    implementation-specific meaning (e.g., in an implementation using reference-counting,
    a value \c true may trigger decrementing a reference counter on some implementation-specific
    object).

    \note An empty overrider is sufficient, but then reading keys in QSsl::Pem format
    will not be supported.

    \sa isNull(), QSsl::KeyType, QSsl::EncodingFormat, QSsl::KeyAlgorithm
*/

/*!
    \fn QByteArray TlsKey::toPem(const QByteArray &passPhrase) const
    \internal

    This function must be overridden, if converting a key to PEM format, potentially with
    encryption, is needed (e.g. to save a QSslKey into a file). If this key is
    private and \a passPhrase is not empty, the key's data is expected to be encrypted using
    some conventional encryption algorithm (e.g. DES or AES - the one that different tools
    or even the class QSslKey can understand later).

    \note If this particular functionality is not needed, an overrider returning an
    empty QByteArray is sufficient.

    \sa QSslKey::toPem()
*/

/*!
    \fn QByteArray TlsKey::derFromPem(const QByteArray &pem, QMap<QByteArray, QByteArray> *headers) const
    \internal

    Converts \a pem to DER format, using this key's type and algorithm. The parameter \a headers
    must be a valid, non-null pointer. When parsing \a pem, the headers found there will be saved
    into \a headers.

    \note An overrider returning an empty QByteArray is sufficient, if QSslKey::toDer() is not
    needed.

    \note This function is very implementation-specific. A backend, that already has this key's
    non-empty DER data, may simply return this data.

    \sa QSslKey::toDer()
*/

/*!
    \fn QByteArray TlsKey::pemFromDer(const QByteArray &der, const QMap<QByteArray, QByteArray> &headers) const
    \internal

    If overridden, this function is expected to convert \a der, using \a headers, to PEM format.

    \note This function is very implementation-specific. As of now (Qt 6.1), it is only required by
    Qt's own non-OpenSSL backends, that internally use DER and implement QSslKey::toPem()
    via pemFromDer().
*/

/*!
    \fn void TlsKey::fromHandle(Qt::HANDLE handle, KeyType type)
    \internal

    Initializes this key using the \a handle and \a type, taking the ownership
    of the \a handle.

    \note The meaning of the \a handle is implementation-specific.

    \note If a TLS backend does not support such keys, it must provide an
    empty implementation.

    \sa handle(), QSslKey::QSslKey(), QSslKet::handle()
*/

/*!
    \fn TlsKey::handle() const
    \internal

    If a TLS backend supports opaque keys, returns a native handle that
    this key was initialized with.

    \sa fromHandle(), QSslKey::handle()
*/

/*!
    \fn bool TlsKey::isNull() const
    \internal

    Returns \c true if this is a null key, \c false otherwise.

    \note A null key corresponds to the default-constructed
    QSslKey or the one, that was cleared via QSslKey::clear().

    \sa QSslKey::isNull()
*/

/*!
    \fn QSsl::KeyType TlsKey::type() const
    \internal

    Returns the type of this key (public or private).
*/

/*!
    \fn QSsl::KeyAlgorithm TlsKey::algorithm() const
    \internal

    Return this key's algorithm.
*/

/*!
    \fn int TlsKey::length() const
    \internal

    Returns the length of the key in bits, or -1 if the key is null.
*/

/*!
    \fn void TlsKey::clear(bool deep)
    \internal

    Clears the contents of this key, making it a null key. The meaning
    of \a deep is implementation-specific (e.g. if some internal objects
    representing a key can be shared using reference counting, \a deep equal
    to \c true would imply decrementing a reference count).

    \sa isNull()
*/

/*!
    \fn bool TlsKey::isPkcs8() const
    \internal

    This function is internally used only by Qt's own TLS plugins and affects
    the way PEM file is generated by TlsKey. It's sufficient to override it
    and return \c false in case a new TLS backend is not using Qt's plugin
    as a base.
*/

/*!
    \fn QByteArray TlsKey::decrypt(Cipher cipher, const QByteArray &data, const QByteArray &passPhrase, const QByteArray &iv) const
    \internal

    This function allows to decrypt \a data (for example, a private key read from a file), using
    \a passPhrase, initialization vector \a iv. \a cipher is describing a block cipher and its
    mode (for example, AES256 + CBC). decrypt() is needed to implement QSslKey's constructor.

    \note A TLS backend may provide an empty implementation, but as a result QSslKey will not be able
    to work with private encrypted keys.

    \sa QSslKey
*/

/*!
    \fn QByteArray TlsKey::encrypt(Cipher cipher, const QByteArray &data, const QByteArray &passPhrase, const QByteArray &iv) const
    \internal

    This function is needed to implement QSslKey::toPem() with encryption (for a private
    key). \a cipher names a block cipher to use to encrypt \a data, using
    \a passPhrase and initialization vector \a iv.

    \note An empty implementation is sufficient, but QSslKey::toPem() will fail for
    a private key and non-empty passphrase.

    \sa QSslKey
*/

/*!
    \internal

    Destroys this key.
*/
TlsKey::~TlsKey() = default;

/*!
    \internal

    A convenience function that returns a string, corresponding to the
    key type or algorithm, which can be used as a header in a PEM file.
*/
QByteArray TlsKey::pemHeader() const
{
    if (type() == QSsl::PublicKey)
        return QByteArrayLiteral("-----BEGIN PUBLIC KEY-----");
    else if (algorithm() == QSsl::Rsa)
        return QByteArrayLiteral("-----BEGIN RSA PRIVATE KEY-----");
    else if (algorithm() == QSsl::Dsa)
        return QByteArrayLiteral("-----BEGIN DSA PRIVATE KEY-----");
    else if (algorithm() == QSsl::Ec)
        return QByteArrayLiteral("-----BEGIN EC PRIVATE KEY-----");
    else if (algorithm() == QSsl::Dh)
        return QByteArrayLiteral("-----BEGIN PRIVATE KEY-----");

    Q_UNREACHABLE();
    return {};
}

/*!
    \internal
    A convenience function that returns a string, corresponding to the
    key type or algorithm, which can be used as a footer in a PEM file.
*/
QByteArray TlsKey::pemFooter() const
{
    if (type() == QSsl::PublicKey)
        return QByteArrayLiteral("-----END PUBLIC KEY-----");
    else if (algorithm() == QSsl::Rsa)
        return QByteArrayLiteral("-----END RSA PRIVATE KEY-----");
    else if (algorithm() == QSsl::Dsa)
        return QByteArrayLiteral("-----END DSA PRIVATE KEY-----");
    else if (algorithm() == QSsl::Ec)
        return QByteArrayLiteral("-----END EC PRIVATE KEY-----");
    else if (algorithm() == QSsl::Dh)
        return QByteArrayLiteral("-----END PRIVATE KEY-----");

    Q_UNREACHABLE();
    return {};
}

/*!
    \class X509Certificate
    \internal (Network-private)
    \brief X509Certificate is an abstract class that allows a TLS backend to
    provide an implementation of the QSslCertificate class.

    This class provides an interface that must be reimplemented by a TLS plugin,
    that supports QSslCertificate. Most functions are pure virtual, and thus
    have to be overridden. For some of them, an empty overrider is acceptable,
    though a part of functionality in QSslCertificate will be missing.

    \sa QTlsBackend::createCertificate(), QTlsBackend::X509PemReader(), QTlsBackend::X509DerReader()
*/

/*!
    \fn bool X509Certificate::isEqual(const X509Certificate &other) const
    \internal

    This function is expected to return \c true if this certificate is the same as
    the \a other, \c false otherwise. Used by QSslCertificate's comparison operators.
*/

/*!
    \fn bool X509Certificate::isNull() const
    \internal

    Returns true if this certificate was default-constructed and not initialized yet.
    This function is called by QSslCertificate::isNull().

    \sa QSslCertificate::isNull()
*/

/*!
    \fn bool X509Certificate::isSelfSigned() const
    \internal

    This function is needed to implement QSslCertificate::isSelfSigned()

    \sa QSslCertificate::isSelfSigned()
*/

/*!
    \fn QByteArray X509Certificate::version() const
    \internal

    Implements QSslCertificate::version().

    \sa QSslCertificate::version()
*/

/*!
    \fn QByteArray X509Certificate::serialNumber() const
    \internal

    This function is expected to return the certificate's serial number string in
    hexadecimal format.

    \sa QSslCertificate::serialNumber()
*/

/*!
    \fn QStringList X509Certificate::issuerInfo(QSslCertificate::SubjectInfo subject) const
    \internal

    This function is expected to return the issuer information for the \a subject
    from the certificate, or an empty list if there is no information for subject
    in the certificate. There can be more than one entry of each type.

    \sa QSslCertificate::issuerInfo().
*/

/*!
    \fn QStringList X509Certificate::issuerInfo(const QByteArray &attribute) const
    \internal

    This function is expected to return the issuer information for attribute from
    the certificate, or an empty list if there is no information for \a attribute
    in the certificate. There can be more than one entry for an attribute.

    \sa QSslCertificate::issuerInfo().
*/

/*!
    \fn QStringList X509Certificate::subjectInfo(QSslCertificate::SubjectInfo subject) const
    \internal

    This function is expected to return the information for the \a subject, or an empty list
    if there is no information for subject in the certificate. There can be more than one
    entry of each type.

    \sa QSslCertificate::subjectInfo().
*/

/*!
    \fn QStringList X509Certificate::subjectInfo(const QByteArray &attribute) const
    \internal

    This function is expected to return the subject information for \a attribute, or
    an empty list if there is no information for attribute in the certificate.
    There can be more than one entry for an attribute.

    \sa QSslCertificate::subjectInfo().
*/

/*!
    \fn QList<QByteArray> X509Certificate::subjectInfoAttributes() const
    \internal

    This function is expected to return a list of the attributes that have values
    in the subject information of this certificate. The information associated
    with a given attribute can be accessed using the subjectInfo() method. Note
    that this list may include the OIDs for any elements that are not known by
    the TLS backend.

    \note This function is needed for QSslCertificate:::subjectInfoAttributes().

    \sa subjectInfo()
*/

/*!
    \fn QList<QByteArray> X509Certificate::issuerInfoAttributes() const
    \internal

    This function is expected to return a list of the attributes that have
    values in the issuer information of this certificate. The information
    associated with a given attribute can be accessed using the issuerInfo()
    method. Note that this list may include the OIDs for any
    elements that are not known by the TLS backend.

    \note This function implements QSslCertificate::issuerInfoAttributes().

    \sa issuerInfo()
*/

/*!
    \fn QMultiMap<QSsl::AlternativeNameEntryType, QString> X509Certificate::subjectAlternativeNames() const
    \internal

    This function is expected to return the list of alternative subject names for
    this certificate. The alternative names typically contain host names, optionally
    with wildcards, that are valid for this certificate.

    \sa subjectInfo()
*/

/*!
    \fn QDateTime X509Certificate::effectiveDate() const
    \internal

    This function is expected to return the date-time that the certificate
    becomes valid, or an empty QDateTime if this is a null certificate.

    \sa expiryDate()
*/

/*!
    \fn QDateTime X509Certificate::expiryDate() const
    \internal

    This function is expected to return the date-time that the certificate expires,
    or an empty QDateTime if this is a null certificate.

    \sa effectiveDate()
*/

/*!
    \fn qsizetype X509Certificate::numberOfExtensions() const
    \internal

    This function is expected to return the number of X509 extensions of
    this certificate.
*/

/*!
    \fn QString X509Certificate::oidForExtension(qsizetype i) const
    \internal

    This function is expected to return the ASN.1 OID for the extension
    with index \a i.

    \sa numberOfExtensions()
*/

/*!
    \fn QString X509Certificate::nameForExtension(qsizetype i) const
    \internal

    This function is expected to return the name for the extension
    with index \a i. If no name is known for the extension then the
    OID will be returned.

    \sa numberOfExtensions(), oidForExtension()
*/

/*!
    \fn QVariant X509Certificate::valueForExtension(qsizetype i) const
    \internal

    This function is expected to return the value of the extension
    with index \a i. The structure of the value returned depends on
    the extension type

    \sa numberOfExtensions()
*/

/*!
    \fn bool X509Certificate::isExtensionCritical(qsizetype i) const
    \internal

    This function is expected to return the criticality of the extension
    with index \a i.

    \sa numberOfExtensions()
*/

/*!
    \fn bool X509Certificate::isExtensionSupported(qsizetype i) const
    \internal

    This function is expected to return \c true if this extension is supported.
    In this case, supported simply means that the structure of the QVariant returned
    by the valueForExtension() accessor will remain unchanged between versions.

    \sa numberOfExtensions()
*/

/*!
    \fn QByteArray X509Certificate::toPem() const
    \internal

    This function is expected to return this certificate converted to a PEM (Base64)
    encoded representation.
*/

/*!
    \fn QByteArray X509Certificate::toDer() const
    \internal

    This function is expected to return this certificate converted to a DER (binary)
    encoded representation.
*/

/*!
    \fn QString X509Certificate::toText() const
    \internal

    This function is expected to return this certificate converted to a human-readable
    text representation.
*/

/*!
    \fn Qt::HANDLE X509Certificate::handle() const
    \internal

    This function is expected to return a pointer to the native certificate handle,
    if there is one, else nullptr.
*/

/*!
    \fn size_t X509Certificate::hash(size_t seed) const
    \internal

    This function is expected to return the hash value for this certificate,
    using \a seed to seed the calculation.
*/

/*!
    \internal

    Destroys this certificate.
*/
X509Certificate::~X509Certificate() = default;

/*!
    \internal

    Returns the certificate subject's public key.
*/
TlsKey *X509Certificate::publicKey() const
{
    return nullptr;
}

#if QT_CONFIG(ssl)

/*!
    \class TlsCryptograph
    \internal (Network-private)
    \brief TlsCryptograph is an abstract class, that allows a TLS pluging to implement QSslSocket.

    This abstract base class provides an interface that must be reimplemented by a TLS plugin,
    that supports QSslSocket. A class, implementing TlsCryptograph's interface, is responsible
    for TLS handshake, reading and writing encryped application data; it is expected
    to work with QSslSocket and it's private implementation - QSslSocketPrivate.
    QSslSocketPrivate provides access to its read/write buffers, QTcpSocket it
    internally uses for connecting, reading and writing. QSslSocketPrivate
    can also be used for reporting errors and storing the certificates received
    during the handshake phase.

    \note Most of the functions in this class are pure virtual and have no actual implementation
    in the QtNetwork module. This documentation is mostly conceptual and only describes what those
    functions are expected to do, but not how they must be implemented.

    \sa QTlsBackend::createTlsCryptograph()
*/

/*!
    \fn void TlsCryptograph::init(QSslSocket *q, QSslSocketPrivate *d)
    \internal

    When initializing this TlsCryptograph, QSslSocket will pass a pointer to self and
    its d-object using this function.
*/

/*!
    \fn QList<QSslError> TlsCryptograph::tlsErrors() const
    \internal

    Returns a list of QSslError, describing errors encountered during
    the TLS handshake.

    \sa QSslSocket::sslHandshakeErrors()
*/

/*!
    \fn void TlsCryptograph::startClientEncryption()
    \internal

    A client-side QSslSocket calls this function after its internal TCP socket
    establishes a connection with a remote host, or from QSslSocket::startClientEncryption().
    This TlsCryptograph is expected to initialize some implementation-specific TLS context,
    if needed, and then start the client side of the TLS handshake (for example, by calling
    transmit()), using TCP socket from QSslSocketPrivate.

    \sa init(), transmit(), QSslSocket::startClientEncryption(), QSslSocket::connectToHostEncrypted()
*/

/*!
    \fn void TlsCryptograph::startServerEncryption()
    \internal

    This function is called by QSslSocket::startServerEncryption(). The TlsCryptograph
    is expected to initialize some implementation-specific TLS context, if needed,
    and then try to read the ClientHello message and continue the TLS handshake
    (for example, by calling transmit()).

    \sa transmit(), QSslSocket::startServerEncryption()
*/

/*!
    \fn void TlsCryptograph::continueHandshake()
    \internal

    QSslSocket::resume() calls this function if its pause mode is QAbstractSocket::PauseOnSslErrors,
    and errors, found during the handshake, were ignored. If implemented, this function is expected
    to emit QSslSocket::encrypted().

    \sa QAbstractSocket::pauseMode(), QSslSocket::sslHandshakeErrors(), QSslSocket::ignoreSslErrors(), QSslSocket::resume()
*/

/*!
    \fn void TlsCryptograph::disconnectFromHost()
    \internal

    This function is expected to call disconnectFromHost() on the TCP socket
    that can be obtained from QSslSocketPrivate. Any additional actions
    are implementation-specific (e.g., sending shutdown alert message).

*/

/*!
    \fn void TlsCryptograph::disconnected()
    \internal

    This function is called when the remote has disconnected. If there
    is data left to be read you may ignore the maxReadBufferSize restriction
    and read it all now.
*/

/*!
    \fn QSslCipher TlsCryptograph::sessionCipher() const
    \internal

    This function returns a QSslCipher object describing the ciphersuite negotiated
    during the handshake.
*/

/*!
    \fn QSsl::SslProtocol TlsCryptograph::sessionProtocol() const
    \internal

    This function returns the version of TLS (or DTLS) protocol negotiated during the handshake.
*/

/*!
    \fn void TlsCryptograph::transmit()
    \internal

    This function is responsible for reading and writing data. The meaning of these I/O
    operations depends on an implementation-specific TLS state machine. These read and write
    operations can be reading and writing parts of a TLS handshake (e.g. by calling handshake-specific
    functions), or reading and writing application data (if encrypted connection was already
    established). transmit() is expected to use the QSslSocket's TCP socket (accessible via
    QSslSocketPrivate) to read the incoming data and write the outgoing data. When in encrypted
    state, transmit() is also using QSslSocket's internal read and write buffers: the read buffer
    to fill with decrypted incoming data; the write buffer - for the data to encrypt and send.
    This TlsCryptograph can also use QSslSocketPrivate to check which TLS errors were ignored during
    the handshake.

    \note This function is responsible for emitting QSslSocket's signals, that occur during the
    handshake (e.g. QSslSocket::sslErrors() or QSslSocket::encrypted()), and also read/write signals,
    e.g. QSslSocket::bytesWritten() and QSslSocket::readyRead().

    \sa init()
*/

/*!
    \internal

    Destroys this object.
*/
TlsCryptograph::~TlsCryptograph() = default;

/*!
    \internal

    This function allows to share QSslContext between several QSslSocket objects.
    The default implementation does nothing.

    \note The definition of the class QSslContext is implementation-specific.

    \sa sslContext()
*/
void TlsCryptograph::checkSettingSslContext(std::shared_ptr<QSslContext> tlsContext)
{
    Q_UNUSED(tlsContext);
}

/*!
    \internal

    Returns the context previously set by checkSettingSslContext() or \nullptr,
    if no context was set. The default implementation returns \nullptr.

    \sa checkSettingSslContext()
*/
std::shared_ptr<QSslContext> TlsCryptograph::sslContext() const
{
    return {};
}

/*!
    \internal

    If this TLS backend supports reporting errors before handshake is finished,
    e.g. from a verification callback function, enableHandshakeContinuation()
    allows this object to continue handshake. The default implementation does
    nothing.

    \sa QSslSocket::handshakeInterruptedOnError(), QSslConfiguration::setHandshakeMustInterruptOnError()
*/
void TlsCryptograph::enableHandshakeContinuation()
{
}

/*!
    \internal

    Windows and OpenSSL-specific, only used internally by Qt's OpenSSL TLS backend.

    \note The default empty implementation is sufficient.
*/
void TlsCryptograph::cancelCAFetch()
{
}

/*!
    \internal

    Windows and Schannel-specific, only used by Qt's Schannel TLS backend, in
    general, if a backend has its own buffer where it stores undecrypted data
    then it must report true if it contains any data through this function.

    \note The default empty implementation, returning \c false is sufficient.
*/
bool TlsCryptograph::hasUndecryptedData() const
{
    return false;
}

/*!
    \internal

    Returns the list of OCSP (Online Certificate Status Protocol) responses,
    received during the handshake. The default implementation returns an empty
    list.
*/
QList<QOcspResponse> TlsCryptograph::ocsps() const
{
    return {};
}

/*!
    \internal

    A helper function that can be used during a handshake. Returns \c true if the \a peerName
    matches one of subject alternative names or common names found in the \a certificate.
*/
bool TlsCryptograph::isMatchingHostname(const QSslCertificate &certificate, const QString &peerName)
{
    return QSslSocketPrivate::isMatchingHostname(certificate, peerName);
}

/*!
    \internal
    Calls QAbstractSocketPrivate::setErrorAndEmit() for \a d, passing \a errorCode and
    \a errorDescription as parameters.
*/
void TlsCryptograph::setErrorAndEmit(QSslSocketPrivate *d, QAbstractSocket::SocketError errorCode,
                                     const QString &errorDescription) const
{
    Q_ASSERT(d);
    d->setErrorAndEmit(errorCode, errorDescription);
}

#if QT_CONFIG(dtls)
/*!
    \class DtlsBase
    \internal (Network-private)
    \brief DtlsBase is a base class for the classes DtlsCryptograph and DtlsCookieVerifier.

    DtlsBase is the base class for the classes DtlsCryptograph and DtlsCookieVerifier. It's
    an abstract class, an interface that these before-mentioned classes share. It allows to
    set, get and clear the last error that occurred, set and get cookie generation parameters,
    set and get QSslConfiguration.

    \note This class is not supposed to be inherited directly, it's only needed by DtlsCryptograph
    and DtlsCookieVerifier.

    \sa QDtls, QDtlsClientVerifier, DtlsCryptograph, DtlsCookieVerifier
*/

/*!
    \fn void DtlsBase::setDtlsError(QDtlsError code, const QString &description)
    \internal

    Sets the last error to \a code and its textual description to \a description.

    \sa QDtlsError, error(), errorString()
*/

/*!
    \fn QDtlsError DtlsBase::error() const
    \internal

    This function, when overridden, is expected to return the code for the last error that occurred.
    If no error occurred it should return QDtlsError::NoError.

    \sa QDtlsError, errorString(), setDtlsError()
*/

/*!
    \fn QDtlsError DtlsBase::errorString() const
    \internal

    This function, when overridden, is expected to return the textual description for the last error
    that occurred or an empty string if no error occurred.

    \sa QDtlsError, error(), setDtlsError()
*/

/*!
    \fn void DtlsBase::clearDtlsError()
    \internal

    This function is expected to set the error code for the last error to QDtlsError::NoError and
    its textual description to an empty string.

    \sa QDtlsError, setDtlsError(), error(), errorString()
*/

/*!
    \fn void DtlsBase::setConfiguration(const QSslConfiguration &configuration)
    \internal

    Sets a TLS configuration that an object of a class inheriting from DtlsCookieVerifier or
    DtlsCryptograph will use, to \a configuration.

    \sa configuration()
*/

/*!
    \fn QSslConfiguration DtlsBase::configuration() const
    \internal

    Returns TLS configuration this object is using (either set by setConfiguration()
    previously, or the default DTLS configuration).

    \sa setConfiguration(), QSslConfiguration::defaultDtlsConfiguration()
*/

/*!
    \fn bool DtlsBase::setCookieGeneratorParameters(const QDtlsClientVerifier::GeneratorParameters &params)
    \internal

    Sets the DTLS cookie generation parameters that DtlsCookieVerifier or DtlsCryptograph will use to
    \a params.

    \note This function returns \c false if parameters were invalid - if the secret was empty. Otherwise,
    this function must return true.

    \sa QDtlsClientVerifier::GeneratorParameters, cookieGeneratorParameters()
*/

/*!
    \fn QDtlsClientVerifier::GeneratorParameters DtlsBase::cookieGeneratorParameters() const
    \internal

    Returns DTLS cookie generation parameters that were either previously set by setCookieGeneratorParameters(),
    or default parameters.

    \sa setCookieGeneratorParameters()
*/

/*!
    \internal

    Destroys this object.
*/
DtlsBase::~DtlsBase() = default;

/*!
    \class DtlsCookieVerifier
    \internal (Network-private)
    \brief DtlsCookieVerifier is an interface that allows a TLS plugin to support the class QDtlsClientVerifier.

    DtlsCookieVerifier is an interface, an abstract class, that has to be implemented by
    a TLS plugin that supports DTLS cookie verification.

    \sa QDtlsClientVerifier
*/

/*!
    \fn bool DtlsCookieVerifier::verifyClient(QUdpSocket *socket, const QByteArray &dgram, const QHostAddress &address, quint16 port)
    \internal

    This function is expected to verify a ClientHello message, found in \a dgram, using \a address,
    \a port, and cookie generator parameters. The function returns \c true if such cookie was found
    and \c false otherwise. If no valid cookie was found in the \a dgram, this verifier should use
    \a socket to send a HelloVerifyRequest message, using \a address and \a port as the destination
    and a source material for cookie generation, see also
    \l {RFC 6347, section 4.2.1}

    \sa QDtlsClientVerifier
*/

/*!
    \fn QByteArray DtlsCookieVerifier::verifiedHello() const
    \internal

    Returns the last ClientHello message containing the DTLS cookie that this verifier was
    able to verify as correct, or an empty byte array.

    \sa verifyClient()
*/

/*!
    \class DtlsCryptograph
    \internal (Network-private)
    \brief DtlsCryptograph is an interface that allows a TLS plugin to implement the class QDtls.

    DtlsCryptograph is an abstract class; a TLS plugin can provide a class, inheriting from
    DtlsCryptograph and implementing its pure virtual functions, thus implementing the class
    QDtls and enabling DTLS over UDP.

    To write DTLS datagrams, a class, inheriting DtlsCryptograph, is expected to use
    QUdpSocket. In general, all reading is done externally, so DtlsCryptograph is
    expected to only write into QUdpSocket, check possible socket errors, change socket
    options if needed.

    \note All functions in this class are pure virtual and have no actual implementation
    in the QtNetwork module. This documentation is mostly conceptual and only describes
    what those functions are expected to do, but not how they must be implemented.

    \sa QDtls, QUdpSocket
*/

/*!
    \fn QSslSocket::SslMode DtlsCryptograph::cryptographMode() const
    \internal

    Returns the mode (client or server) this object operates in.

    \note This mode is set once when a new DtlsCryptograph is created
    by QTlsBackend and cannot change.

    \sa QTlsBackend::createDtlsCryptograph()
*/

/*!
    \fn void DtlsCryptograph::setPeer(const QHostAddress &addr, quint16 port, const QString &name)
    \internal

    Sets the remote peer's address to \a addr and remote port to \a port. \a name,
    if not empty, is to be used when validating the peer's certificate.

    \sa peerAddress(), peerPort(), peerVerificationName()
*/

/*!
    \fn QHostAddress DtlsCryptograph::peerAddress() const
    \internal

    Returns the remote peer's address previously set by setPeer() or,
    if no address was set, an empty address.

    \sa setPeer()
*/

/*!
    \fn quint16 DtlsCryptograph::peerPort() const
    \internal

    Returns the remote peer's port previously set by setPeer() or
    0 if no port was set.

    \sa setPeer(), peerAddress()
*/

/*!
    \fn void DtlsCryptograph::setPeerVerificationName(const QString &name)
    \internal

    Sets the host name to use during certificate validation to \a name.

    \sa peerVerificationName(), setPeer()
*/

/*!
    \fn QString DtlsCryptograph::peerVerificationName() const
    \internal

    Returns the name that this object is using during the certificate validation,
    previously set by setPeer() or setPeerVerificationName(). Returns an empty string
    if no peer verification name was set.

    \sa setPeer(), setPeerVerificationName()
*/

/*!
    \fn void DtlsCryptograph::setDtlsMtuHint(quint16 mtu)
    \internal

    Sets the maximum transmission unit (MTU), if it is supported by a TLS implementation, to \a mtu.

    \sa dtlsMtuHint()
*/

/*!
    \fn quint16 DtlsCryptograph::dtlsMtuHint() const
    \internal

    Returns the value of the maximum transmission unit either previously set by setDtlsMtuHint(),
    or some implementation-specific value (guessed or somehow known to this DtlsCryptograph).

    \sa setDtlsMtuHint()
*/

/*!
    \fn QDtls::HandshakeState DtlsCryptograph::state() const
    \internal

    Returns the current handshake state for this DtlsCryptograph (not started, in progress,
    peer verification error found, complete).

    \sa isConnectionEncrypted(), startHandshake()
*/

/*!
    \fn bool DtlsCryptograph::isConnectionEncrypted() const
    \internal

    Returns \c true if this DtlsCryptograph has completed a handshake without validation
    errors (or these errors were ignored). Returns \c false otherwise.
*/

/*!
    \fn bool DtlsCryptograph::startHandshake(QUdpSocket *socket, const QByteArray &dgram)
    \internal

    This function is expected to initialize some implementation-specific context and to start a DTLS
    handshake, using \a socket to write datagrams (but not to read them). If this object is operating
    as a server, \a dgram is non-empty and contains the ClientHello message. This function returns
    \c true if no error occurred (and this DtlsCryptograph's state switching to
    QDtls::HandshakeState::HandshakeInProgress), \c false otherwise.

    \sa continueHandshake(), handleTimeout(), resumeHandshake(), abortHandshake(), state()
*/

/*!
    \fn bool DtlsCryptograph::handleTimeout(QUdpSocket *socket)
    \internal

    In case a timeout occurred during the handshake, allows to re-transmit the last message,
    using \a socket to write the datagram. Returns \c true if no error occurred, \c false otherwise.

    \sa QDtls::handshakeTimeout(), QDtls::handleTimeout()
*/

/*!
    \fn bool DtlsCryptograph::continueHandshake(QUdpSocket *socket, const QByteArray &dgram)
    \internal

    Continues the handshake, using \a socket to write datagrams (a handshake-specific message).
    \a dgram contains the peer's handshake-specific message. Returns \c false in case some error
    was encountered (this can include socket-related errors and errors found during the certificate
    validation). Returns \c true if the handshake was complete successfully, or is still in progress.

    This function, depending on the implementation-specific state machine, may leave the handshake
    state in QDtls::HandshakeState::HandshakeInProgress, or switch to QDtls::HandshakeState::HandshakeComplete
    or QDtls::HandshakeState::PeerVerificationFailed.

    This function may store the peer's certificate (or chain of certificates), extract and store
    the information about the negotiated session protocol and ciphersuite.

    \sa startHandshake()
*/

/*!
    \fn bool DtlsCryptograph::resumeHandshake(QUdpSocket *socket)
    \internal

    If peer validation errors were found duing the handshake, this function tries to
    continue and complete the handshake. If errors were ignored, the function switches
    this object's state to QDtls::HandshakeState::HandshakeComplete and returns \c true.

    \sa abortHandshake()
*/

/*!
    \fn void DtlsCryptograph::abortHandshake(QUdpSocket *socket)
    \internal

    Aborts the handshake if it's in progress or in the state QDtls::HandshakeState::PeerVerificationFailed.
    The use of \a socket is implementation-specific (for example, this DtlsCryptograph may send
    ShutdownAlert message).

    \sa resumeHandshake()
*/

/*!
    \fn void DtlsCryptograph::sendShutdownAlert(QUdpSocket *socket)
    \internal

    If the underlying TLS library provides the required functionality, this function
    may sent ShutdownAlert message using \a socket.
*/

/*!
    \fn QList<QSslError> DtlsCryptograph::peerVerificationErrors() const
    \internal

    Returns the list of errors that this object encountered during DTLS handshake
    and certificate validation.

    \sa ignoreVerificationErrors()
*/

/*!
    \fn void DtlsCryptograph::ignoreVerificationErrors(const QList<QSslError> &errorsToIgnore)
    \internal

    Tells this object to ignore errors from \a errorsToIgnore when they are found during
    DTLS handshake.

    \sa peerVerificationErrors()
*/

/*!
    \fn QSslCipher DtlsCryptograph::dtlsSessionCipher() const
    \internal

    If such information is available, returns the ciphersuite, negotiated during
    the handshake.

    \sa continueHandshake(), dtlsSessionProtocol()
*/

/*!
    \fn QSsl::SslProtocol DtlsCryptograph::dtlsSessionProtocol() const
    \internal

    Returns the version of the session protocol that was negotiated during the handshake or
    QSsl::UnknownProtocol if the handshake is incomplete or no information about the session
    protocol is available.

    \sa continueHandshake(), dtlsSessionCipher()
*/

/*!
    \fn qint64 DtlsCryptograph::writeDatagramEncrypted(QUdpSocket *socket, const QByteArray &dgram)
    \internal

    If this DtlsCryptograph is in the QDtls::HandshakeState::HandshakeComplete state, this function
    encrypts \a dgram and writes this encrypted data into \a socket.

    Returns the number of bytes (of \a dgram) written, or -1 in case of error. This function should
    set the error code and description if some error was encountered.

    \sa decryptDatagram()
*/

/*!
    \fn QByteArray DtlsCryptograph::decryptDatagram(QUdpSocket *socket, const QByteArray &dgram)
    \internal

    If this DtlsCryptograph is in the QDtls::HandshakeState::HandshakeComplete state, decrypts \a dgram.
    The use of \a socket is implementation-specific. This function should return an empty byte array
    and set the error code and description if some error was encountered.
*/

#endif // QT_CONFIG(dtls)
#endif // QT_CONFIG(ssl)

} // namespace QTlsPrivate

#if QT_CONFIG(ssl)
/*!
    \internal
*/
Q_NETWORK_EXPORT void qt_ForceTlsSecurityLevel()
{
    if (auto *backend = QSslSocketPrivate::tlsBackendInUse())
        backend->forceAutotestSecurityLevel();
}

#endif // QT_CONFIG(ssl)

QT_END_NAMESPACE

#include "moc_qtlsbackend_p.cpp"