485void QSslSocket::connectToHostEncrypted(
const QString &hostName, quint16 port, OpenMode mode, NetworkLayerProtocol protocol)
488 if (d->state == ConnectedState || d->state == ConnectingState) {
490 "QSslSocket::connectToHostEncrypted() called when already connecting/connected");
494 if (!supportsSsl()) {
495 qCWarning(lcSsl,
"QSslSocket::connectToHostEncrypted: TLS initialization failed");
496 d->setErrorAndEmit(QAbstractSocket::SslInternalError, tr(
"TLS initialization failed"));
500 if (!d->verifyProtocolSupported(
"QSslSocket::connectToHostEncrypted:"))
504 d->autoStartHandshake =
true;
505 d->initialized =
true;
509 connectToHost(hostName, port, mode, protocol);
523void QSslSocket::connectToHostEncrypted(
const QString &hostName, quint16 port,
524 const QString &sslPeerName, OpenMode mode,
525 NetworkLayerProtocol protocol)
528 if (d->state == ConnectedState || d->state == ConnectingState) {
530 "QSslSocket::connectToHostEncrypted() called when already connecting/connected");
534 if (!supportsSsl()) {
535 qCWarning(lcSsl,
"QSslSocket::connectToHostEncrypted: TLS initialization failed");
536 d->setErrorAndEmit(QAbstractSocket::SslInternalError, tr(
"TLS initialization failed"));
541 d->autoStartHandshake =
true;
542 d->initialized =
true;
543 d->verificationPeerName = sslPeerName;
547 connectToHost(hostName, port, mode, protocol);
562bool QSslSocket::setSocketDescriptor(qintptr socketDescriptor, SocketState state, OpenMode openMode)
565#ifdef QSSLSOCKET_DEBUG
566 qCDebug(lcSsl) <<
"QSslSocket::setSocketDescriptor(" << socketDescriptor <<
','
567 << state <<
',' << openMode <<
')';
570 d->createPlainSocket(openMode);
571 bool retVal = d->plainSocket->setSocketDescriptor(socketDescriptor, state, openMode);
572 d->cachedSocketDescriptor = d->plainSocket->socketDescriptor();
573 d->setError(d->plainSocket->error(), d->plainSocket->errorString());
574 setSocketState(state);
575 setOpenMode(openMode);
576 setLocalPort(d->plainSocket->localPort());
577 setLocalAddress(d->plainSocket->localAddress());
578 setPeerPort(d->plainSocket->peerPort());
579 setPeerAddress(d->plainSocket->peerAddress());
580 setPeerName(d->plainSocket->peerName());
581 d->readChannelCount = d->plainSocket->readChannelCount();
582 d->writeChannelCount = d->plainSocket->writeChannelCount();
959void QSslSocket::setSslConfiguration(
const QSslConfiguration &configuration)
962 d->configuration.localCertificateChain = configuration.localCertificateChain();
963 d->configuration.privateKey = configuration.privateKey();
964 d->configuration.ciphers = configuration.ciphers();
965 d->configuration.ellipticCurves = configuration.ellipticCurves();
966 d->configuration.preSharedKeyIdentityHint = configuration.preSharedKeyIdentityHint();
967 d->configuration.dhParams = configuration.diffieHellmanParameters();
968 d->configuration.caCertificates = configuration.caCertificates();
969 d->configuration.peerVerifyDepth = configuration.peerVerifyDepth();
970 d->configuration.peerVerifyMode = configuration.peerVerifyMode();
971 d->configuration.protocol = configuration.protocol();
972 d->configuration.backendConfig = configuration.backendConfiguration();
973 d->configuration.sslOptions = configuration.d->sslOptions;
974 d->configuration.sslSession = configuration.sessionTicket();
975 d->configuration.sslSessionTicketLifeTimeHint = configuration.sessionTicketLifeTimeHint();
976 d->configuration.nextAllowedProtocols = configuration.allowedNextProtocols();
977 d->configuration.nextNegotiatedProtocol = configuration.nextNegotiatedProtocol();
978 d->configuration.nextProtocolNegotiationStatus = configuration.nextProtocolNegotiationStatus();
979 d->configuration.keyingMaterial = configuration.keyingMaterial();
981 d->configuration.ocspStaplingEnabled = configuration.ocspStaplingEnabled();
983#if QT_CONFIG(openssl)
984 d->configuration.reportFromCallback = configuration.handshakeMustInterruptOnError();
985 d->configuration.missingCertIsFatal = configuration.missingCertificateIsFatal();
990 if (!configuration.d->allowRootCertOnDemandLoading) {
991 d->allowRootCertOnDemandLoading =
false;
992 d->configuration.allowRootCertOnDemandLoading =
false;
1228void QSslSocket::setPrivateKey(
const QString &fileName, QSsl::KeyAlgorithm algorithm,
1229 QSsl::EncodingFormat format,
const QByteArray &passPhrase)
1231 QFile file(fileName);
1232 if (!file.open(QIODevice::ReadOnly)) {
1233 qCWarning(lcSsl,
"QSslSocket::setPrivateKey: Couldn't open file for reading");
1237 QSslKey key(file.readAll(), algorithm, format, QSsl::PrivateKey, passPhrase);
1239 qCWarning(lcSsl,
"QSslSocket::setPrivateKey: "
1240 "The specified file does not contain a valid key");
1245 d->configuration.privateKey = key;
1295bool QSslSocket::waitForEncrypted(
int msecs)
1298 if (!d->plainSocket || d->connectionEncrypted)
1300 if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1302 if (!d->verifyProtocolSupported(
"QSslSocket::waitForEncrypted:"))
1305 QElapsedTimer stopWatch;
1308 if (d->plainSocket->state() != QAbstractSocket::ConnectedState) {
1310 if (!d->plainSocket->waitForConnected(msecs))
1314 while (!d->connectionEncrypted) {
1316 if (d->mode == UnencryptedMode)
1317 startClientEncryption();
1320 if (!d->plainSocket->waitForReadyRead(qt_subtract_from_timeout(msecs, stopWatch.elapsed())))
1323 return d->connectionEncrypted;
1329bool QSslSocket::waitForReadyRead(
int msecs)
1332 if (!d->plainSocket)
1334 if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1335 return d->plainSocket->waitForReadyRead(msecs);
1341 bool readyReadEmitted =
false;
1342 bool *previousReadyReadEmittedPointer = d->readyReadEmittedPointer;
1343 d->readyReadEmittedPointer = &readyReadEmitted;
1345 QElapsedTimer stopWatch;
1348 if (!d->connectionEncrypted) {
1350 if (!waitForEncrypted(msecs)) {
1351 d->readyReadEmittedPointer = previousReadyReadEmittedPointer;
1356 if (!d->writeBuffer.isEmpty()) {
1363 while (!readyReadEmitted &&
1364 d->plainSocket->waitForReadyRead(qt_subtract_from_timeout(msecs, stopWatch.elapsed()))) {
1367 d->readyReadEmittedPointer = previousReadyReadEmittedPointer;
1368 return readyReadEmitted;
1374bool QSslSocket::waitForBytesWritten(
int msecs)
1377 if (!d->plainSocket)
1379 if (d->mode == UnencryptedMode)
1380 return d->plainSocket->waitForBytesWritten(msecs);
1382 QElapsedTimer stopWatch;
1385 if (!d->connectionEncrypted) {
1387 if (!waitForEncrypted(msecs))
1390 if (!d->writeBuffer.isEmpty()) {
1395 return d->plainSocket->waitForBytesWritten(qt_subtract_from_timeout(msecs, stopWatch.elapsed()));
1405bool QSslSocket::waitForDisconnected(
int msecs)
1410 if (state() == UnconnectedState) {
1411 qCWarning(lcSsl,
"QSslSocket::waitForDisconnected() is not allowed in UnconnectedState");
1415 if (!d->plainSocket)
1418 if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1419 return d->plainSocket->waitForDisconnected(msecs);
1421 QElapsedTimer stopWatch;
1424 if (!d->connectionEncrypted) {
1426 if (!waitForEncrypted(msecs))
1431 if (!d->writeBuffer.isEmpty())
1437 if (state() == UnconnectedState)
1440 bool retVal = d->plainSocket->waitForDisconnected(qt_subtract_from_timeout(msecs, stopWatch.elapsed()));
1442 setSocketState(d->plainSocket->state());
1443 d->setError(d->plainSocket->error(), d->plainSocket->errorString());
1702void QSslSocket::startClientEncryption()
1705 if (d->mode != UnencryptedMode) {
1707 "QSslSocket::startClientEncryption: cannot start handshake on non-plain connection");
1710 if (state() != ConnectedState) {
1712 "QSslSocket::startClientEncryption: cannot start handshake when not connected");
1716 if (!supportsSsl()) {
1717 qCWarning(lcSsl,
"QSslSocket::startClientEncryption: TLS initialization failed");
1718 d->setErrorAndEmit(QAbstractSocket::SslInternalError, tr(
"TLS initialization failed"));
1722 if (!d->verifyProtocolSupported(
"QSslSocket::startClientEncryption:"))
1725#ifdef QSSLSOCKET_DEBUG
1726 qCDebug(lcSsl) <<
"QSslSocket::startClientEncryption()";
1728 d->mode = SslClientMode;
1729 emit modeChanged(d->mode);
1730 d->startClientEncryption();
1855void QSslSocket::connectToHost(
const QString &hostName, quint16 port, OpenMode openMode, NetworkLayerProtocol protocol)
1858 d->preferredNetworkLayerProtocol = protocol;
1859 if (!d->initialized)
1861 d->initialized =
false;
1863#ifdef QSSLSOCKET_DEBUG
1864 qCDebug(lcSsl) <<
"QSslSocket::connectToHost("
1865 << hostName <<
',' << port <<
',' << openMode <<
')';
1867 if (!d->plainSocket) {
1868#ifdef QSSLSOCKET_DEBUG
1869 qCDebug(lcSsl) <<
"\tcreating internal plain socket";
1871 d->createPlainSocket(openMode);
1873#ifndef QT_NO_NETWORKPROXY
1874 d->plainSocket->setProtocolTag(d->protocolTag);
1875 d->plainSocket->setProxy(proxy());
1877 QIODevice::open(openMode);
1878 d->readChannelCount = d->writeChannelCount = 0;
1879 d->plainSocket->connectToHost(hostName, port, openMode, d->preferredNetworkLayerProtocol);
1880 d->cachedSocketDescriptor = d->plainSocket->socketDescriptor();
1886void QSslSocket::disconnectFromHost()
1889#ifdef QSSLSOCKET_DEBUG
1890 qCDebug(lcSsl) <<
"QSslSocket::disconnectFromHost()";
1892 if (!d->plainSocket)
1894 if (d->state == UnconnectedState)
1896 if (d->mode == UnencryptedMode && !d->autoStartHandshake) {
1897 d->plainSocket->disconnectFromHost();
1900 if (d->state <= ConnectingState) {
1901 d->pendingClose =
true;
1906 if (
auto *backend = d->backend.get())
1907 backend->cancelCAFetch();
1910 if (d->state != ClosingState) {
1911 d->state = ClosingState;
1912 emit stateChanged(d->state);
1915 if (!d->writeBuffer.isEmpty()) {
1916 d->pendingClose =
true;
1920 if (d->mode == UnencryptedMode) {
1921 d->plainSocket->disconnectFromHost();
1923 d->disconnectFromHost();
1930qint64 QSslSocket::readData(
char *data, qint64 maxlen)
1933 qint64 readBytes = 0;
1935 if (d->mode == UnencryptedMode && !d->autoStartHandshake) {
1936 readBytes = d->plainSocket->read(data, maxlen);
1937#ifdef QSSLSOCKET_DEBUG
1938 qCDebug(lcSsl) <<
"QSslSocket::readData(" << (
void *)data <<
',' << maxlen <<
") =="
1943 if (d->plainSocket->bytesAvailable() || d->hasUndecryptedData())
1944 QMetaObject::invokeMethod(
this,
"_q_flushReadBuffer", Qt::QueuedConnection);
1945 else if (d->state != QAbstractSocket::ConnectedState)
1946 return maxlen ? qint64(-1) : qint64(0);
1980QSslSocketPrivate::QSslSocketPrivate()
1981 : initialized(
false)
1982 , mode(QSslSocket::UnencryptedMode)
1983 , autoStartHandshake(
false)
1984 , connectionEncrypted(
false)
1985 , ignoreAllSslErrors(
false)
1986 , readyReadEmittedPointer(
nullptr)
1987 , allowRootCertOnDemandLoading(
true)
1988 , plainSocket(
nullptr)
1990 , flushTriggered(
false)
1992 QSslConfigurationPrivate::deepCopyDefaultConfiguration(&configuration);
1995 if (!configuration.allowRootCertOnDemandLoading)
1996 allowRootCertOnDemandLoading =
false;
1998 const auto *tlsBackend = tlsBackendInUse();
2000 qCWarning(lcSsl,
"No TLS backend is available");
2003 backend.reset(tlsBackend->createTlsCryptograph());
2004 if (!backend.get()) {
2005 qCWarning(lcSsl) <<
"The backend named" << tlsBackend->backendName()
2006 <<
"does not support TLS";
2220void QSslSocketPrivate::setDefaultCaCertificates(
const QList<QSslCertificate> &certs)
2222 QSslSocketPrivate::ensureInitialized();
2223 QMutexLocker locker(&globalData()->mutex);
2224 globalData()->config.detach();
2225 globalData()->config->caCertificates = certs;
2226 globalData()->dtlsConfig.detach();
2227 globalData()->dtlsConfig->caCertificates = certs;
2230 s_loadRootCertsOnDemand =
false;
2236void QSslSocketPrivate::addDefaultCaCertificate(
const QSslCertificate &cert)
2238 QSslSocketPrivate::ensureInitialized();
2239 QMutexLocker locker(&globalData()->mutex);
2240 if (globalData()->config->caCertificates.contains(cert))
2242 globalData()->config.detach();
2243 globalData()->config->caCertificates += cert;
2244 globalData()->dtlsConfig.detach();
2245 globalData()->dtlsConfig->caCertificates += cert;
2251void QSslSocketPrivate::addDefaultCaCertificates(
const QList<QSslCertificate> &certs)
2253 QSslSocketPrivate::ensureInitialized();
2254 QMutexLocker locker(&globalData()->mutex);
2255 globalData()->config.detach();
2256 globalData()->config->caCertificates += certs;
2257 globalData()->dtlsConfig.detach();
2258 globalData()->dtlsConfig->caCertificates += certs;
2287void QSslConfigurationPrivate::deepCopyDefaultConfiguration(QSslConfigurationPrivate *ptr)
2289 QSslSocketPrivate::ensureInitialized();
2290 QMutexLocker locker(&globalData()->mutex);
2291 const QSslConfigurationPrivate *global = globalData()->config.constData();
2296 ptr->ref.storeRelaxed(1);
2297 ptr->peerCertificate = global->peerCertificate;
2298 ptr->peerCertificateChain = global->peerCertificateChain;
2299 ptr->localCertificateChain = global->localCertificateChain;
2300 ptr->privateKey = global->privateKey;
2301 ptr->sessionCipher = global->sessionCipher;
2302 ptr->sessionProtocol = global->sessionProtocol;
2303 ptr->ciphers = global->ciphers;
2304 ptr->caCertificates = global->caCertificates;
2305 ptr->allowRootCertOnDemandLoading = global->allowRootCertOnDemandLoading;
2306 ptr->protocol = global->protocol;
2307 ptr->peerVerifyMode = global->peerVerifyMode;
2308 ptr->peerVerifyDepth = global->peerVerifyDepth;
2309 ptr->sslOptions = global->sslOptions;
2310 ptr->ellipticCurves = global->ellipticCurves;
2311 ptr->backendConfig = global->backendConfig;
2313 ptr->dtlsCookieEnabled = global->dtlsCookieEnabled;
2316 ptr->ocspStaplingEnabled = global->ocspStaplingEnabled;
2318#if QT_CONFIG(openssl)
2319 ptr->reportFromCallback = global->reportFromCallback;
2320 ptr->missingCertIsFatal = global->missingCertIsFatal;
2338void QSslConfigurationPrivate::setDefaultDtlsConfiguration(
const QSslConfiguration &configuration)
2340 QSslSocketPrivate::ensureInitialized();
2341 QMutexLocker locker(&globalData()->mutex);
2342 if (globalData()->dtlsConfig == configuration.d)
2345 globalData()->dtlsConfig =
const_cast<QSslConfigurationPrivate*>(configuration.d.constData());
2351void QSslSocketPrivate::createPlainSocket(QIODevice::OpenMode openMode)
2354 q->setOpenMode(openMode);
2355 q->setSocketState(QAbstractSocket::UnconnectedState);
2356 q->setSocketError(QAbstractSocket::UnknownSocketError);
2358 q->setLocalAddress(QHostAddress());
2360 q->setPeerAddress(QHostAddress());
2361 q->setPeerName(QString());
2363 plainSocket =
new QTcpSocket(q);
2364 q->connect(plainSocket, SIGNAL(connected()),
2365 q, SLOT(_q_connectedSlot()),
2366 Qt::DirectConnection);
2367 q->connect(plainSocket, SIGNAL(hostFound()),
2368 q, SLOT(_q_hostFoundSlot()),
2369 Qt::DirectConnection);
2370 q->connect(plainSocket, SIGNAL(disconnected()),
2371 q, SLOT(_q_disconnectedSlot()),
2372 Qt::DirectConnection);
2373 q->connect(plainSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
2374 q, SLOT(_q_stateChangedSlot(QAbstractSocket::SocketState)),
2375 Qt::DirectConnection);
2376 q->connect(plainSocket, SIGNAL(errorOccurred(QAbstractSocket::SocketError)),
2377 q, SLOT(_q_errorSlot(QAbstractSocket::SocketError)),
2378 Qt::DirectConnection);
2379 q->connect(plainSocket, SIGNAL(readyRead()),
2380 q, SLOT(_q_readyReadSlot()),
2381 Qt::DirectConnection);
2382 q->connect(plainSocket, SIGNAL(channelReadyRead(
int)),
2383 q, SLOT(_q_channelReadyReadSlot(
int)),
2384 Qt::DirectConnection);
2385 q->connect(plainSocket, SIGNAL(bytesWritten(qint64)),
2386 q, SLOT(_q_bytesWrittenSlot(qint64)),
2387 Qt::DirectConnection);
2388 q->connect(plainSocket, SIGNAL(channelBytesWritten(
int,qint64)),
2389 q, SLOT(_q_channelBytesWrittenSlot(
int,qint64)),
2390 Qt::DirectConnection);
2391 q->connect(plainSocket, SIGNAL(readChannelFinished()),
2392 q, SLOT(_q_readChannelFinishedSlot()),
2393 Qt::DirectConnection);
2394#ifndef QT_NO_NETWORKPROXY
2395 q->connect(plainSocket, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
2396 q, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
2400 writeBuffer.clear();
2401 connectionEncrypted =
false;
2402 configuration.peerCertificate.clear();
2403 configuration.peerCertificateChain.clear();
2404 mode = QSslSocket::UnencryptedMode;
2405 q->setReadBufferSize(readBufferMaxSize);
2432bool QSslSocketPrivate::bind(
const QHostAddress &address, quint16 port, QAbstractSocket::BindMode mode,
2433 const QNetworkInterface *iface)
2439 initialized =
false;
2441#ifdef QSSLSOCKET_DEBUG
2442 qCDebug(lcSsl) <<
"QSslSocket::bind(" << address <<
',' << port <<
',' << mode <<
')';
2445#ifdef QSSLSOCKET_DEBUG
2446 qCDebug(lcSsl) <<
"\tcreating internal plain socket";
2448 createPlainSocket(QIODevice::ReadWrite);
2450 bool ret = plainSocket->bind(address, port, mode);
2451 localPort = plainSocket->localPort();
2452 localAddress = plainSocket->localAddress();
2453 cachedSocketDescriptor = plainSocket->socketDescriptor();
2454 readChannelCount = writeChannelCount = 0;
2461void QSslSocketPrivate::_q_connectedSlot()
2464 q->setLocalPort(plainSocket->localPort());
2465 q->setLocalAddress(plainSocket->localAddress());
2466 q->setPeerPort(plainSocket->peerPort());
2467 q->setPeerAddress(plainSocket->peerAddress());
2468 q->setPeerName(plainSocket->peerName());
2469 cachedSocketDescriptor = plainSocket->socketDescriptor();
2470 readChannelCount = plainSocket->readChannelCount();
2471 writeChannelCount = plainSocket->writeChannelCount();
2473#ifdef QSSLSOCKET_DEBUG
2474 qCDebug(lcSsl) <<
"QSslSocket::_q_connectedSlot()";
2475 qCDebug(lcSsl) <<
"\tstate =" << q->state();
2476 qCDebug(lcSsl) <<
"\tpeer =" << q->peerName() << q->peerAddress() << q->peerPort();
2477 qCDebug(lcSsl) <<
"\tlocal =" << QHostInfo::fromName(q->localAddress().toString()).hostName()
2478 << q->localAddress() << q->localPort();
2481 if (autoStartHandshake)
2482 q->startClientEncryption();
2484 emit q->connected();
2486 if (pendingClose && !autoStartHandshake) {
2487 pendingClose =
false;
2488 q->disconnectFromHost();
3019bool QSslSocketPrivate::isMatchingHostname(
const QSslCertificate &cert,
const QString &peerName)
3021 QHostAddress hostAddress(peerName);
3022 if (!hostAddress.isNull()) {
3023 const auto subjectAlternativeNames = cert.subjectAlternativeNames();
3024 const auto ipAddresses = subjectAlternativeNames.equal_range(QSsl::AlternativeNameEntryType::IpAddressEntry);
3026 for (
auto it = ipAddresses.first; it != ipAddresses.second; it++) {
3027 if (QHostAddress(*it).isEqual(hostAddress, QHostAddress::StrictConversion))
3032 const QString lowerPeerName = QString::fromLatin1(QUrl::toAce(peerName));
3033 const QStringList commonNames = cert.subjectInfo(QSslCertificate::CommonName);
3035 for (
const QString &commonName : commonNames) {
3036 if (isMatchingHostname(commonName, lowerPeerName))
3040 const auto subjectAlternativeNames = cert.subjectAlternativeNames();
3041 const auto altNames = subjectAlternativeNames.equal_range(QSsl::DnsEntry);
3042 for (
auto it = altNames.first; it != altNames.second; ++it) {
3043 if (isMatchingHostname(*it, lowerPeerName))
3054bool QSslSocketPrivate::isMatchingHostname(
const QString &cn,
const QString &hostname)
3056 qsizetype wildcard = cn.indexOf(u'*');
3060 return QLatin1StringView(QUrl::toAce(cn)) == hostname;
3062 qsizetype firstCnDot = cn.indexOf(u'.');
3063 qsizetype secondCnDot = cn.indexOf(u'.', firstCnDot+1);
3066 if ((-1 == secondCnDot) || (secondCnDot+1 >= cn.size()))
3070 if (wildcard+1 != firstCnDot)
3074 if (cn.lastIndexOf(u'*') != wildcard)
3079 if (cn.startsWith(
"xn--"_L1, Qt::CaseInsensitive))
3083 if (wildcard && QStringView{hostname}.left(wildcard).compare(QStringView{cn}.left(wildcard), Qt::CaseInsensitive) != 0)
3087 qsizetype hnDot = hostname.indexOf(u'.');
3088 if (QStringView{hostname}.mid(hnDot + 1) != QStringView{cn}.mid(firstCnDot + 1)
3089 && QStringView{hostname}.mid(hnDot + 1) != QLatin1StringView(QUrl::toAce(cn.mid(firstCnDot + 1)))) {
3094 QHostAddress addr(hostname);
3105QTlsBackend *QSslSocketPrivate::tlsBackendInUse()
3107 const QMutexLocker locker(&backendMutex);
3111 if (!activeBackendName.size())
3112 activeBackendName = QTlsBackend::defaultBackendName();
3114 if (!activeBackendName.size()) {
3115 qCWarning(lcSsl,
"No functional TLS backend was found");
3119 tlsBackend = QTlsBackend::findBackend(activeBackendName);
3121 QObject::connect(tlsBackend, &QObject::destroyed, tlsBackend, [] {
3122 const QMutexLocker locker(&backendMutex);
3123 tlsBackend =
nullptr;
3125 Qt::DirectConnection);