Debian Codegraph @

src/network/ssl/qsslsocket.cpp

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