Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qsslsocket.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// Copyright (C) 2014 BlackBerry Limited. All rights reserved.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4// Qt-Security score:significant reason:default
5
6
7//#define QSSLSOCKET_DEBUG
8
9/*!
10 \class QSslSocket
11 \brief The QSslSocket class provides an SSL encrypted socket for both
12 clients and servers.
13 \since 4.3
14
15 \reentrant
16 \ingroup network
17 \ingroup ssl
18 \inmodule QtNetwork
19
20 QSslSocket establishes a secure, encrypted TCP connection you can
21 use for transmitting encrypted data. It can operate in both client
22 and server mode, and it supports modern TLS protocols, including
23 TLS 1.3. By default, QSslSocket uses only TLS protocols
24 which are considered to be secure (QSsl::SecureProtocols), but you can
25 change the TLS protocol by calling setProtocol() as long as you do
26 it before the handshake has started.
27
28 SSL encryption operates on top of the existing TCP stream after
29 the socket enters the ConnectedState. There are two simple ways to
30 establish a secure connection using QSslSocket: With an immediate
31 SSL handshake, or with a delayed SSL handshake occurring after the
32 connection has been established in unencrypted mode.
33
34 The most common way to use QSslSocket is to construct an object
35 and start a secure connection by calling connectToHostEncrypted().
36 This method starts an immediate SSL handshake once the connection
37 has been established.
38
39 \snippet code/src_network_ssl_qsslsocket.cpp 0
40
41 As with a plain QTcpSocket, QSslSocket enters the HostLookupState,
42 ConnectingState, and finally the ConnectedState, if the connection
43 is successful. The handshake then starts automatically, and if it
44 succeeds, the encrypted() signal is emitted to indicate the socket
45 has entered the encrypted state and is ready for use.
46
47 Note that data can be written to the socket immediately after the
48 return from connectToHostEncrypted() (i.e., before the encrypted()
49 signal is emitted). The data is queued in QSslSocket until after
50 the encrypted() signal is emitted.
51
52 An example of using the delayed SSL handshake to secure an
53 existing connection is the case where an SSL server secures an
54 incoming connection. Suppose you create an SSL server class as a
55 subclass of QTcpServer. You would override
56 QTcpServer::incomingConnection() with something like the example
57 below, which first constructs an instance of QSslSocket and then
58 calls setSocketDescriptor() to set the new socket's descriptor to
59 the existing one passed in. It then initiates the SSL handshake
60 by calling startServerEncryption().
61
62 \snippet code/src_network_ssl_qsslsocket.cpp 1
63
64 If an error occurs, QSslSocket emits the sslErrors() signal. In this
65 case, if no action is taken to ignore the error(s), the connection
66 is dropped. To continue, despite the occurrence of an error, you
67 can call ignoreSslErrors(), either from within this slot after the
68 error occurs, or any time after construction of the QSslSocket and
69 before the connection is attempted. This will allow QSslSocket to
70 ignore the errors it encounters when establishing the identity of
71 the peer. Ignoring errors during an SSL handshake should be used
72 with caution, since a fundamental characteristic of secure
73 connections is that they should be established with a successful
74 handshake.
75
76 Once encrypted, you use QSslSocket as a regular QTcpSocket. When
77 readyRead() is emitted, you can call read(), canReadLine() and
78 readLine(), or getChar() to read decrypted data from QSslSocket's
79 internal buffer, and you can call write() or putChar() to write
80 data back to the peer. QSslSocket will automatically encrypt the
81 written data for you, and emit encryptedBytesWritten() once
82 the data has been written to the peer.
83
84 As a convenience, QSslSocket supports QTcpSocket's blocking
85 functions waitForConnected(), waitForReadyRead(),
86 waitForBytesWritten(), and waitForDisconnected(). It also provides
87 waitForEncrypted(), which will block the calling thread until an
88 encrypted connection has been established.
89
90 \snippet code/src_network_ssl_qsslsocket.cpp 2
91
92 QSslSocket provides an extensive, easy-to-use API for handling
93 cryptographic ciphers, private keys, and local, peer, and
94 Certification Authority (CA) certificates. It also provides an API
95 for handling errors that occur during the handshake phase.
96
97 The following features can also be customized:
98
99 \list
100 \li The socket's cryptographic cipher suite can be customized before
101 the handshake phase with QSslConfiguration::setCiphers().
102 \li The socket's local certificate and private key can be customized
103 before the handshake phase with setLocalCertificate() and
104 setPrivateKey().
105 \li The CA certificate database can be extended and customized with
106 QSslConfiguration::addCaCertificate(),
107 QSslConfiguration::addCaCertificates().
108 \endlist
109
110 To extend the list of \e default CA certificates used by the SSL sockets
111 during the SSL handshake you must update the default configuration, as
112 in the snippet below:
113
114 \code
115 QList<QSslCertificate> certificates = getCertificates();
116 QSslConfiguration configuration = QSslConfiguration::defaultConfiguration();
117 configuration.addCaCertificates(certificates);
118 QSslConfiguration::setDefaultConfiguration(configuration);
119 \endcode
120
121 \note If available, root certificates on Unix (excluding \macos) will be
122 loaded on demand from the standard certificate directories. If you do not
123 want to load root certificates on demand, you need to call either
124 QSslConfiguration::defaultConfiguration().setCaCertificates() before the first
125 SSL handshake is made in your application (for example, via passing
126 QSslSocket::systemCaCertificates() to it), or call
127 QSslConfiguration::defaultConfiguration()::setCaCertificates() on your QSslSocket instance
128 prior to the SSL handshake.
129
130 For more information about ciphers and certificates, refer to QSslCipher and
131 QSslCertificate.
132
133 This product includes software developed by the OpenSSL Project
134 for use in the OpenSSL Toolkit (\l{http://www.openssl.org/}).
135
136 \note Be aware of the difference between the bytesWritten() signal and
137 the encryptedBytesWritten() signal. For a QTcpSocket, bytesWritten()
138 will get emitted as soon as data has been written to the TCP socket.
139 For a QSslSocket, bytesWritten() will get emitted when the data
140 is being encrypted and encryptedBytesWritten()
141 will get emitted as soon as data has been written to the TCP socket.
142
143 \sa QSslCertificate, QSslCipher, QSslError
144*/
145
146/*!
147 \enum QSslSocket::SslMode
148
149 Describes the connection modes available for QSslSocket.
150
151 \value UnencryptedMode The socket is unencrypted. Its
152 behavior is identical to QTcpSocket.
153
154 \value SslClientMode The socket is a client-side SSL socket.
155 It is either already encrypted, or it is in the SSL handshake
156 phase (see QSslSocket::isEncrypted()).
157
158 \value SslServerMode The socket is a server-side SSL socket.
159 It is either already encrypted, or it is in the SSL handshake
160 phase (see QSslSocket::isEncrypted()).
161*/
162
163/*!
164 \enum QSslSocket::PeerVerifyMode
165 \since 4.4
166
167 Describes the peer verification modes for QSslSocket. The default mode is
168 AutoVerifyPeer, which selects an appropriate mode depending on the
169 socket's QSocket::SslMode.
170
171 \value VerifyNone QSslSocket will not request a certificate from the
172 peer. You can set this mode if you are not interested in the identity of
173 the other side of the connection. The connection will still be encrypted,
174 and your socket will still send its local certificate to the peer if it's
175 requested.
176
177 \value QueryPeer QSslSocket will request a certificate from the peer, but
178 does not require this certificate to be valid. This is useful when you
179 want to display peer certificate details to the user without affecting the
180 actual SSL handshake. This mode is the default for servers.
181 Note: In Schannel this value acts the same as VerifyNone.
182
183 \value VerifyPeer QSslSocket will request a certificate from the peer
184 during the SSL handshake phase, and requires that this certificate is
185 valid. On failure, QSslSocket will emit the QSslSocket::sslErrors()
186 signal. This mode is the default for clients.
187
188 \value AutoVerifyPeer QSslSocket will automatically use QueryPeer for
189 server sockets and VerifyPeer for client sockets.
190
191 \sa QSslSocket::peerVerifyMode()
192*/
193
194/*!
195 \fn void QSslSocket::encrypted()
196
197 This signal is emitted when QSslSocket enters encrypted mode. After this
198 signal has been emitted, QSslSocket::isEncrypted() will return true, and
199 all further transmissions on the socket will be encrypted.
200
201 \sa QSslSocket::connectToHostEncrypted(), QSslSocket::isEncrypted()
202*/
203
204/*!
205 \fn void QSslSocket::modeChanged(QSslSocket::SslMode mode)
206
207 This signal is emitted when QSslSocket changes from \l
208 QSslSocket::UnencryptedMode to either \l QSslSocket::SslClientMode or \l
209 QSslSocket::SslServerMode. \a mode is the new mode.
210
211 \sa QSslSocket::mode()
212*/
213
214/*!
215 \fn void QSslSocket::encryptedBytesWritten(qint64 written)
216 \since 4.4
217
218 This signal is emitted when QSslSocket writes its encrypted data to the
219 network. The \a written parameter contains the number of bytes that were
220 successfully written.
221
222 \sa QIODevice::bytesWritten()
223*/
224
225/*!
226 \fn void QSslSocket::peerVerifyError(const QSslError &error)
227 \since 4.4
228
229 QSslSocket can emit this signal several times during the SSL handshake,
230 before encryption has been established, to indicate that an error has
231 occurred while establishing the identity of the peer. The \a error is
232 usually an indication that QSslSocket is unable to securely identify the
233 peer.
234
235 This signal provides you with an early indication when something's wrong.
236 By connecting to this signal, you can manually choose to tear down the
237 connection from inside the connected slot before the handshake has
238 completed. If no action is taken, QSslSocket will proceed to emitting
239 QSslSocket::sslErrors().
240
241 \sa sslErrors()
242*/
243
244/*!
245 \fn void QSslSocket::sslErrors(const QList<QSslError> &errors);
246
247 QSslSocket emits this signal after the SSL handshake to indicate that one
248 or more errors have occurred while establishing the identity of the
249 peer. The errors are usually an indication that QSslSocket is unable to
250 securely identify the peer. Unless any action is taken, the connection
251 will be dropped after this signal has been emitted.
252
253 If you want to continue connecting despite the errors that have occurred,
254 you must call QSslSocket::ignoreSslErrors() from inside a slot connected to
255 this signal. If you need to access the error list at a later point, you
256 can call sslHandshakeErrors().
257
258 \a errors contains one or more errors that prevent QSslSocket from
259 verifying the identity of the peer.
260
261 \note You cannot use Qt::QueuedConnection when connecting to this signal,
262 or calling QSslSocket::ignoreSslErrors() will have no effect.
263
264 \sa peerVerifyError()
265*/
266
267/*!
268 \fn void QSslSocket::preSharedKeyAuthenticationRequired(QSslPreSharedKeyAuthenticator *authenticator)
269 \since 5.5
270
271 QSslSocket emits this signal when it negotiates a PSK ciphersuite, and
272 therefore a PSK authentication is then required.
273
274 When using PSK, the client must send to the server a valid identity and a
275 valid pre shared key, in order for the SSL handshake to continue.
276 Applications can provide this information in a slot connected to this
277 signal, by filling in the passed \a authenticator object according to their
278 needs.
279
280 \note Ignoring this signal, or failing to provide the required credentials,
281 will cause the handshake to fail, and therefore the connection to be aborted.
282
283 \note The \a authenticator object is owned by the socket and must not be
284 deleted by the application.
285
286 \sa QSslPreSharedKeyAuthenticator
287*/
288
289/*!
290 \fn void QSslSocket::alertSent(QSsl::AlertLevel level, QSsl::AlertType type, const QString &description)
291
292 QSslSocket emits this signal if an alert message was sent to a peer. \a level
293 describes if it was a warning or a fatal error. \a type gives the code
294 of the alert message. When a textual description of the alert message is
295 available, it is supplied in \a description.
296
297 \note This signal is mostly informational and can be used for debugging
298 purposes, normally it does not require any actions from the application.
299 \note Not all backends support this functionality.
300
301 \sa alertReceived(), QSsl::AlertLevel, QSsl::AlertType
302*/
303
304/*!
305 \fn void QSslSocket::alertReceived(QSsl::AlertLevel level, QSsl::AlertType type, const QString &description)
306
307 QSslSocket emits this signal if an alert message was received from a peer.
308 \a level tells if the alert was fatal or it was a warning. \a type is the
309 code explaining why the alert was sent. When a textual description of
310 the alert message is available, it is supplied in \a description.
311
312 \note The signal is mostly for informational and debugging purposes and does not
313 require any handling in the application. If the alert was fatal, underlying
314 backend will handle it and close the connection.
315 \note Not all backends support this functionality.
316
317 \sa alertSent(), QSsl::AlertLevel, QSsl::AlertType
318*/
319
320/*!
321 \fn void QSslSocket::handshakeInterruptedOnError(const QSslError &error)
322
323 QSslSocket emits this signal if a certificate verification error was
324 found and if early error reporting was enabled in QSslConfiguration.
325 An application is expected to inspect the \a error and decide if
326 it wants to continue the handshake, or abort it and send an alert message
327 to the peer. The signal-slot connection must be direct.
328
329 \sa continueInterruptedHandshake(), sslErrors(), QSslConfiguration::setHandshakeMustInterruptOnError()
330*/
331
332/*!
333 \fn void QSslSocket::newSessionTicketReceived()
334 \since 5.15
335
336 If TLS 1.3 protocol was negotiated during a handshake, QSslSocket
337 emits this signal after receiving NewSessionTicket message. Session
338 and session ticket's lifetime hint are updated in the socket's
339 configuration. The session can be used for session resumption (and
340 a shortened handshake) in future TLS connections.
341
342 \note This functionality enabled only with OpenSSL backend and requires
343 OpenSSL v 1.1.1 or above.
344
345 \sa QSslSocket::sslConfiguration(), QSslConfiguration::sessionTicket(), QSslConfiguration::sessionTicketLifeTimeHint()
346*/
347
348#include "qssl_p.h"
349#include "qsslsocket.h"
350#include "qsslcipher.h"
351#include "qocspresponse.h"
352#include "qtlsbackend_p.h"
354#include "qsslsocket_p.h"
355
356#include <QtCore/qdebug.h>
357#include <QtCore/qdir.h>
358#include <QtCore/qmutex.h>
359#include <QtCore/qurl.h>
360#include <QtCore/qelapsedtimer.h>
361#include <QtNetwork/qhostaddress.h>
362#include <QtNetwork/qhostinfo.h>
363
365
366using namespace Qt::StringLiterals;
367
368#ifdef Q_OS_VXWORKS
369constexpr auto isVxworks = true;
370#else
371constexpr auto isVxworks = false;
372#endif
373
392Q_GLOBAL_STATIC(QSslSocketGlobalData, globalData)
393
394/*!
395 Constructs a QSslSocket object. \a parent is passed to QObject's
396 constructor. The new socket's \l {QSslCipher} {cipher} suite is
397 set to the one returned by the static method defaultCiphers().
398*/
399QSslSocket::QSslSocket(QObject *parent)
400 : QTcpSocket(*new QSslSocketPrivate, parent)
401{
402 Q_D(QSslSocket);
403#ifdef QSSLSOCKET_DEBUG
404 qCDebug(lcSsl) << "QSslSocket::QSslSocket(" << parent << "), this =" << (void *)this;
405#endif
406 d->q_ptr = this;
407 d->init();
408}
409
410/*!
411 Destroys the QSslSocket.
412*/
413QSslSocket::~QSslSocket()
414{
415 Q_D(QSslSocket);
416#ifdef QSSLSOCKET_DEBUG
417 qCDebug(lcSsl) << "QSslSocket::~QSslSocket(), this =" << (void *)this;
418#endif
419 delete d->plainSocket;
420 d->plainSocket = nullptr;
421}
422
423/*!
424 \reimp
425
426 \since 5.0
427
428 Continues data transfer on the socket after it has been paused. If
429 "setPauseMode(QAbstractSocket::PauseOnSslErrors);" has been called on
430 this socket and a sslErrors() signal is received, calling this method
431 is necessary for the socket to continue.
432
433 \sa QAbstractSocket::pauseMode(), QAbstractSocket::setPauseMode()
434*/
435void QSslSocket::resume()
436{
437 Q_D(QSslSocket);
438 if (!d->paused)
439 return;
440 // continuing might emit signals, rather do this through the event loop
441 QMetaObject::invokeMethod(this, "_q_resumeImplementation", Qt::QueuedConnection);
442}
443
444/*!
445 Starts an encrypted connection to the device \a hostName on \a
446 port, using \a mode as the \l OpenMode. This is equivalent to
447 calling connectToHost() to establish the connection, followed by a
448 call to startClientEncryption(). The \a protocol parameter can be
449 used to specify which network protocol to use (eg. IPv4 or IPv6).
450
451 QSslSocket first enters the HostLookupState. Then, after entering
452 either the event loop or one of the waitFor...() functions, it
453 enters the ConnectingState, emits connected(), and then initiates
454 the SSL client handshake. At each state change, QSslSocket emits
455 signal stateChanged().
456
457 After initiating the SSL client handshake, if the identity of the
458 peer can't be established, signal sslErrors() is emitted. If you
459 want to ignore the errors and continue connecting, you must call
460 ignoreSslErrors(), either from inside a slot function connected to
461 the sslErrors() signal, or prior to entering encrypted mode. If
462 ignoreSslErrors() is not called, the connection is dropped, signal
463 disconnected() is emitted, and QSslSocket returns to the
464 UnconnectedState.
465
466 If the SSL handshake is successful, QSslSocket emits encrypted().
467
468 \snippet code/src_network_ssl_qsslsocket.cpp 3
469
470 \note The example above shows that text can be written to
471 the socket immediately after requesting the encrypted connection,
472 before the encrypted() signal has been emitted. In such cases, the
473 text is queued in the object and written to the socket \e after
474 the connection is established and the encrypted() signal has been
475 emitted.
476
477 The default for \a mode is \l ReadWrite.
478
479 If you want to create a QSslSocket on the server side of a connection, you
480 should instead call startServerEncryption() upon receiving the incoming
481 connection through QTcpServer.
482
483 \sa connectToHost(), startClientEncryption(), waitForConnected(), waitForEncrypted()
484*/
485void QSslSocket::connectToHostEncrypted(const QString &hostName, quint16 port, OpenMode mode, NetworkLayerProtocol protocol)
486{
487 Q_D(QSslSocket);
488 if (d->state == ConnectedState || d->state == ConnectingState) {
489 qCWarning(lcSsl,
490 "QSslSocket::connectToHostEncrypted() called when already connecting/connected");
491 return;
492 }
493
494 if (!supportsSsl()) {
495 qCWarning(lcSsl, "QSslSocket::connectToHostEncrypted: TLS initialization failed");
496 d->setErrorAndEmit(QAbstractSocket::SslInternalError, tr("TLS initialization failed"));
497 return;
498 }
499
500 if (!d->verifyProtocolSupported("QSslSocket::connectToHostEncrypted:"))
501 return;
502
503 d->init();
504 d->autoStartHandshake = true;
505 d->initialized = true;
506
507 // Note: When connecting to localhost, some platforms (e.g., HP-UX and some BSDs)
508 // establish the connection immediately (i.e., first attempt).
509 connectToHost(hostName, port, mode, protocol);
510}
511
512/*!
513 \since 4.6
514 \overload
515
516 In addition to the original behaviour of connectToHostEncrypted,
517 this overloaded method enables the usage of a different hostname
518 (\a sslPeerName) for the certificate validation instead of
519 the one used for the TCP connection (\a hostName).
520
521 \sa connectToHostEncrypted()
522*/
523void QSslSocket::connectToHostEncrypted(const QString &hostName, quint16 port,
524 const QString &sslPeerName, OpenMode mode,
525 NetworkLayerProtocol protocol)
526{
527 Q_D(QSslSocket);
528 if (d->state == ConnectedState || d->state == ConnectingState) {
529 qCWarning(lcSsl,
530 "QSslSocket::connectToHostEncrypted() called when already connecting/connected");
531 return;
532 }
533
534 if (!supportsSsl()) {
535 qCWarning(lcSsl, "QSslSocket::connectToHostEncrypted: TLS initialization failed");
536 d->setErrorAndEmit(QAbstractSocket::SslInternalError, tr("TLS initialization failed"));
537 return;
538 }
539
540 d->init();
541 d->autoStartHandshake = true;
542 d->initialized = true;
543 d->verificationPeerName = sslPeerName;
544
545 // Note: When connecting to localhost, some platforms (e.g., HP-UX and some BSDs)
546 // establish the connection immediately (i.e., first attempt).
547 connectToHost(hostName, port, mode, protocol);
548}
549
550/*!
551 Initializes QSslSocket with the native socket descriptor \a
552 socketDescriptor. Returns \c true if \a socketDescriptor is accepted
553 as a valid socket descriptor; otherwise returns \c false.
554 The socket is opened in the mode specified by \a openMode, and
555 enters the socket state specified by \a state.
556
557 \note It is not possible to initialize two sockets with the same
558 native socket descriptor.
559
560 \sa socketDescriptor()
561*/
562bool QSslSocket::setSocketDescriptor(qintptr socketDescriptor, SocketState state, OpenMode openMode)
563{
564 Q_D(QSslSocket);
565#ifdef QSSLSOCKET_DEBUG
566 qCDebug(lcSsl) << "QSslSocket::setSocketDescriptor(" << socketDescriptor << ','
567 << state << ',' << openMode << ')';
568#endif
569 if (!d->plainSocket)
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();
583 return retVal;
584}
585
586/*!
587 \since 4.6
588 Sets the given \a option to the value described by \a value.
589
590 \sa socketOption()
591*/
592void QSslSocket::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
593{
594 Q_D(QSslSocket);
595 if (d->plainSocket)
596 d->plainSocket->setSocketOption(option, value);
597}
598
599/*!
600 \since 4.6
601 Returns the value of the \a option option.
602
603 \sa setSocketOption()
604*/
605QVariant QSslSocket::socketOption(QAbstractSocket::SocketOption option)
606{
607 Q_D(QSslSocket);
608 if (d->plainSocket)
609 return d->plainSocket->socketOption(option);
610 else
611 return QVariant();
612}
613
614/*!
615 Returns the current mode for the socket; either UnencryptedMode, where
616 QSslSocket behaves identially to QTcpSocket, or one of SslClientMode or
617 SslServerMode, where the client is either negotiating or in encrypted
618 mode.
619
620 When the mode changes, QSslSocket emits modeChanged()
621
622 \sa SslMode
623*/
624QSslSocket::SslMode QSslSocket::mode() const
625{
626 Q_D(const QSslSocket);
627 return d->mode;
628}
629
630/*!
631 Returns \c true if the socket is encrypted; otherwise, false is returned.
632
633 An encrypted socket encrypts all data that is written by calling write()
634 or putChar() before the data is written to the network, and decrypts all
635 incoming data as the data is received from the network, before you call
636 read(), readLine() or getChar().
637
638 QSslSocket emits encrypted() when it enters encrypted mode.
639
640 You can call sessionCipher() to find which cryptographic cipher is used to
641 encrypt and decrypt your data.
642
643 \sa mode()
644*/
645bool QSslSocket::isEncrypted() const
646{
647 Q_D(const QSslSocket);
648 return d->connectionEncrypted;
649}
650
651/*!
652 Returns the socket's SSL protocol. By default, \l QSsl::SecureProtocols is used.
653
654 \sa setProtocol()
655*/
656QSsl::SslProtocol QSslSocket::protocol() const
657{
658 Q_D(const QSslSocket);
659 return d->configuration.protocol;
660}
661
662/*!
663 Sets the socket's SSL protocol to \a protocol. This will affect the next
664 initiated handshake; calling this function on an already-encrypted socket
665 will not affect the socket's protocol.
666*/
667void QSslSocket::setProtocol(QSsl::SslProtocol protocol)
668{
669 Q_D(QSslSocket);
670 d->configuration.protocol = protocol;
671}
672
673/*!
674 \since 4.4
675
676 Returns the socket's verify mode. This mode decides whether
677 QSslSocket should request a certificate from the peer (i.e., the client
678 requests a certificate from the server, or a server requesting a
679 certificate from the client), and whether it should require that this
680 certificate is valid.
681
682 The default mode is AutoVerifyPeer, which tells QSslSocket to use
683 VerifyPeer for clients and QueryPeer for servers.
684
685 \sa setPeerVerifyMode(), peerVerifyDepth(), mode()
686*/
687QSslSocket::PeerVerifyMode QSslSocket::peerVerifyMode() const
688{
689 Q_D(const QSslSocket);
690 return d->configuration.peerVerifyMode;
691}
692
693/*!
694 \since 4.4
695
696 Sets the socket's verify mode to \a mode. This mode decides whether
697 QSslSocket should request a certificate from the peer (i.e., the client
698 requests a certificate from the server, or a server requesting a
699 certificate from the client), and whether it should require that this
700 certificate is valid.
701
702 The default mode is AutoVerifyPeer, which tells QSslSocket to use
703 VerifyPeer for clients and QueryPeer for servers.
704
705 Setting this mode after encryption has started has no effect on the
706 current connection.
707
708 \sa peerVerifyMode(), setPeerVerifyDepth(), mode()
709*/
710void QSslSocket::setPeerVerifyMode(QSslSocket::PeerVerifyMode mode)
711{
712 Q_D(QSslSocket);
713 d->configuration.peerVerifyMode = mode;
714}
715
716/*!
717 \since 4.4
718
719 Returns the maximum number of certificates in the peer's certificate chain
720 to be checked during the SSL handshake phase, or 0 (the default) if no
721 maximum depth has been set, indicating that the whole certificate chain
722 should be checked.
723
724 The certificates are checked in issuing order, starting with the peer's
725 own certificate, then its issuer's certificate, and so on.
726
727 \sa setPeerVerifyDepth(), peerVerifyMode()
728*/
729int QSslSocket::peerVerifyDepth() const
730{
731 Q_D(const QSslSocket);
732 return d->configuration.peerVerifyDepth;
733}
734
735/*!
736 \since 4.4
737
738 Sets the maximum number of certificates in the peer's certificate chain to
739 be checked during the SSL handshake phase, to \a depth. Setting a depth of
740 0 means that no maximum depth is set, indicating that the whole
741 certificate chain should be checked.
742
743 The certificates are checked in issuing order, starting with the peer's
744 own certificate, then its issuer's certificate, and so on.
745
746 \sa peerVerifyDepth(), setPeerVerifyMode()
747*/
748void QSslSocket::setPeerVerifyDepth(int depth)
749{
750 Q_D(QSslSocket);
751 if (depth < 0) {
752 qCWarning(lcSsl, "QSslSocket::setPeerVerifyDepth: cannot set negative depth of %d", depth);
753 return;
754 }
755 d->configuration.peerVerifyDepth = depth;
756}
757
758/*!
759 \since 4.8
760
761 Returns the different hostname for the certificate validation, as set by
762 setPeerVerifyName or by connectToHostEncrypted.
763
764 \sa setPeerVerifyName(), connectToHostEncrypted()
765*/
766QString QSslSocket::peerVerifyName() const
767{
768 Q_D(const QSslSocket);
769 return d->verificationPeerName;
770}
771
772/*!
773 \since 4.8
774
775 Sets a different host name, given by \a hostName, for the certificate
776 validation instead of the one used for the TCP connection.
777
778 \sa connectToHostEncrypted()
779*/
780void QSslSocket::setPeerVerifyName(const QString &hostName)
781{
782 Q_D(QSslSocket);
783 d->verificationPeerName = hostName;
784}
785
786/*!
787 \reimp
788
789 Returns the number of decrypted bytes that are immediately available for
790 reading.
791*/
792qint64 QSslSocket::bytesAvailable() const
793{
794 Q_D(const QSslSocket);
795 if (d->mode == UnencryptedMode)
796 return QAbstractSocket::bytesAvailable() + (d->plainSocket ? d->plainSocket->bytesAvailable() : 0);
797 return QAbstractSocket::bytesAvailable();
798}
799
800/*!
801 \reimp
802
803 Returns the number of unencrypted bytes that are waiting to be encrypted
804 and written to the network.
805*/
806qint64 QSslSocket::bytesToWrite() const
807{
808 Q_D(const QSslSocket);
809 if (d->mode == UnencryptedMode)
810 return d->plainSocket ? d->plainSocket->bytesToWrite() : 0;
811 return d->writeBuffer.size();
812}
813
814/*!
815 \since 4.4
816
817 Returns the number of encrypted bytes that are awaiting decryption.
818 Normally, this function will return 0 because QSslSocket decrypts its
819 incoming data as soon as it can.
820*/
821qint64 QSslSocket::encryptedBytesAvailable() const
822{
823 Q_D(const QSslSocket);
824 if (d->mode == UnencryptedMode)
825 return 0;
826 return d->plainSocket->bytesAvailable();
827}
828
829/*!
830 \since 4.4
831
832 Returns the number of encrypted bytes that are waiting to be written to
833 the network.
834*/
835qint64 QSslSocket::encryptedBytesToWrite() const
836{
837 Q_D(const QSslSocket);
838 if (d->mode == UnencryptedMode)
839 return 0;
840 return d->plainSocket->bytesToWrite();
841}
842
843/*!
844 \reimp
845
846 Returns \c true if you can read one while line (terminated by a single ASCII
847 '\\n' character) of decrypted characters; otherwise, false is returned.
848*/
849bool QSslSocket::canReadLine() const
850{
851 Q_D(const QSslSocket);
852 if (d->mode == UnencryptedMode)
853 return QAbstractSocket::canReadLine() || (d->plainSocket && d->plainSocket->canReadLine());
854 return QAbstractSocket::canReadLine();
855}
856
857/*!
858 \reimp
859*/
860void QSslSocket::close()
861{
862#ifdef QSSLSOCKET_DEBUG
863 qCDebug(lcSsl) << "QSslSocket::close()";
864#endif
865 Q_D(QSslSocket);
866
867 // On Windows, CertGetCertificateChain is probably still doing its
868 // job, if the socket is re-used, we want to ignore its reported
869 // root CA.
870 if (auto *backend = d->backend.get())
871 backend->cancelCAFetch();
872
873 if (!d->abortCalled && (encryptedBytesToWrite() || !d->writeBuffer.isEmpty()))
874 flush();
875
876 // Initiate TLS shutdown while the read buffer is still valid;
877 // QTcpSocket::close() destroys it before calling disconnectFromHost().
878 if (!d->abortCalled)
879 disconnectFromHost();
880
881 if (d->plainSocket) {
882 if (d->abortCalled)
883 d->plainSocket->abort();
884 else
885 d->plainSocket->close();
886 }
887
888 QTcpSocket::close();
889
890 // must be cleared, reading/writing not possible on closed socket:
891 d->buffer.clear();
892 d->writeBuffer.clear();
893}
894
895/*!
896 \reimp
897*/
898bool QSslSocket::atEnd() const
899{
900 Q_D(const QSslSocket);
901 if (d->mode == UnencryptedMode)
902 return QAbstractSocket::atEnd() && (!d->plainSocket || d->plainSocket->atEnd());
903 return QAbstractSocket::atEnd();
904}
905
906/*!
907 \since 4.4
908
909 Sets the size of QSslSocket's internal read buffer to be \a size bytes.
910*/
911void QSslSocket::setReadBufferSize(qint64 size)
912{
913 Q_D(QSslSocket);
914 d->readBufferMaxSize = size;
915
916 if (d->plainSocket)
917 d->plainSocket->setReadBufferSize(size);
918}
919
920/*!
921 \since 4.4
922
923 Returns the socket's SSL configuration state. The default SSL
924 configuration of a socket is to use the default ciphers,
925 default CA certificates, no local private key or certificate.
926
927 The SSL configuration also contains fields that can change with
928 time without notice.
929
930 \sa localCertificate(), peerCertificate(), peerCertificateChain(),
931 sessionCipher(), privateKey(), QSslConfiguration::ciphers(),
932 QSslConfiguration::caCertificates()
933*/
934QSslConfiguration QSslSocket::sslConfiguration() const
935{
936 Q_D(const QSslSocket);
937
938 // create a deep copy of our configuration
939 QSslConfigurationPrivate *copy = new QSslConfigurationPrivate(d->configuration);
940 copy->ref.storeRelaxed(0); // the QSslConfiguration constructor refs up
941 copy->sessionCipher = d->sessionCipher();
942 copy->sessionProtocol = d->sessionProtocol();
943
944 return QSslConfiguration(copy);
945}
946
947/*!
948 \since 4.4
949
950 Sets the socket's SSL configuration to be the contents of \a configuration.
951 This function sets the local certificate, the ciphers, the private key and the CA
952 certificates to those stored in \a configuration.
953
954 It is not possible to set the SSL-state related fields.
955
956 \sa setLocalCertificate(), setPrivateKey(), QSslConfiguration::setCaCertificates(),
957 QSslConfiguration::setCiphers()
958*/
959void QSslSocket::setSslConfiguration(const QSslConfiguration &configuration)
960{
961 Q_D(QSslSocket);
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 // The getter is non-const, it hands the values over, so read the private:
980 d->configuration.keyingMaterial = configuration.d->keyingMaterial;
981#if QT_CONFIG(ocsp)
982 d->configuration.ocspStaplingEnabled = configuration.ocspStaplingEnabled();
983#endif
984#if QT_CONFIG(openssl)
985 d->configuration.reportFromCallback = configuration.handshakeMustInterruptOnError();
986 d->configuration.missingCertIsFatal = configuration.missingCertificateIsFatal();
987#endif // openssl
988 // if the CA certificates were set explicitly (either via
989 // QSslConfiguration::setCaCertificates() or QSslSocket::setCaCertificates(),
990 // we cannot load the certificates on demand
991 if (!configuration.d->allowRootCertOnDemandLoading) {
992 d->allowRootCertOnDemandLoading = false;
993 d->configuration.allowRootCertOnDemandLoading = false;
994 }
995}
996
997/*!
998 Sets the certificate chain to be presented to the peer during the
999 SSL handshake to be \a localChain.
1000
1001 \sa QSslConfiguration::setLocalCertificateChain()
1002 \since 5.1
1003 */
1004void QSslSocket::setLocalCertificateChain(const QList<QSslCertificate> &localChain)
1005{
1006 Q_D(QSslSocket);
1007 d->configuration.localCertificateChain = localChain;
1008}
1009
1010/*!
1011 Returns the socket's local \l {QSslCertificate} {certificate} chain,
1012 or an empty list if no local certificates have been assigned.
1013
1014 \sa setLocalCertificateChain()
1015 \since 5.1
1016*/
1017QList<QSslCertificate> QSslSocket::localCertificateChain() const
1018{
1019 Q_D(const QSslSocket);
1020 return d->configuration.localCertificateChain;
1021}
1022
1023/*!
1024 Sets the socket's local certificate to \a certificate. The local
1025 certificate is necessary if you need to confirm your identity to the
1026 peer. It is used together with the private key; if you set the local
1027 certificate, you must also set the private key.
1028
1029 The local certificate and private key are always necessary for server
1030 sockets, but are also rarely used by client sockets if the server requires
1031 the client to authenticate.
1032
1033 \note Secure Transport SSL backend on macOS may update the default keychain
1034 (the default is probably your login keychain) by importing your local certificates
1035 and keys. This can also result in system dialogs showing up and asking for
1036 permission when your application is using these private keys. If such behavior
1037 is undesired, set the QT_SSL_USE_TEMPORARY_KEYCHAIN environment variable to a
1038 non-zero value; this will prompt QSslSocket to use its own temporary keychain.
1039
1040 \sa localCertificate(), setPrivateKey()
1041*/
1042void QSslSocket::setLocalCertificate(const QSslCertificate &certificate)
1043{
1044 Q_D(QSslSocket);
1045 d->configuration.localCertificateChain = QList<QSslCertificate>();
1046 d->configuration.localCertificateChain += certificate;
1047}
1048
1049/*!
1050 \overload
1051
1052 Sets the socket's local \l {QSslCertificate} {certificate} to the
1053 first one found in file \a path, which is parsed according to the
1054 specified \a format.
1055*/
1056void QSslSocket::setLocalCertificate(const QString &path,
1057 QSsl::EncodingFormat format)
1058{
1059 QFile file(path);
1060 if (file.open(QIODevice::ReadOnly | QIODevice::Text))
1061 setLocalCertificate(QSslCertificate(file.readAll(), format));
1062
1063}
1064
1065/*!
1066 Returns the socket's local \l {QSslCertificate} {certificate}, or
1067 an empty certificate if no local certificate has been assigned.
1068
1069 \sa setLocalCertificate(), privateKey()
1070*/
1071QSslCertificate QSslSocket::localCertificate() const
1072{
1073 Q_D(const QSslSocket);
1074 if (d->configuration.localCertificateChain.isEmpty())
1075 return QSslCertificate();
1076 return d->configuration.localCertificateChain[0];
1077}
1078
1079/*!
1080 Returns the peer's digital certificate (i.e., the immediate
1081 certificate of the host you are connected to), or a null
1082 certificate, if the peer has not assigned a certificate.
1083
1084 The peer certificate is checked automatically during the
1085 handshake phase, so this function is normally used to fetch
1086 the certificate for display or for connection diagnostic
1087 purposes. It contains information about the peer, including
1088 its host name, the certificate issuer, and the peer's public
1089 key.
1090
1091 Because the peer certificate is set during the handshake phase, it
1092 is safe to access the peer certificate from a slot connected to
1093 the sslErrors() signal or the encrypted() signal.
1094
1095 If a null certificate is returned, it can mean the SSL handshake
1096 failed, or it can mean the host you are connected to doesn't have
1097 a certificate, or it can mean there is no connection.
1098
1099 If you want to check the peer's complete chain of certificates,
1100 use peerCertificateChain() to get them all at once.
1101
1102 \sa peerCertificateChain()
1103*/
1104QSslCertificate QSslSocket::peerCertificate() const
1105{
1106 Q_D(const QSslSocket);
1107 return d->configuration.peerCertificate;
1108}
1109
1110/*!
1111 Returns the peer's chain of digital certificates, or an empty list
1112 of certificates.
1113
1114 Peer certificates are checked automatically during the handshake
1115 phase. This function is normally used to fetch certificates for
1116 display, or for performing connection diagnostics. Certificates
1117 contain information about the peer and the certificate issuers,
1118 including host name, issuer names, and issuer public keys.
1119
1120 The peer certificates are set in QSslSocket during the handshake
1121 phase, so it is safe to call this function from a slot connected
1122 to the sslErrors() signal or the encrypted() signal.
1123
1124 If an empty list is returned, it can mean the SSL handshake
1125 failed, or it can mean the host you are connected to doesn't have
1126 a certificate, or it can mean there is no connection.
1127
1128 If you want to get only the peer's immediate certificate, use
1129 peerCertificate().
1130
1131 \sa peerCertificate()
1132*/
1133QList<QSslCertificate> QSslSocket::peerCertificateChain() const
1134{
1135 Q_D(const QSslSocket);
1136 return d->configuration.peerCertificateChain;
1137}
1138
1139/*!
1140 Returns the socket's cryptographic \l {QSslCipher} {cipher}, or a
1141 null cipher if the connection isn't encrypted. The socket's cipher
1142 for the session is set during the handshake phase. The cipher is
1143 used to encrypt and decrypt data transmitted through the socket.
1144
1145 QSslSocket also provides functions for setting the ordered list of
1146 ciphers from which the handshake phase will eventually select the
1147 session cipher. This ordered list must be in place before the
1148 handshake phase begins.
1149
1150 \sa QSslConfiguration::ciphers(), QSslConfiguration::setCiphers(),
1151 QSslConfiguration::supportedCiphers()
1152*/
1153QSslCipher QSslSocket::sessionCipher() const
1154{
1155 Q_D(const QSslSocket);
1156 return d->sessionCipher();
1157}
1158
1159/*!
1160 Returns the socket's SSL/TLS protocol or UnknownProtocol if the
1161 connection isn't encrypted. The socket's protocol for the session
1162 is set during the handshake phase.
1163
1164 \sa protocol(), setProtocol()
1165 \since 5.4
1166*/
1167QSsl::SslProtocol QSslSocket::sessionProtocol() const
1168{
1169 Q_D(const QSslSocket);
1170 return d->sessionProtocol();
1171}
1172
1173/*!
1174 \since 5.13
1175
1176 This function returns Online Certificate Status Protocol responses that
1177 a server may send during a TLS handshake using OCSP stapling. The list
1178 is empty if no definitive response or no response at all was received.
1179
1180 \sa QSslConfiguration::setOcspStaplingEnabled()
1181*/
1182QList<QOcspResponse> QSslSocket::ocspResponses() const
1183{
1184 Q_D(const QSslSocket);
1185 if (const auto *backend = d->backend.get())
1186 return backend->ocsps();
1187 return {};
1188}
1189
1190/*!
1191 Sets the socket's private \l {QSslKey} {key} to \a key. The
1192 private key and the local \l {QSslCertificate} {certificate} are
1193 used by clients and servers that must prove their identity to
1194 SSL peers.
1195
1196 Both the key and the local certificate are required if you are
1197 creating an SSL server socket. If you are creating an SSL client
1198 socket, the key and local certificate are required if your client
1199 must identify itself to an SSL server.
1200
1201 \sa privateKey(), setLocalCertificate()
1202*/
1203void QSslSocket::setPrivateKey(const QSslKey &key)
1204{
1205 Q_D(QSslSocket);
1206 d->configuration.privateKey = key;
1207}
1208
1209/*!
1210 \overload
1211
1212 Reads the string in file \a fileName and decodes it using
1213 a specified \a algorithm and encoding \a format to construct
1214 an \l {QSslKey} {SSL key}. If the encoded key is encrypted,
1215 \a passPhrase is used to decrypt it.
1216
1217 The socket's private key is set to the constructed key. The
1218 private key and the local \l {QSslCertificate} {certificate} are
1219 used by clients and servers that must prove their identity to SSL
1220 peers.
1221
1222 Both the key and the local certificate are required if you are
1223 creating an SSL server socket. If you are creating an SSL client
1224 socket, the key and local certificate are required if your client
1225 must identify itself to an SSL server.
1226
1227 \sa privateKey(), setLocalCertificate()
1228*/
1229void QSslSocket::setPrivateKey(const QString &fileName, QSsl::KeyAlgorithm algorithm,
1230 QSsl::EncodingFormat format, const QByteArray &passPhrase)
1231{
1232 QFile file(fileName);
1233 if (!file.open(QIODevice::ReadOnly)) {
1234 qCWarning(lcSsl, "QSslSocket::setPrivateKey: Couldn't open file for reading");
1235 return;
1236 }
1237
1238 QSslKey key(file.readAll(), algorithm, format, QSsl::PrivateKey, passPhrase);
1239 if (key.isNull()) {
1240 qCWarning(lcSsl, "QSslSocket::setPrivateKey: "
1241 "The specified file does not contain a valid key");
1242 return;
1243 }
1244
1245 Q_D(QSslSocket);
1246 d->configuration.privateKey = key;
1247}
1248
1249/*!
1250 Returns this socket's private key.
1251
1252 \sa setPrivateKey(), localCertificate()
1253*/
1254QSslKey QSslSocket::privateKey() const
1255{
1256 Q_D(const QSslSocket);
1257 return d->configuration.privateKey;
1258}
1259
1260/*!
1261 Waits until the socket is connected, or \a msecs milliseconds,
1262 whichever happens first. If the connection has been established,
1263 this function returns \c true; otherwise it returns \c false.
1264
1265 \sa QAbstractSocket::waitForConnected()
1266*/
1267bool QSslSocket::waitForConnected(int msecs)
1268{
1269 Q_D(QSslSocket);
1270 if (!d->plainSocket)
1271 return false;
1272 bool retVal = d->plainSocket->waitForConnected(msecs);
1273 if (!retVal) {
1274 setSocketState(d->plainSocket->state());
1275 d->setError(d->plainSocket->error(), d->plainSocket->errorString());
1276 }
1277 return retVal;
1278}
1279
1280/*!
1281 Waits until the socket has completed the SSL handshake and has
1282 emitted encrypted(), or \a msecs milliseconds, whichever comes
1283 first. If encrypted() has been emitted, this function returns
1284 true; otherwise (e.g., the socket is disconnected, or the SSL
1285 handshake fails), false is returned.
1286
1287 The following example waits up to one second for the socket to be
1288 encrypted:
1289
1290 \snippet code/src_network_ssl_qsslsocket.cpp 5
1291
1292 If msecs is -1, this function will not time out.
1293
1294 \sa startClientEncryption(), startServerEncryption(), encrypted(), isEncrypted()
1295*/
1296bool QSslSocket::waitForEncrypted(int msecs)
1297{
1298 Q_D(QSslSocket);
1299 if (!d->plainSocket || d->connectionEncrypted)
1300 return false;
1301 if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1302 return false;
1303 if (!d->verifyProtocolSupported("QSslSocket::waitForEncrypted:"))
1304 return false;
1305
1306 QElapsedTimer stopWatch;
1307 stopWatch.start();
1308
1309 if (d->plainSocket->state() != QAbstractSocket::ConnectedState) {
1310 // Wait until we've entered connected state.
1311 if (!d->plainSocket->waitForConnected(msecs))
1312 return false;
1313 }
1314
1315 while (!d->connectionEncrypted) {
1316 // Start the handshake, if this hasn't been started yet.
1317 if (d->mode == UnencryptedMode)
1318 startClientEncryption();
1319 // Loop, waiting until the connection has been encrypted or an error
1320 // occurs.
1321 if (!d->plainSocket->waitForReadyRead(qt_subtract_from_timeout(msecs, stopWatch.elapsed())))
1322 return false;
1323 }
1324 return d->connectionEncrypted;
1325}
1326
1327/*!
1328 \reimp
1329*/
1330bool QSslSocket::waitForReadyRead(int msecs)
1331{
1332 Q_D(QSslSocket);
1333 if (!d->plainSocket)
1334 return false;
1335 if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1336 return d->plainSocket->waitForReadyRead(msecs);
1337
1338 // This function must return true if and only if readyRead() *was* emitted.
1339 // So we initialize "readyReadEmitted" to false and check if it was set to true.
1340 // waitForReadyRead() could be called recursively, so we can't use the same variable
1341 // (the inner waitForReadyRead() may fail, but the outer one still succeeded)
1342 bool readyReadEmitted = false;
1343 bool *previousReadyReadEmittedPointer = d->readyReadEmittedPointer;
1344 d->readyReadEmittedPointer = &readyReadEmitted;
1345
1346 QElapsedTimer stopWatch;
1347 stopWatch.start();
1348
1349 if (!d->connectionEncrypted) {
1350 // Wait until we've entered encrypted mode, or until a failure occurs.
1351 if (!waitForEncrypted(msecs)) {
1352 d->readyReadEmittedPointer = previousReadyReadEmittedPointer;
1353 return false;
1354 }
1355 }
1356
1357 if (!d->writeBuffer.isEmpty()) {
1358 // empty our cleartext write buffer first
1359 d->transmit();
1360 }
1361
1362 // test readyReadEmitted first because either operation above
1363 // (waitForEncrypted or transmit) may have set it
1364 while (!readyReadEmitted &&
1365 d->plainSocket->waitForReadyRead(qt_subtract_from_timeout(msecs, stopWatch.elapsed()))) {
1366 }
1367
1368 d->readyReadEmittedPointer = previousReadyReadEmittedPointer;
1369 return readyReadEmitted;
1370}
1371
1372/*!
1373 \reimp
1374*/
1375bool QSslSocket::waitForBytesWritten(int msecs)
1376{
1377 Q_D(QSslSocket);
1378 if (!d->plainSocket)
1379 return false;
1380 if (d->mode == UnencryptedMode)
1381 return d->plainSocket->waitForBytesWritten(msecs);
1382
1383 QElapsedTimer stopWatch;
1384 stopWatch.start();
1385
1386 if (!d->connectionEncrypted) {
1387 // Wait until we've entered encrypted mode, or until a failure occurs.
1388 if (!waitForEncrypted(msecs))
1389 return false;
1390 }
1391 if (!d->writeBuffer.isEmpty()) {
1392 // empty our cleartext write buffer first
1393 d->transmit();
1394 }
1395
1396 return d->plainSocket->waitForBytesWritten(qt_subtract_from_timeout(msecs, stopWatch.elapsed()));
1397}
1398
1399/*!
1400 Waits until the socket has disconnected or \a msecs milliseconds,
1401 whichever comes first. If the connection has been disconnected,
1402 this function returns \c true; otherwise it returns \c false.
1403
1404 \sa QAbstractSocket::waitForDisconnected()
1405*/
1406bool QSslSocket::waitForDisconnected(int msecs)
1407{
1408 Q_D(QSslSocket);
1409
1410 // require calling connectToHost() before waitForDisconnected()
1411 if (state() == UnconnectedState) {
1412 qCWarning(lcSsl, "QSslSocket::waitForDisconnected() is not allowed in UnconnectedState");
1413 return false;
1414 }
1415
1416 if (!d->plainSocket)
1417 return false;
1418 // Forward to the plain socket unless the connection is secure.
1419 if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1420 return d->plainSocket->waitForDisconnected(msecs);
1421
1422 QElapsedTimer stopWatch;
1423 stopWatch.start();
1424
1425 if (!d->connectionEncrypted) {
1426 // Wait until we've entered encrypted mode, or until a failure occurs.
1427 if (!waitForEncrypted(msecs))
1428 return false;
1429 }
1430 // We are delaying the disconnect, if the write buffer is not empty.
1431 // So, start the transmission.
1432 if (!d->writeBuffer.isEmpty())
1433 d->transmit();
1434
1435 // At this point, the socket might be disconnected, if disconnectFromHost()
1436 // was called just after the connectToHostEncrypted() call. Also, we can
1437 // lose the connection as a result of the transmit() call.
1438 if (state() == UnconnectedState)
1439 return true;
1440
1441 bool retVal = d->plainSocket->waitForDisconnected(qt_subtract_from_timeout(msecs, stopWatch.elapsed()));
1442 if (!retVal) {
1443 setSocketState(d->plainSocket->state());
1444 d->setError(d->plainSocket->error(), d->plainSocket->errorString());
1445 }
1446 return retVal;
1447}
1448
1449/*!
1450 \since 5.15
1451
1452 Returns a list of the last SSL errors that occurred. This is the
1453 same list as QSslSocket passes via the sslErrors() signal. If the
1454 connection has been encrypted with no errors, this function will
1455 return an empty list.
1456
1457 \sa connectToHostEncrypted()
1458*/
1459QList<QSslError> QSslSocket::sslHandshakeErrors() const
1460{
1461 Q_D(const QSslSocket);
1462 if (const auto *backend = d->backend.get())
1463 return backend->tlsErrors();
1464 return {};
1465}
1466
1467/*!
1468 Returns \c true if this platform supports SSL; otherwise, returns
1469 false. If the platform doesn't support SSL, the socket will fail
1470 in the connection phase.
1471*/
1472bool QSslSocket::supportsSsl()
1473{
1474 return QSslSocketPrivate::supportsSsl();
1475}
1476
1477/*!
1478 \since 5.0
1479 Returns the version number of the SSL library in use. Note that
1480 this is the version of the library in use at run-time not compile
1481 time. If no SSL support is available then this will return -1.
1482*/
1483long QSslSocket::sslLibraryVersionNumber()
1484{
1485 if (const auto *tlsBackend = QSslSocketPrivate::tlsBackendInUse())
1486 return tlsBackend->tlsLibraryVersionNumber();
1487
1488 return -1;
1489}
1490
1491/*!
1492 \since 5.0
1493 Returns the version string of the SSL library in use. Note that
1494 this is the version of the library in use at run-time not compile
1495 time. If no SSL support is available then this will return an empty value.
1496*/
1497QString QSslSocket::sslLibraryVersionString()
1498{
1499 if (const auto *tlsBackend = QSslSocketPrivate::tlsBackendInUse())
1500 return tlsBackend->tlsLibraryVersionString();
1501 return {};
1502}
1503
1504/*!
1505 \since 5.4
1506 Returns the version number of the SSL library in use at compile
1507 time. If no SSL support is available then this will return -1.
1508
1509 \sa sslLibraryVersionNumber()
1510*/
1511long QSslSocket::sslLibraryBuildVersionNumber()
1512{
1513 if (const auto *tlsBackend = QSslSocketPrivate::tlsBackendInUse())
1514 return tlsBackend->tlsLibraryBuildVersionNumber();
1515 return -1;
1516}
1517
1518/*!
1519 \since 5.4
1520 Returns the version string of the SSL library in use at compile
1521 time. If no SSL support is available then this will return an
1522 empty value.
1523
1524 \sa sslLibraryVersionString()
1525*/
1526QString QSslSocket::sslLibraryBuildVersionString()
1527{
1528 if (const auto *tlsBackend = QSslSocketPrivate::tlsBackendInUse())
1529 return tlsBackend->tlsLibraryBuildVersionString();
1530
1531 return {};
1532}
1533
1534/*!
1535 \since 6.1
1536 Returns the names of the currently available backends. These names
1537 are in lower case, e.g. "openssl", "securetransport", "schannel"
1538 (similar to the already existing feature names for TLS backends in Qt).
1539
1540 \sa activeBackend()
1541*/
1542QList<QString> QSslSocket::availableBackends()
1543{
1544 return QTlsBackend::availableBackendNames();
1545}
1546
1547/*!
1548 \since 6.1
1549 Returns the name of the backend that QSslSocket and related classes
1550 use. If the active backend was not set explicitly, this function
1551 returns the name of a default backend that QSslSocket selects implicitly
1552 from the list of available backends.
1553
1554 \note When selecting a default backend implicitly, QSslSocket prefers
1555 the OpenSSL backend if available. If it's not available, the Schannel backend
1556 is implicitly selected on Windows, and Secure Transport on Darwin platforms.
1557 Failing these, if a custom TLS backend is found, it is used.
1558 If no other backend is found, the "certificate only" backend is selected.
1559 For more information about TLS plugins, please see
1560 \l {Enabling and Disabling SSL Support when Building Qt from Source}.
1561
1562 \sa setActiveBackend(), availableBackends()
1563*/
1564QString QSslSocket::activeBackend()
1565{
1566 const QMutexLocker locker(&QSslSocketPrivate::backendMutex);
1567
1568 if (!QSslSocketPrivate::activeBackendName.size())
1569 QSslSocketPrivate::activeBackendName = QTlsBackend::defaultBackendName();
1570
1571 return QSslSocketPrivate::activeBackendName;
1572}
1573
1574/*!
1575 \since 6.1
1576 Returns true if a backend with name \a backendName was set as
1577 active backend. \a backendName must be one of names returned
1578 by availableBackends().
1579
1580 \note An application cannot mix different backends simultaneously.
1581 This implies that a non-default backend must be selected prior
1582 to any use of QSslSocket or related classes, e.g. QSslCertificate
1583 or QSslKey.
1584
1585 \sa activeBackend(), availableBackends()
1586*/
1587bool QSslSocket::setActiveBackend(const QString &backendName)
1588{
1589 if (!backendName.size()) {
1590 qCWarning(lcSsl, "Invalid parameter (backend name cannot be an empty string)");
1591 return false;
1592 }
1593
1594 QMutexLocker locker(&QSslSocketPrivate::backendMutex);
1595 if (QSslSocketPrivate::tlsBackend) {
1596 qCWarning(lcSsl) << "Cannot set backend named" << backendName
1597 << "as active, another backend is already in use";
1598 locker.unlock();
1599 return activeBackend() == backendName;
1600 }
1601
1602 if (!QTlsBackend::availableBackendNames().contains(backendName)) {
1603 qCWarning(lcSsl) << "Cannot set unavailable backend named" << backendName
1604 << "as active";
1605 return false;
1606 }
1607
1608 QSslSocketPrivate::activeBackendName = backendName;
1609
1610 return true;
1611}
1612
1613/*!
1614 \since 6.1
1615 If a backend with name \a backendName is available, this function returns the
1616 list of TLS protocol versions supported by this backend. An empty \a backendName
1617 is understood as a query about the currently active backend. Otherwise, this
1618 function returns an empty list.
1619
1620 \sa availableBackends(), activeBackend(), isProtocolSupported()
1621*/
1622QList<QSsl::SslProtocol> QSslSocket::supportedProtocols(const QString &backendName)
1623{
1624 return QTlsBackend::supportedProtocols(backendName.size() ? backendName : activeBackend());
1625}
1626
1627/*!
1628 \since 6.1
1629 Returns true if \a protocol is supported by a backend named \a backendName. An empty
1630 \a backendName is understood as a query about the currently active backend.
1631
1632 \sa supportedProtocols()
1633*/
1634bool QSslSocket::isProtocolSupported(QSsl::SslProtocol protocol, const QString &backendName)
1635{
1636 const auto versions = supportedProtocols(backendName);
1637 return versions.contains(protocol);
1638}
1639
1640/*!
1641 \since 6.1
1642 This function returns backend-specific classes implemented by the backend named
1643 \a backendName. An empty \a backendName is understood as a query about the
1644 currently active backend.
1645
1646 \sa QSsl::ImplementedClass, activeBackend(), isClassImplemented()
1647*/
1648QList<QSsl::ImplementedClass> QSslSocket::implementedClasses(const QString &backendName)
1649{
1650 return QTlsBackend::implementedClasses(backendName.size() ? backendName : activeBackend());
1651}
1652
1653/*!
1654 \since 6.1
1655 Returns true if a class \a cl is implemented by the backend named \a backendName. An empty
1656 \a backendName is understood as a query about the currently active backend.
1657
1658 \sa implementedClasses()
1659*/
1660
1661bool QSslSocket::isClassImplemented(QSsl::ImplementedClass cl, const QString &backendName)
1662{
1663 return implementedClasses(backendName).contains(cl);
1664}
1665
1666/*!
1667 \since 6.1
1668 This function returns features supported by a backend named \a backendName.
1669 An empty \a backendName is understood as a query about the currently active backend.
1670
1671 \sa QSsl::SupportedFeature, activeBackend()
1672*/
1673QList<QSsl::SupportedFeature> QSslSocket::supportedFeatures(const QString &backendName)
1674{
1675 return QTlsBackend::supportedFeatures(backendName.size() ? backendName : activeBackend());
1676}
1677
1678/*!
1679 \since 6.1
1680 Returns true if a feature \a ft is supported by a backend named \a backendName. An empty
1681 \a backendName is understood as a query about the currently active backend.
1682
1683 \sa QSsl::SupportedFeature, supportedFeatures()
1684*/
1685bool QSslSocket::isFeatureSupported(QSsl::SupportedFeature ft, const QString &backendName)
1686{
1687 return supportedFeatures(backendName).contains(ft);
1688}
1689
1690/*!
1691 Starts a delayed SSL handshake for a client connection. This
1692 function can be called when the socket is in the \l ConnectedState
1693 but still in the \l UnencryptedMode. If it is not yet connected,
1694 or if it is already encrypted, this function has no effect.
1695
1696 Clients that implement STARTTLS functionality often make use of
1697 delayed SSL handshakes. Most other clients can avoid calling this
1698 function directly by using connectToHostEncrypted() instead, which
1699 automatically performs the handshake.
1700
1701 \sa connectToHostEncrypted(), startServerEncryption()
1702*/
1703void QSslSocket::startClientEncryption()
1704{
1705 Q_D(QSslSocket);
1706 if (d->mode != UnencryptedMode) {
1707 qCWarning(lcSsl,
1708 "QSslSocket::startClientEncryption: cannot start handshake on non-plain connection");
1709 return;
1710 }
1711 if (state() != ConnectedState) {
1712 qCWarning(lcSsl,
1713 "QSslSocket::startClientEncryption: cannot start handshake when not connected");
1714 return;
1715 }
1716
1717 if (!supportsSsl()) {
1718 qCWarning(lcSsl, "QSslSocket::startClientEncryption: TLS initialization failed");
1719 d->setErrorAndEmit(QAbstractSocket::SslInternalError, tr("TLS initialization failed"));
1720 return;
1721 }
1722
1723 if (!d->verifyProtocolSupported("QSslSocket::startClientEncryption:"))
1724 return;
1725
1726#ifdef QSSLSOCKET_DEBUG
1727 qCDebug(lcSsl) << "QSslSocket::startClientEncryption()";
1728#endif
1729 d->mode = SslClientMode;
1730 emit modeChanged(d->mode);
1731 d->startClientEncryption();
1732}
1733
1734/*!
1735 Starts a delayed SSL handshake for a server connection. This
1736 function can be called when the socket is in the \l ConnectedState
1737 but still in \l UnencryptedMode. If it is not connected or it is
1738 already encrypted, the function has no effect.
1739
1740 For server sockets, calling this function is the only way to
1741 initiate the SSL handshake. Most servers will call this function
1742 immediately upon receiving a connection, or as a result of having
1743 received a protocol-specific command to enter SSL mode (e.g, the
1744 server may respond to receiving the string "STARTTLS\\r\\n" by
1745 calling this function).
1746
1747 The most common way to implement an SSL server is to create a
1748 subclass of QTcpServer and reimplement
1749 QTcpServer::incomingConnection(). The returned socket descriptor
1750 is then passed to QSslSocket::setSocketDescriptor().
1751
1752 \sa connectToHostEncrypted(), startClientEncryption()
1753*/
1754void QSslSocket::startServerEncryption()
1755{
1756 Q_D(QSslSocket);
1757 if (d->mode != UnencryptedMode) {
1758 qCWarning(lcSsl, "QSslSocket::startServerEncryption: cannot start handshake on non-plain connection");
1759 return;
1760 }
1761#ifdef QSSLSOCKET_DEBUG
1762 qCDebug(lcSsl) << "QSslSocket::startServerEncryption()";
1763#endif
1764 if (!supportsSsl()) {
1765 qCWarning(lcSsl, "QSslSocket::startServerEncryption: TLS initialization failed");
1766 d->setErrorAndEmit(QAbstractSocket::SslInternalError, tr("TLS initialization failed"));
1767 return;
1768 }
1769 if (!d->verifyProtocolSupported("QSslSocket::startServerEncryption"))
1770 return;
1771
1772 d->mode = SslServerMode;
1773 emit modeChanged(d->mode);
1774 d->startServerEncryption();
1775}
1776
1777/*!
1778 This slot tells QSslSocket to ignore errors during QSslSocket's
1779 handshake phase and continue connecting. If you want to continue
1780 with the connection even if errors occur during the handshake
1781 phase, then you must call this slot, either from a slot connected
1782 to sslErrors(), or before the handshake phase. If you don't call
1783 this slot, either in response to errors or before the handshake,
1784 the connection will be dropped after the sslErrors() signal has
1785 been emitted.
1786
1787 If there are no errors during the SSL handshake phase (i.e., the
1788 identity of the peer is established with no problems), QSslSocket
1789 will not emit the sslErrors() signal, and it is unnecessary to
1790 call this function.
1791
1792 \warning Be sure to always let the user inspect the errors
1793 reported by the sslErrors() signal, and only call this method
1794 upon confirmation from the user that proceeding is ok.
1795 If there are unexpected errors, the connection should be aborted.
1796 Calling this method without inspecting the actual errors will
1797 most likely pose a security risk for your application. Use it
1798 with great care!
1799
1800 \sa sslErrors()
1801*/
1802void QSslSocket::ignoreSslErrors()
1803{
1804 Q_D(QSslSocket);
1805 d->ignoreAllSslErrors = true;
1806}
1807
1808/*!
1809 \overload
1810 \since 4.6
1811
1812 This method tells QSslSocket to ignore only the errors given in \a
1813 errors.
1814
1815 \note Because most SSL errors are associated with a certificate, for most
1816 of them you must set the expected certificate this SSL error is related to.
1817 If, for instance, you want to connect to a server that uses
1818 a self-signed certificate, consider the following snippet:
1819
1820 \snippet code/src_network_ssl_qsslsocket.cpp 6
1821
1822 Multiple calls to this function will replace the list of errors that
1823 were passed in previous calls.
1824 You can clear the list of errors you want to ignore by calling this
1825 function with an empty list.
1826
1827 \sa sslErrors(), sslHandshakeErrors()
1828*/
1829void QSslSocket::ignoreSslErrors(const QList<QSslError> &errors)
1830{
1831 Q_D(QSslSocket);
1832 d->ignoreErrorsList = errors;
1833}
1834
1835
1836/*!
1837 \since 6.0
1838
1839 If an application wants to conclude a handshake even after receiving
1840 handshakeInterruptedOnError() signal, it must call this function.
1841 This call must be done from a slot function attached to the signal.
1842 The signal-slot connection must be direct.
1843
1844 \sa handshakeInterruptedOnError(), QSslConfiguration::setHandshakeMustInterruptOnError()
1845*/
1846void QSslSocket::continueInterruptedHandshake()
1847{
1848 Q_D(QSslSocket);
1849 if (auto *backend = d->backend.get())
1850 backend->enableHandshakeContinuation();
1851}
1852
1853/*!
1854 \reimp
1855*/
1856void QSslSocket::connectToHost(const QString &hostName, quint16 port, OpenMode openMode, NetworkLayerProtocol protocol)
1857{
1858 Q_D(QSslSocket);
1859 d->preferredNetworkLayerProtocol = protocol;
1860 if (!d->initialized)
1861 d->init();
1862 d->initialized = false;
1863
1864#ifdef QSSLSOCKET_DEBUG
1865 qCDebug(lcSsl) << "QSslSocket::connectToHost("
1866 << hostName << ',' << port << ',' << openMode << ')';
1867#endif
1868 if (!d->plainSocket) {
1869#ifdef QSSLSOCKET_DEBUG
1870 qCDebug(lcSsl) << "\tcreating internal plain socket";
1871#endif
1872 d->createPlainSocket(openMode);
1873 }
1874#ifndef QT_NO_NETWORKPROXY
1875 d->plainSocket->setProtocolTag(d->protocolTag);
1876 d->plainSocket->setProxy(proxy());
1877#endif
1878 QIODevice::open(openMode);
1879 d->readChannelCount = d->writeChannelCount = 0;
1880 d->plainSocket->connectToHost(hostName, port, openMode, d->preferredNetworkLayerProtocol);
1881 d->cachedSocketDescriptor = d->plainSocket->socketDescriptor();
1882}
1883
1884/*!
1885 \reimp
1886*/
1887void QSslSocket::disconnectFromHost()
1888{
1889 Q_D(QSslSocket);
1890#ifdef QSSLSOCKET_DEBUG
1891 qCDebug(lcSsl) << "QSslSocket::disconnectFromHost()";
1892#endif
1893 if (!d->plainSocket)
1894 return;
1895 if (d->state == UnconnectedState)
1896 return;
1897 if (d->mode == UnencryptedMode && !d->autoStartHandshake) {
1898 d->plainSocket->disconnectFromHost();
1899 return;
1900 }
1901 if (d->state <= ConnectingState) {
1902 d->pendingClose = true;
1903 return;
1904 }
1905 // Make sure we don't process any signal from the CA fetcher
1906 // (Windows):
1907 if (auto *backend = d->backend.get())
1908 backend->cancelCAFetch();
1909
1910 // Perhaps emit closing()
1911 if (d->state != ClosingState) {
1912 d->state = ClosingState;
1913 emit stateChanged(d->state);
1914 }
1915
1916 if (!d->writeBuffer.isEmpty()) {
1917 d->pendingClose = true;
1918 return;
1919 }
1920
1921 if (d->mode == UnencryptedMode) {
1922 d->plainSocket->disconnectFromHost();
1923 } else {
1924 d->disconnectFromHost();
1925 }
1926}
1927
1928/*!
1929 \reimp
1930*/
1931qint64 QSslSocket::readData(char *data, qint64 maxlen)
1932{
1933 Q_D(QSslSocket);
1934 qint64 readBytes = 0;
1935
1936 if (d->mode == UnencryptedMode && !d->autoStartHandshake) {
1937 readBytes = d->plainSocket->read(data, maxlen);
1938#ifdef QSSLSOCKET_DEBUG
1939 qCDebug(lcSsl) << "QSslSocket::readData(" << (void *)data << ',' << maxlen << ") =="
1940 << readBytes;
1941#endif
1942 } else {
1943 // possibly trigger another transmit() to decrypt more data from the socket
1944 if (d->plainSocket->bytesAvailable() || d->hasUndecryptedData())
1945 QMetaObject::invokeMethod(this, "_q_flushReadBuffer", Qt::QueuedConnection);
1946 else if (d->state != QAbstractSocket::ConnectedState)
1947 return maxlen ? qint64(-1) : qint64(0);
1948 }
1949
1950 return readBytes;
1951}
1952
1953/*!
1954 \reimp
1955*/
1956qint64 QSslSocket::writeData(const char *data, qint64 len)
1957{
1958 Q_D(QSslSocket);
1959#ifdef QSSLSOCKET_DEBUG
1960 qCDebug(lcSsl) << "QSslSocket::writeData(" << (void *)data << ',' << len << ')';
1961#endif
1962 if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1963 return d->plainSocket->write(data, len);
1964
1965 d->write(data, len);
1966
1967 // make sure we flush to the plain socket's buffer
1968 if (!d->flushTriggered) {
1969 d->flushTriggered = true;
1970 QMetaObject::invokeMethod(this, "_q_flushWriteBuffer", Qt::QueuedConnection);
1971 }
1972
1973 return len;
1974}
1975
1976bool QSslSocketPrivate::s_loadRootCertsOnDemand = false;
1977
1978/*!
1979 \internal
1980*/
1981QSslSocketPrivate::QSslSocketPrivate()
1982 : initialized(false)
1983 , mode(QSslSocket::UnencryptedMode)
1984 , autoStartHandshake(false)
1985 , connectionEncrypted(false)
1986 , ignoreAllSslErrors(false)
1987 , readyReadEmittedPointer(nullptr)
1988 , allowRootCertOnDemandLoading(true)
1989 , plainSocket(nullptr)
1990 , paused(false)
1991 , flushTriggered(false)
1992{
1993 QSslConfigurationPrivate::deepCopyDefaultConfiguration(&configuration);
1994 // If the global configuration doesn't allow root certificates to be loaded
1995 // on demand then we have to disable it for this socket as well.
1996 if (!configuration.allowRootCertOnDemandLoading)
1997 allowRootCertOnDemandLoading = false;
1998
1999 const auto *tlsBackend = tlsBackendInUse();
2000 if (!tlsBackend) {
2001 qCWarning(lcSsl, "No TLS backend is available");
2002 return;
2003 }
2004 backend.reset(tlsBackend->createTlsCryptograph());
2005 if (!backend.get()) {
2006 qCWarning(lcSsl) << "The backend named" << tlsBackend->backendName()
2007 << "does not support TLS";
2008 }
2009}
2010
2011/*!
2012 \internal
2013*/
2014QSslSocketPrivate::~QSslSocketPrivate()
2015{
2016}
2017
2018/*!
2019 \internal
2020*/
2021bool QSslSocketPrivate::supportsSsl()
2022{
2023 if (const auto *tlsBackend = tlsBackendInUse())
2024 return tlsBackend->implementedClasses().contains(QSsl::ImplementedClass::Socket);
2025 return false;
2026}
2027
2028/*!
2029 \internal
2030
2031 Declared static in QSslSocketPrivate, makes sure the SSL libraries have
2032 been initialized.
2033*/
2034void QSslSocketPrivate::ensureInitialized()
2035{
2036 if (!supportsSsl())
2037 return;
2038
2039 const auto *tlsBackend = tlsBackendInUse();
2040 Q_ASSERT(tlsBackend);
2041 tlsBackend->ensureInitialized();
2042}
2043
2044/*!
2045 \internal
2046*/
2047void QSslSocketPrivate::init()
2048{
2049 // TLSTODO: delete those data members.
2050 mode = QSslSocket::UnencryptedMode;
2051 autoStartHandshake = false;
2052 connectionEncrypted = false;
2053 ignoreAllSslErrors = false;
2054 abortCalled = false;
2055 pendingClose = false;
2056 flushTriggered = false;
2057 // We don't want to clear the ignoreErrorsList, so
2058 // that it is possible setting it before connecting.
2059
2060 buffer.clear();
2061 writeBuffer.clear();
2062 configuration.peerCertificate.clear();
2063 configuration.peerCertificateChain.clear();
2064
2065 if (backend.get()) {
2066 Q_ASSERT(q_ptr);
2067 backend->init(static_cast<QSslSocket *>(q_ptr), this);
2068 }
2069}
2070
2071/*!
2072 \internal
2073*/
2074bool QSslSocketPrivate::verifyProtocolSupported(const char *where)
2075{
2076 auto protocolName = "DTLS"_L1;
2077 switch (configuration.protocol) {
2078 case QSsl::UnknownProtocol:
2079 // UnknownProtocol, according to our docs, is for cipher whose protocol is unknown.
2080 // Should not be used when configuring QSslSocket.
2081 protocolName = "UnknownProtocol"_L1;
2082 Q_FALLTHROUGH();
2083QT_WARNING_PUSH
2084QT_WARNING_DISABLE_DEPRECATED
2085 case QSsl::DtlsV1_0:
2086 case QSsl::DtlsV1_2:
2087 case QSsl::DtlsV1_0OrLater:
2088 case QSsl::DtlsV1_2OrLater:
2089 qCWarning(lcSsl) << where << "QSslConfiguration with unexpected protocol" << protocolName;
2090 setErrorAndEmit(QAbstractSocket::SslInvalidUserDataError,
2091 QSslSocket::tr("Attempted to use an unsupported protocol."));
2092 return false;
2093QT_WARNING_POP
2094 default:
2095 return true;
2096 }
2097}
2098
2099/*!
2100 \internal
2101*/
2102QList<QSslCipher> QSslSocketPrivate::defaultCiphers()
2103{
2104 QSslSocketPrivate::ensureInitialized();
2105 QMutexLocker locker(&globalData()->mutex);
2106 return globalData()->config->ciphers;
2107}
2108
2109/*!
2110 \internal
2111*/
2112QList<QSslCipher> QSslSocketPrivate::supportedCiphers()
2113{
2114 QSslSocketPrivate::ensureInitialized();
2115 QMutexLocker locker(&globalData()->mutex);
2116 return globalData()->supportedCiphers;
2117}
2118
2119/*!
2120 \internal
2121*/
2122void QSslSocketPrivate::setDefaultCiphers(const QList<QSslCipher> &ciphers)
2123{
2124 QMutexLocker locker(&globalData()->mutex);
2125 globalData()->config.detach();
2126 globalData()->config->ciphers = ciphers;
2127}
2128
2129/*!
2130 \internal
2131*/
2132void QSslSocketPrivate::setDefaultSupportedCiphers(const QList<QSslCipher> &ciphers)
2133{
2134 QMutexLocker locker(&globalData()->mutex);
2135 globalData()->config.detach();
2136 globalData()->supportedCiphers = ciphers;
2137}
2138
2139/*!
2140 \internal
2141*/
2142void QSslSocketPrivate::resetDefaultEllipticCurves()
2143{
2144 const auto *tlsBackend = tlsBackendInUse();
2145 if (!tlsBackend)
2146 return;
2147
2148 auto ids = tlsBackend->ellipticCurvesIds();
2149 if (!ids.size())
2150 return;
2151
2152 QList<QSslEllipticCurve> curves;
2153 curves.reserve(ids.size());
2154 for (int id : ids) {
2155 QSslEllipticCurve curve;
2156 curve.id = id;
2157 curves.append(curve);
2158 }
2159
2160 // Set the list of supported ECs, but not the list
2161 // of *default* ECs. OpenSSL doesn't like forcing an EC for the wrong
2162 // ciphersuite, so don't try it -- leave the empty list to mean
2163 // "the implementation will choose the most suitable one".
2164 setDefaultSupportedEllipticCurves(curves);
2165}
2166
2167/*!
2168 \internal
2169*/
2170void QSslSocketPrivate::setDefaultDtlsCiphers(const QList<QSslCipher> &ciphers)
2171{
2172 QMutexLocker locker(&globalData()->mutex);
2173 globalData()->dtlsConfig.detach();
2174 globalData()->dtlsConfig->ciphers = ciphers;
2175}
2176
2177/*!
2178 \internal
2179*/
2180QList<QSslCipher> QSslSocketPrivate::defaultDtlsCiphers()
2181{
2182 QSslSocketPrivate::ensureInitialized();
2183 QMutexLocker locker(&globalData()->mutex);
2184 return globalData()->dtlsConfig->ciphers;
2185}
2186
2187/*!
2188 \internal
2189*/
2190QList<QSslEllipticCurve> QSslSocketPrivate::supportedEllipticCurves()
2191{
2192 QSslSocketPrivate::ensureInitialized();
2193 const QMutexLocker locker(&globalData()->mutex);
2194 return globalData()->supportedEllipticCurves;
2195}
2196
2197/*!
2198 \internal
2199*/
2200void QSslSocketPrivate::setDefaultSupportedEllipticCurves(const QList<QSslEllipticCurve> &curves)
2201{
2202 const QMutexLocker locker(&globalData()->mutex);
2203 globalData()->config.detach();
2204 globalData()->dtlsConfig.detach();
2205 globalData()->supportedEllipticCurves = curves;
2206}
2207
2208/*!
2209 \internal
2210*/
2211QList<QSslCertificate> QSslSocketPrivate::defaultCaCertificates()
2212{
2213 QSslSocketPrivate::ensureInitialized();
2214 QMutexLocker locker(&globalData()->mutex);
2215 return globalData()->config->caCertificates;
2216}
2217
2218/*!
2219 \internal
2220*/
2221void QSslSocketPrivate::setDefaultCaCertificates(const QList<QSslCertificate> &certs)
2222{
2223 QSslSocketPrivate::ensureInitialized();
2224 QMutexLocker locker(&globalData()->mutex);
2225 globalData()->config.detach();
2226 globalData()->config->caCertificates = certs;
2227 globalData()->dtlsConfig.detach();
2228 globalData()->dtlsConfig->caCertificates = certs;
2229 // when the certificates are set explicitly, we do not want to
2230 // load the system certificates on demand
2231 s_loadRootCertsOnDemand = false;
2232}
2233
2234/*!
2235 \internal
2236*/
2237void QSslSocketPrivate::addDefaultCaCertificate(const QSslCertificate &cert)
2238{
2239 QSslSocketPrivate::ensureInitialized();
2240 QMutexLocker locker(&globalData()->mutex);
2241 if (globalData()->config->caCertificates.contains(cert))
2242 return;
2243 globalData()->config.detach();
2244 globalData()->config->caCertificates += cert;
2245 globalData()->dtlsConfig.detach();
2246 globalData()->dtlsConfig->caCertificates += cert;
2247}
2248
2249/*!
2250 \internal
2251*/
2252void QSslSocketPrivate::addDefaultCaCertificates(const QList<QSslCertificate> &certs)
2253{
2254 QSslSocketPrivate::ensureInitialized();
2255 QMutexLocker locker(&globalData()->mutex);
2256 globalData()->config.detach();
2257 globalData()->config->caCertificates += certs;
2258 globalData()->dtlsConfig.detach();
2259 globalData()->dtlsConfig->caCertificates += certs;
2260}
2261
2262/*!
2263 \internal
2264*/
2265QSslConfiguration QSslConfigurationPrivate::defaultConfiguration()
2266{
2267 QSslSocketPrivate::ensureInitialized();
2268 QMutexLocker locker(&globalData()->mutex);
2269 return QSslConfiguration(globalData()->config.data());
2270}
2271
2272/*!
2273 \internal
2274*/
2275void QSslConfigurationPrivate::setDefaultConfiguration(const QSslConfiguration &configuration)
2276{
2277 QSslSocketPrivate::ensureInitialized();
2278 QMutexLocker locker(&globalData()->mutex);
2279 if (globalData()->config == configuration.d)
2280 return; // nothing to do
2281
2282 globalData()->config = const_cast<QSslConfigurationPrivate*>(configuration.d.constData());
2283}
2284
2285/*!
2286 \internal
2287*/
2288void QSslConfigurationPrivate::deepCopyDefaultConfiguration(QSslConfigurationPrivate *ptr)
2289{
2290 QSslSocketPrivate::ensureInitialized();
2291 QMutexLocker locker(&globalData()->mutex);
2292 const QSslConfigurationPrivate *global = globalData()->config.constData();
2293
2294 if (!global)
2295 return;
2296
2297 ptr->ref.storeRelaxed(1);
2298 ptr->peerCertificate = global->peerCertificate;
2299 ptr->peerCertificateChain = global->peerCertificateChain;
2300 ptr->localCertificateChain = global->localCertificateChain;
2301 ptr->privateKey = global->privateKey;
2302 ptr->sessionCipher = global->sessionCipher;
2303 ptr->sessionProtocol = global->sessionProtocol;
2304 ptr->ciphers = global->ciphers;
2305 ptr->caCertificates = global->caCertificates;
2306 ptr->allowRootCertOnDemandLoading = global->allowRootCertOnDemandLoading;
2307 ptr->protocol = global->protocol;
2308 ptr->peerVerifyMode = global->peerVerifyMode;
2309 ptr->peerVerifyDepth = global->peerVerifyDepth;
2310 ptr->sslOptions = global->sslOptions;
2311 ptr->ellipticCurves = global->ellipticCurves;
2312 ptr->backendConfig = global->backendConfig;
2313#if QT_CONFIG(dtls)
2314 ptr->dtlsCookieEnabled = global->dtlsCookieEnabled;
2315#endif
2316#if QT_CONFIG(ocsp)
2317 ptr->ocspStaplingEnabled = global->ocspStaplingEnabled;
2318#endif
2319#if QT_CONFIG(openssl)
2320 ptr->reportFromCallback = global->reportFromCallback;
2321 ptr->missingCertIsFatal = global->missingCertIsFatal;
2322#endif
2323}
2324
2325/*!
2326 \internal
2327*/
2328QSslConfiguration QSslConfigurationPrivate::defaultDtlsConfiguration()
2329{
2330 QSslSocketPrivate::ensureInitialized();
2331 QMutexLocker locker(&globalData()->mutex);
2332
2333 return QSslConfiguration(globalData()->dtlsConfig.data());
2334}
2335
2336/*!
2337 \internal
2338*/
2339void QSslConfigurationPrivate::setDefaultDtlsConfiguration(const QSslConfiguration &configuration)
2340{
2341 QSslSocketPrivate::ensureInitialized();
2342 QMutexLocker locker(&globalData()->mutex);
2343 if (globalData()->dtlsConfig == configuration.d)
2344 return; // nothing to do
2345
2346 globalData()->dtlsConfig = const_cast<QSslConfigurationPrivate*>(configuration.d.constData());
2347}
2348
2349/*!
2350 \internal
2351*/
2352void QSslSocketPrivate::createPlainSocket(QIODevice::OpenMode openMode)
2353{
2354 Q_Q(QSslSocket);
2355 q->setOpenMode(openMode); // <- from QIODevice
2356 q->setSocketState(QAbstractSocket::UnconnectedState);
2357 q->setSocketError(QAbstractSocket::UnknownSocketError);
2358 q->setLocalPort(0);
2359 q->setLocalAddress(QHostAddress());
2360 q->setPeerPort(0);
2361 q->setPeerAddress(QHostAddress());
2362 q->setPeerName(QString());
2363
2364 plainSocket = new QTcpSocket(q);
2365 q->connect(plainSocket, SIGNAL(connected()),
2366 q, SLOT(_q_connectedSlot()),
2367 Qt::DirectConnection);
2368 q->connect(plainSocket, SIGNAL(hostFound()),
2369 q, SLOT(_q_hostFoundSlot()),
2370 Qt::DirectConnection);
2371 q->connect(plainSocket, SIGNAL(disconnected()),
2372 q, SLOT(_q_disconnectedSlot()),
2373 Qt::DirectConnection);
2374 q->connect(plainSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
2375 q, SLOT(_q_stateChangedSlot(QAbstractSocket::SocketState)),
2376 Qt::DirectConnection);
2377 q->connect(plainSocket, SIGNAL(errorOccurred(QAbstractSocket::SocketError)),
2378 q, SLOT(_q_errorSlot(QAbstractSocket::SocketError)),
2379 Qt::DirectConnection);
2380 q->connect(plainSocket, SIGNAL(readyRead()),
2381 q, SLOT(_q_readyReadSlot()),
2382 Qt::DirectConnection);
2383 q->connect(plainSocket, SIGNAL(channelReadyRead(int)),
2384 q, SLOT(_q_channelReadyReadSlot(int)),
2385 Qt::DirectConnection);
2386 q->connect(plainSocket, SIGNAL(bytesWritten(qint64)),
2387 q, SLOT(_q_bytesWrittenSlot(qint64)),
2388 Qt::DirectConnection);
2389 q->connect(plainSocket, SIGNAL(channelBytesWritten(int,qint64)),
2390 q, SLOT(_q_channelBytesWrittenSlot(int,qint64)),
2391 Qt::DirectConnection);
2392 q->connect(plainSocket, SIGNAL(readChannelFinished()),
2393 q, SLOT(_q_readChannelFinishedSlot()),
2394 Qt::DirectConnection);
2395#ifndef QT_NO_NETWORKPROXY
2396 q->connect(plainSocket, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
2397 q, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
2398#endif
2399
2400 buffer.clear();
2401 writeBuffer.clear();
2402 connectionEncrypted = false;
2403 configuration.peerCertificate.clear();
2404 configuration.peerCertificateChain.clear();
2405 mode = QSslSocket::UnencryptedMode;
2406 q->setReadBufferSize(readBufferMaxSize);
2407}
2408
2409void QSslSocketPrivate::pauseSocketNotifiers(QSslSocket *socket)
2410{
2411 if (!socket->d_func()->plainSocket)
2412 return;
2413 QAbstractSocketPrivate::pauseSocketNotifiers(socket->d_func()->plainSocket);
2414}
2415
2416void QSslSocketPrivate::resumeSocketNotifiers(QSslSocket *socket)
2417{
2418 if (!socket->d_func()->plainSocket)
2419 return;
2420 QAbstractSocketPrivate::resumeSocketNotifiers(socket->d_func()->plainSocket);
2421}
2422
2423bool QSslSocketPrivate::isPaused() const
2424{
2425 return paused;
2426}
2427
2428void QSslSocketPrivate::setPaused(bool p)
2429{
2430 paused = p;
2431}
2432
2433bool QSslSocketPrivate::bind(const QHostAddress &address, quint16 port, QAbstractSocket::BindMode mode,
2434 const QNetworkInterface *iface)
2435{
2436 Q_UNUSED(iface); // only relevant for QUdpSocket for now
2437 // this function is called from QAbstractSocket::bind
2438 if (!initialized)
2439 init();
2440 initialized = false;
2441
2442#ifdef QSSLSOCKET_DEBUG
2443 qCDebug(lcSsl) << "QSslSocket::bind(" << address << ',' << port << ',' << mode << ')';
2444#endif
2445 if (!plainSocket) {
2446#ifdef QSSLSOCKET_DEBUG
2447 qCDebug(lcSsl) << "\tcreating internal plain socket";
2448#endif
2449 createPlainSocket(QIODevice::ReadWrite);
2450 }
2451 bool ret = plainSocket->bind(address, port, mode);
2452 localPort = plainSocket->localPort();
2453 localAddress = plainSocket->localAddress();
2454 cachedSocketDescriptor = plainSocket->socketDescriptor();
2455 readChannelCount = writeChannelCount = 0;
2456 return ret;
2457}
2458
2459/*!
2460 \internal
2461*/
2462void QSslSocketPrivate::_q_connectedSlot()
2463{
2464 Q_Q(QSslSocket);
2465 q->setLocalPort(plainSocket->localPort());
2466 q->setLocalAddress(plainSocket->localAddress());
2467 q->setPeerPort(plainSocket->peerPort());
2468 q->setPeerAddress(plainSocket->peerAddress());
2469 q->setPeerName(plainSocket->peerName());
2470 cachedSocketDescriptor = plainSocket->socketDescriptor();
2471 readChannelCount = plainSocket->readChannelCount();
2472 writeChannelCount = plainSocket->writeChannelCount();
2473
2474#ifdef QSSLSOCKET_DEBUG
2475 qCDebug(lcSsl) << "QSslSocket::_q_connectedSlot()";
2476 qCDebug(lcSsl) << "\tstate =" << q->state();
2477 qCDebug(lcSsl) << "\tpeer =" << q->peerName() << q->peerAddress() << q->peerPort();
2478 qCDebug(lcSsl) << "\tlocal =" << QHostInfo::fromName(q->localAddress().toString()).hostName()
2479 << q->localAddress() << q->localPort();
2480#endif
2481
2482 if (autoStartHandshake)
2483 q->startClientEncryption();
2484
2485 emit q->connected();
2486
2487 if (pendingClose && !autoStartHandshake) {
2488 pendingClose = false;
2489 q->disconnectFromHost();
2490 }
2491}
2492
2493/*!
2494 \internal
2495*/
2496void QSslSocketPrivate::_q_hostFoundSlot()
2497{
2498 Q_Q(QSslSocket);
2499#ifdef QSSLSOCKET_DEBUG
2500 qCDebug(lcSsl) << "QSslSocket::_q_hostFoundSlot()";
2501 qCDebug(lcSsl) << "\tstate =" << q->state();
2502#endif
2503 emit q->hostFound();
2504}
2505
2506/*!
2507 \internal
2508*/
2509void QSslSocketPrivate::_q_disconnectedSlot()
2510{
2511 Q_Q(QSslSocket);
2512#ifdef QSSLSOCKET_DEBUG
2513 qCDebug(lcSsl) << "QSslSocket::_q_disconnectedSlot()";
2514 qCDebug(lcSsl) << "\tstate =" << q->state();
2515#endif
2516 disconnected();
2517 emit q->disconnected();
2518
2519 q->setLocalPort(0);
2520 q->setLocalAddress(QHostAddress());
2521 q->setPeerPort(0);
2522 q->setPeerAddress(QHostAddress());
2523 q->setPeerName(QString());
2524 cachedSocketDescriptor = -1;
2525}
2526
2527/*!
2528 \internal
2529*/
2530void QSslSocketPrivate::_q_stateChangedSlot(QAbstractSocket::SocketState state)
2531{
2532 Q_Q(QSslSocket);
2533#ifdef QSSLSOCKET_DEBUG
2534 qCDebug(lcSsl) << "QSslSocket::_q_stateChangedSlot(" << state << ')';
2535#endif
2536 q->setSocketState(state);
2537 emit q->stateChanged(state);
2538}
2539
2540/*!
2541 \internal
2542*/
2543void QSslSocketPrivate::_q_errorSlot(QAbstractSocket::SocketError error)
2544{
2545 Q_UNUSED(error);
2546#ifdef QSSLSOCKET_DEBUG
2547 Q_Q(QSslSocket);
2548 qCDebug(lcSsl) << "QSslSocket::_q_errorSlot(" << error << ')';
2549 qCDebug(lcSsl) << "\tstate =" << q->state();
2550 qCDebug(lcSsl) << "\terrorString =" << q->errorString();
2551#endif
2552 // this moves encrypted bytes from plain socket into our buffer
2553 if (plainSocket->bytesAvailable() && mode != QSslSocket::UnencryptedMode) {
2554 qint64 tmpReadBufferMaxSize = readBufferMaxSize;
2555 readBufferMaxSize = 0; // reset temporarily so the plain sockets completely drained drained
2556 transmit();
2557 readBufferMaxSize = tmpReadBufferMaxSize;
2558 }
2559
2560 setErrorAndEmit(plainSocket->error(), plainSocket->errorString());
2561}
2562
2563/*!
2564 \internal
2565*/
2566void QSslSocketPrivate::_q_readyReadSlot()
2567{
2568 Q_Q(QSslSocket);
2569#ifdef QSSLSOCKET_DEBUG
2570 qCDebug(lcSsl) << "QSslSocket::_q_readyReadSlot() -" << plainSocket->bytesAvailable() << "bytes available";
2571#endif
2572 if (mode == QSslSocket::UnencryptedMode) {
2573 if (readyReadEmittedPointer)
2574 *readyReadEmittedPointer = true;
2575 emit q->readyRead();
2576 return;
2577 }
2578
2579 transmit();
2580}
2581
2582/*!
2583 \internal
2584*/
2585void QSslSocketPrivate::_q_channelReadyReadSlot(int channel)
2586{
2587 Q_Q(QSslSocket);
2588 if (mode == QSslSocket::UnencryptedMode)
2589 emit q->channelReadyRead(channel);
2590}
2591
2592/*!
2593 \internal
2594*/
2595void QSslSocketPrivate::_q_bytesWrittenSlot(qint64 written)
2596{
2597 Q_Q(QSslSocket);
2598#ifdef QSSLSOCKET_DEBUG
2599 qCDebug(lcSsl) << "QSslSocket::_q_bytesWrittenSlot(" << written << ')';
2600#endif
2601
2602 if (mode == QSslSocket::UnencryptedMode)
2603 emit q->bytesWritten(written);
2604 else
2605 emit q->encryptedBytesWritten(written);
2606 if (state == QAbstractSocket::ClosingState && writeBuffer.isEmpty())
2607 q->disconnectFromHost();
2608}
2609
2610/*!
2611 \internal
2612*/
2613void QSslSocketPrivate::_q_channelBytesWrittenSlot(int channel, qint64 written)
2614{
2615 Q_Q(QSslSocket);
2616 if (mode == QSslSocket::UnencryptedMode)
2617 emit q->channelBytesWritten(channel, written);
2618}
2619
2620/*!
2621 \internal
2622*/
2623void QSslSocketPrivate::_q_readChannelFinishedSlot()
2624{
2625 Q_Q(QSslSocket);
2626 emit q->readChannelFinished();
2627}
2628
2629/*!
2630 \internal
2631*/
2632void QSslSocketPrivate::_q_flushWriteBuffer()
2633{
2634 Q_Q(QSslSocket);
2635
2636 // need to notice if knock-on effects of this flush (e.g. a readReady() via transmit())
2637 // make another necessary, so clear flag before calling:
2638 flushTriggered = false;
2639 if (!writeBuffer.isEmpty())
2640 q->flush();
2641}
2642
2643/*!
2644 \internal
2645*/
2646void QSslSocketPrivate::_q_flushReadBuffer()
2647{
2648 // trigger a read from the plainSocket into SSL
2649 if (mode != QSslSocket::UnencryptedMode)
2650 transmit();
2651}
2652
2653/*!
2654 \internal
2655*/
2656void QSslSocketPrivate::_q_resumeImplementation()
2657{
2658 if (plainSocket)
2659 plainSocket->resume();
2660 paused = false;
2661 if (!connectionEncrypted) {
2662 if (verifyErrorsHaveBeenIgnored()) {
2663 continueHandshake();
2664 } else {
2665 const auto sslErrors = backend->tlsErrors();
2666 Q_ASSERT(!sslErrors.isEmpty());
2667 setErrorAndEmit(QAbstractSocket::SslHandshakeFailedError, sslErrors.constFirst().errorString());
2668 plainSocket->disconnectFromHost();
2669 return;
2670 }
2671 }
2672 transmit();
2673}
2674
2675/*!
2676 \internal
2677*/
2678bool QSslSocketPrivate::verifyErrorsHaveBeenIgnored()
2679{
2680 Q_ASSERT(backend.get());
2681
2682 bool doEmitSslError;
2683 if (!ignoreErrorsList.empty()) {
2684 // check whether the errors we got are all in the list of expected errors
2685 // (applies only if the method QSslSocket::ignoreSslErrors(const QList<QSslError> &errors)
2686 // was called)
2687 const auto &sslErrors = backend->tlsErrors();
2688 doEmitSslError = false;
2689 for (int a = 0; a < sslErrors.size(); a++) {
2690 if (!ignoreErrorsList.contains(sslErrors.at(a))) {
2691 doEmitSslError = true;
2692 break;
2693 }
2694 }
2695 } else {
2696 // if QSslSocket::ignoreSslErrors(const QList<QSslError> &errors) was not called and
2697 // we get an SSL error, emit a signal unless we ignored all errors (by calling
2698 // QSslSocket::ignoreSslErrors() )
2699 doEmitSslError = !ignoreAllSslErrors;
2700 }
2701 return !doEmitSslError;
2702}
2703
2704/*!
2705 \internal
2706*/
2707bool QSslSocketPrivate::isAutoStartingHandshake() const
2708{
2709 return autoStartHandshake;
2710}
2711
2712/*!
2713 \internal
2714*/
2715bool QSslSocketPrivate::isPendingClose() const
2716{
2717 return pendingClose;
2718}
2719
2720/*!
2721 \internal
2722*/
2723void QSslSocketPrivate::setPendingClose(bool pc)
2724{
2725 pendingClose = pc;
2726}
2727
2728/*!
2729 \internal
2730*/
2731qint64 QSslSocketPrivate::maxReadBufferSize() const
2732{
2733 return readBufferMaxSize;
2734}
2735
2736/*!
2737 \internal
2738*/
2739void QSslSocketPrivate::setMaxReadBufferSize(qint64 maxSize)
2740{
2741 readBufferMaxSize = maxSize;
2742}
2743
2744/*!
2745 \internal
2746*/
2747void QSslSocketPrivate::setEncrypted(bool enc)
2748{
2749 connectionEncrypted = enc;
2750}
2751
2752/*!
2753 \internal
2754*/
2755QIODevicePrivate::QRingBufferRef &QSslSocketPrivate::tlsWriteBuffer()
2756{
2757 return writeBuffer;
2758}
2759
2760/*!
2761 \internal
2762*/
2763QIODevicePrivate::QRingBufferRef &QSslSocketPrivate::tlsBuffer()
2764{
2765 return buffer;
2766}
2767
2768/*!
2769 \internal
2770*/
2771bool &QSslSocketPrivate::tlsEmittedBytesWritten()
2772{
2773 return emittedBytesWritten;
2774}
2775
2776/*!
2777 \internal
2778*/
2779bool *QSslSocketPrivate::readyReadPointer()
2780{
2781 return readyReadEmittedPointer;
2782}
2783
2784bool QSslSocketPrivate::hasUndecryptedData() const
2785{
2786 return backend.get() && backend->hasUndecryptedData();
2787}
2788
2789/*!
2790 \internal
2791*/
2792qint64 QSslSocketPrivate::peek(char *data, qint64 maxSize)
2793{
2794 if (mode == QSslSocket::UnencryptedMode && !autoStartHandshake) {
2795 //unencrypted mode - do not use QIODevice::peek, as it reads ahead data from the plain socket
2796 //peek at data already in the QIODevice buffer (from a previous read)
2797 qint64 r = buffer.peek(data, maxSize, transactionPos);
2798 if (r == maxSize)
2799 return r;
2800 data += r;
2801 //peek at data in the plain socket
2802 if (plainSocket) {
2803 qint64 r2 = plainSocket->peek(data, maxSize - r);
2804 if (r2 < 0)
2805 return (r > 0 ? r : r2);
2806 return r + r2;
2807 }
2808
2809 return -1;
2810 } else {
2811 //encrypted mode - the socket engine will read and decrypt data into the QIODevice buffer
2812 return QTcpSocketPrivate::peek(data, maxSize);
2813 }
2814}
2815
2816/*!
2817 \internal
2818*/
2819QByteArray QSslSocketPrivate::peek(qint64 maxSize)
2820{
2821 if (mode == QSslSocket::UnencryptedMode && !autoStartHandshake) {
2822 //unencrypted mode - do not use QIODevice::peek, as it reads ahead data from the plain socket
2823 //peek at data already in the QIODevice buffer (from a previous read)
2824 QByteArray ret;
2825 ret.reserve(maxSize);
2826 ret.resize(buffer.peek(ret.data(), maxSize, transactionPos));
2827 if (ret.size() == maxSize)
2828 return ret;
2829 //peek at data in the plain socket
2830 if (plainSocket)
2831 return ret + plainSocket->peek(maxSize - ret.size());
2832
2833 return QByteArray();
2834 } else {
2835 //encrypted mode - the socket engine will read and decrypt data into the QIODevice buffer
2836 return QTcpSocketPrivate::peek(maxSize);
2837 }
2838}
2839
2840/*!
2841 \reimp
2842*/
2843qint64 QSslSocket::skipData(qint64 maxSize)
2844{
2845 Q_D(QSslSocket);
2846
2847 if (d->mode == QSslSocket::UnencryptedMode && !d->autoStartHandshake)
2848 return d->plainSocket->skip(maxSize);
2849
2850 // In encrypted mode, the SSL backend writes decrypted data directly into the
2851 // QIODevice's read buffer. As this buffer is always emptied by the caller,
2852 // we need to wait for more incoming data.
2853 return (d->state == QAbstractSocket::ConnectedState) ? Q_INT64_C(0) : Q_INT64_C(-1);
2854}
2855
2856/*!
2857 \internal
2858*/
2859bool QSslSocketPrivate::flush()
2860{
2861#ifdef QSSLSOCKET_DEBUG
2862 qCDebug(lcSsl) << "QSslSocketPrivate::flush()";
2863#endif
2864 if (mode != QSslSocket::UnencryptedMode) {
2865 // encrypt any unencrypted bytes in our buffer
2866 transmit();
2867 }
2868
2869 return plainSocket && plainSocket->flush();
2870}
2871
2872/*!
2873 \internal
2874*/
2875void QSslSocketPrivate::startClientEncryption()
2876{
2877 if (backend.get())
2878 backend->startClientEncryption();
2879}
2880
2881/*!
2882 \internal
2883*/
2884void QSslSocketPrivate::startServerEncryption()
2885{
2886 if (backend.get())
2887 backend->startServerEncryption();
2888}
2889
2890/*!
2891 \internal
2892*/
2893void QSslSocketPrivate::transmit()
2894{
2895 if (backend.get())
2896 backend->transmit();
2897}
2898
2899/*!
2900 \internal
2901*/
2902void QSslSocketPrivate::disconnectFromHost()
2903{
2904 if (backend.get())
2905 backend->disconnectFromHost();
2906}
2907
2908/*!
2909 \internal
2910*/
2911void QSslSocketPrivate::disconnected()
2912{
2913 if (backend.get())
2914 backend->disconnected();
2915}
2916
2917/*!
2918 \internal
2919*/
2920QSslCipher QSslSocketPrivate::sessionCipher() const
2921{
2922 if (backend.get())
2923 return backend->sessionCipher();
2924
2925 return {};
2926}
2927
2928/*!
2929 \internal
2930*/
2931QSsl::SslProtocol QSslSocketPrivate::sessionProtocol() const
2932{
2933 if (backend.get())
2934 return backend->sessionProtocol();
2935
2936 return QSsl::UnknownProtocol;
2937}
2938
2939/*!
2940 \internal
2941*/
2942void QSslSocketPrivate::continueHandshake()
2943{
2944 if (backend.get())
2945 backend->continueHandshake();
2946}
2947
2948/*!
2949 \internal
2950*/
2951bool QSslSocketPrivate::rootCertOnDemandLoadingSupported()
2952{
2953 return s_loadRootCertsOnDemand;
2954}
2955
2956/*!
2957 \internal
2958*/
2959void QSslSocketPrivate::setRootCertOnDemandLoadingSupported(bool supported)
2960{
2961 s_loadRootCertsOnDemand = supported;
2962}
2963
2964/*!
2965 \internal
2966*/
2967QList<QByteArray> QSslSocketPrivate::unixRootCertDirectories()
2968{
2969 const auto ba = [](const auto &cstr) constexpr {
2970 return QByteArray::fromRawData(std::begin(cstr), std::size(cstr) - 1);
2971 };
2972 static const QByteArray dirs[] = {
2973 ba("/etc/ssl/certs/"), // (K)ubuntu, OpenSUSE, Mandriva ...
2974 ba("/usr/lib/ssl/certs/"), // Gentoo, Mandrake
2975 ba("/usr/share/ssl/"), // Red Hat pre-2004, SuSE
2976 ba("/etc/pki/ca-trust/extracted/pem/directory-hash/"), // Red Hat 2021+
2977 ba("/usr/local/ssl/"), // Normal OpenSSL Tarball
2978 ba("/var/ssl/certs/"), // AIX
2979 ba("/usr/local/ssl/certs/"), // Solaris
2980 ba("/etc/openssl/certs/"), // BlackBerry
2981 ba("/opt/openssl/certs/"), // HP-UX
2982 ba("/etc/ssl/"), // OpenBSD
2983 ba("/etc/security/certificates/"), // HarmonyOS
2984 };
2985 QList<QByteArray> result = QList<QByteArray>::fromReadOnlyData(dirs);
2986 if constexpr (isVxworks) {
2987 static QByteArray vxworksCertsDir = qgetenv("VXWORKS_CERTS_DIR");
2988 if (!vxworksCertsDir.isEmpty())
2989 result.push_back(vxworksCertsDir);
2990 }
2991 return result;
2992}
2993
2994/*!
2995 \internal
2996*/
2997void QSslSocketPrivate::checkSettingSslContext(QSslSocket* socket, std::shared_ptr<QSslContext> tlsContext)
2998{
2999 if (!socket)
3000 return;
3001
3002 if (auto *backend = socket->d_func()->backend.get())
3003 backend->checkSettingSslContext(tlsContext);
3004}
3005
3006/*!
3007 \internal
3008*/
3009std::shared_ptr<QSslContext> QSslSocketPrivate::sslContext(QSslSocket *socket)
3010{
3011 if (!socket)
3012 return {};
3013
3014 if (const auto *backend = socket->d_func()->backend.get())
3015 return backend->sslContext();
3016
3017 return {};
3018}
3019
3020bool QSslSocketPrivate::isMatchingHostname(const QSslCertificate &cert, const QString &peerName)
3021{
3022 QHostAddress hostAddress(peerName);
3023 if (!hostAddress.isNull()) {
3024 const auto subjectAlternativeNames = cert.subjectAlternativeNames();
3025 const auto ipAddresses = subjectAlternativeNames.equal_range(QSsl::AlternativeNameEntryType::IpAddressEntry);
3026
3027 for (auto it = ipAddresses.first; it != ipAddresses.second; it++) {
3028 if (QHostAddress(*it).isEqual(hostAddress, QHostAddress::StrictConversion))
3029 return true;
3030 }
3031 }
3032
3033 const QString lowerPeerName = QString::fromLatin1(QUrl::toAce(peerName));
3034 const QStringList commonNames = cert.subjectInfo(QSslCertificate::CommonName);
3035
3036 for (const QString &commonName : commonNames) {
3037 if (isMatchingHostname(commonName, lowerPeerName))
3038 return true;
3039 }
3040
3041 const auto subjectAlternativeNames = cert.subjectAlternativeNames();
3042 const auto altNames = subjectAlternativeNames.equal_range(QSsl::DnsEntry);
3043 for (auto it = altNames.first; it != altNames.second; ++it) {
3044 if (isMatchingHostname(*it, lowerPeerName))
3045 return true;
3046 }
3047
3048 return false;
3049}
3050
3051/*! \internal
3052 Checks if the certificate's name \a cn matches the \a hostname.
3053 \a hostname must be normalized in ASCII-Compatible Encoding, but \a cn is not normalized
3054 */
3055bool QSslSocketPrivate::isMatchingHostname(const QString &cn, const QString &hostname)
3056{
3057 qsizetype wildcard = cn.indexOf(u'*');
3058
3059 // Check this is a wildcard cert, if not then just compare the strings
3060 if (wildcard < 0)
3061 return QLatin1StringView(QUrl::toAce(cn)) == hostname;
3062
3063 qsizetype firstCnDot = cn.indexOf(u'.');
3064 qsizetype secondCnDot = cn.indexOf(u'.', firstCnDot+1);
3065
3066 // Check at least 3 components
3067 if ((-1 == secondCnDot) || (secondCnDot+1 >= cn.size()))
3068 return false;
3069
3070 // Check * is last character of 1st component (ie. there's a following .)
3071 if (wildcard+1 != firstCnDot)
3072 return false;
3073
3074 // Check only one star
3075 if (cn.lastIndexOf(u'*') != wildcard)
3076 return false;
3077
3078 // Reject wildcard character embedded within the A-labels or U-labels of an internationalized
3079 // domain name (RFC6125 section 7.2)
3080 if (cn.startsWith("xn--"_L1, Qt::CaseInsensitive))
3081 return false;
3082
3083 // Check characters preceding * (if any) match
3084 if (wildcard && QStringView{hostname}.left(wildcard).compare(QStringView{cn}.left(wildcard), Qt::CaseInsensitive) != 0)
3085 return false;
3086
3087 // Check characters following first . match
3088 qsizetype hnDot = hostname.indexOf(u'.');
3089 if (QStringView{hostname}.mid(hnDot + 1) != QStringView{cn}.mid(firstCnDot + 1)
3090 && QStringView{hostname}.mid(hnDot + 1) != QLatin1StringView(QUrl::toAce(cn.mid(firstCnDot + 1)))) {
3091 return false;
3092 }
3093
3094 // Check if the hostname is an IP address, if so then wildcards are not allowed
3095 QHostAddress addr(hostname);
3096 if (!addr.isNull())
3097 return false;
3098
3099 // Ok, I guess this was a wildcard CN and the hostname matches.
3100 return true;
3101}
3102
3103/*!
3104 \internal
3105*/
3106QTlsBackend *QSslSocketPrivate::tlsBackendInUse()
3107{
3108 const QMutexLocker locker(&backendMutex);
3109 if (tlsBackend)
3110 return tlsBackend;
3111
3112 if (!activeBackendName.size())
3113 activeBackendName = QTlsBackend::defaultBackendName();
3114
3115 if (!activeBackendName.size()) {
3116 qCWarning(lcSsl, "No functional TLS backend was found");
3117 return nullptr;
3118 }
3119
3120 tlsBackend = QTlsBackend::findBackend(activeBackendName);
3121 if (tlsBackend) {
3122 QObject::connect(tlsBackend, &QObject::destroyed, tlsBackend, [] {
3123 const QMutexLocker locker(&backendMutex);
3124 tlsBackend = nullptr;
3125 },
3126 Qt::DirectConnection);
3127 }
3128 return tlsBackend;
3129}
3130
3131/*!
3132 \internal
3133*/
3134QSslSocket::SslMode QSslSocketPrivate::tlsMode() const
3135{
3136 return mode;
3137}
3138
3139/*!
3140 \internal
3141*/
3142bool QSslSocketPrivate::isRootsOnDemandAllowed() const
3143{
3144 return allowRootCertOnDemandLoading;
3145}
3146
3147/*!
3148 \internal
3149*/
3150QString QSslSocketPrivate::verificationName() const
3151{
3152 return verificationPeerName;
3153}
3154
3155/*!
3156 \internal
3157*/
3158QString QSslSocketPrivate::tlsHostName() const
3159{
3160 return hostName;
3161}
3162
3163QTcpSocket *QSslSocketPrivate::plainTcpSocket() const
3164{
3165 return plainSocket;
3166}
3167
3168/*!
3169 \internal
3170*/
3171QList<QSslCertificate> QSslSocketPrivate::systemCaCertificates()
3172{
3173 if (const auto *tlsBackend = tlsBackendInUse())
3174 return tlsBackend->systemCaCertificates();
3175 return {};
3176}
3177
3178QT_END_NAMESPACE
3179
3180#include "moc_qsslsocket.cpp"
Definition qlist.h:82
Represents an elliptic curve for use by elliptic-curve cipher algorithms.
QList< QSslCipher > supportedCiphers
QList< QSslEllipticCurve > supportedEllipticCurves
QExplicitlySharedDataPointer< QSslConfigurationPrivate > dtlsConfig
QExplicitlySharedDataPointer< QSslConfigurationPrivate > config
Combined button and popup list for selecting options.
constexpr auto isVxworks