1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
43 //#define QSSLSOCKET_DEBUG
47 \brief The QSslSocket class provides an SSL encrypted socket for both
56 QSslSocket establishes a secure, encrypted TCP connection you can
57 use for transmitting encrypted data. It can operate in both client
58 and server mode, and it supports modern SSL protocols, including
59 SSLv3 and TLSv1_0. By default, QSslSocket uses TLSv1_0, but you can
60 change the SSL protocol by calling setProtocol() as long as you do
61 it before the handshake has started.
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.
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
74 \snippet code/src_network_ssl_qsslsocket.cpp 0
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.
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.
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().
97 \snippet code/src_network_ssl_qsslsocket.cpp 1
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
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.
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.
125 \snippet code/src_network_ssl_qsslsocket.cpp 2
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.
132 The following features can also be customized:
135 \li The socket's cryptographic cipher suite can be customized before
136 the handshake phase with setCiphers() and setDefaultCiphers().
137 \li The socket's local certificate and private key can be customized
138 before the handshake phase with setLocalCertificate() and
140 \li The CA certificate database can be extended and customized with
141 addCaCertificate(), addCaCertificates(), setCaCertificates(),
142 addDefaultCaCertificate(), addDefaultCaCertificates(), and
143 setDefaultCaCertificates().
146 \note If available, root certificates on Unix (excluding Mac OS X) will be
147 loaded on demand from the standard certificate directories. If
148 you do not want to load root certificates on demand, you need to call either
149 the static function setDefaultCaCertificates() before the first SSL handshake
150 is made in your application, (e.g. via
151 "QSslSocket::setDefaultCaCertificates(QSslSocket::systemCaCertificates());"),
152 or call setCaCertificates() on your QSslSocket instance prior to the SSL
155 For more information about ciphers and certificates, refer to QSslCipher and
158 This product includes software developed by the OpenSSL Project
159 for use in the OpenSSL Toolkit (\l{http://www.openssl.org/}).
161 \note Be aware of the difference between the bytesWritten() signal and
162 the encryptedBytesWritten() signal. For a QTcpSocket, bytesWritten()
163 will get emitted as soon as data has been written to the TCP socket.
164 For a QSslSocket, bytesWritten() will get emitted when the data
165 is being encrypted and encryptedBytesWritten()
166 will get emitted as soon as data has been written to the TCP socket.
168 \sa QSslCertificate, QSslCipher, QSslError
172 \enum QSslSocket::SslMode
174 Describes the connection modes available for QSslSocket.
176 \value UnencryptedMode The socket is unencrypted. Its
177 behavior is identical to QTcpSocket.
179 \value SslClientMode The socket is a client-side SSL socket.
180 It is either alreayd encrypted, or it is in the SSL handshake
181 phase (see QSslSocket::isEncrypted()).
183 \value SslServerMode The socket is a server-side SSL socket.
184 It is either already encrypted, or it is in the SSL handshake
185 phase (see QSslSocket::isEncrypted()).
189 \enum QSslSocket::PeerVerifyMode
192 Describes the peer verification modes for QSslSocket. The default mode is
193 AutoVerifyPeer, which selects an appropriate mode depending on the
194 socket's QSocket::SslMode.
196 \value VerifyNone QSslSocket will not request a certificate from the
197 peer. You can set this mode if you are not interested in the identity of
198 the other side of the connection. The connection will still be encrypted,
199 and your socket will still send its local certificate to the peer if it's
202 \value QueryPeer QSslSocket will request a certificate from the peer, but
203 does not require this certificate to be valid. This is useful when you
204 want to display peer certificate details to the user without affecting the
205 actual SSL handshake. This mode is the default for servers.
207 \value VerifyPeer QSslSocket will request a certificate from the peer
208 during the SSL handshake phase, and requires that this certificate is
209 valid. On failure, QSslSocket will emit the QSslSocket::sslErrors()
210 signal. This mode is the default for clients.
212 \value AutoVerifyPeer QSslSocket will automatically use QueryPeer for
213 server sockets and VerifyPeer for client sockets.
215 \sa QSslSocket::peerVerifyMode()
219 \fn QSslSocket::encrypted()
221 This signal is emitted when QSslSocket enters encrypted mode. After this
222 signal has been emitted, QSslSocket::isEncrypted() will return true, and
223 all further transmissions on the socket will be encrypted.
225 \sa QSslSocket::connectToHostEncrypted(), QSslSocket::isEncrypted()
229 \fn QSslSocket::modeChanged(QSslSocket::SslMode mode)
231 This signal is emitted when QSslSocket changes from \l
232 QSslSocket::UnencryptedMode to either \l QSslSocket::SslClientMode or \l
233 QSslSocket::SslServerMode. \a mode is the new mode.
235 \sa QSslSocket::mode()
239 \fn QSslSocket::encryptedBytesWritten(qint64 written)
242 This signal is emitted when QSslSocket writes its encrypted data to the
243 network. The \a written parameter contains the number of bytes that were
244 successfully written.
246 \sa QIODevice::bytesWritten()
250 \fn void QSslSocket::peerVerifyError(const QSslError &error)
253 QSslSocket can emit this signal several times during the SSL handshake,
254 before encryption has been established, to indicate that an error has
255 occurred while establishing the identity of the peer. The \a error is
256 usually an indication that QSslSocket is unable to securely identify the
259 This signal provides you with an early indication when something's wrong.
260 By connecting to this signal, you can manually choose to tear down the
261 connection from inside the connected slot before the handshake has
262 completed. If no action is taken, QSslSocket will proceed to emitting
263 QSslSocket::sslErrors().
269 \fn void QSslSocket::sslErrors(const QList<QSslError> &errors);
271 QSslSocket emits this signal after the SSL handshake to indicate that one
272 or more errors have occurred while establishing the identity of the
273 peer. The errors are usually an indication that QSslSocket is unable to
274 securely identify the peer. Unless any action is taken, the connection
275 will be dropped after this signal has been emitted.
277 If you want to continue connecting despite the errors that have occurred,
278 you must call QSslSocket::ignoreSslErrors() from inside a slot connected to
279 this signal. If you need to access the error list at a later point, you
280 can call sslErrors() (without arguments).
282 \a errors contains one or more errors that prevent QSslSocket from
283 verifying the identity of the peer.
285 Note: You cannot use Qt::QueuedConnection when connecting to this signal,
286 or calling QSslSocket::ignoreSslErrors() will have no effect.
288 \sa peerVerifyError()
291 #include "qsslcipher.h"
292 #include "qsslsocket.h"
293 #include "qsslsocket_openssl_p.h"
294 #include "qsslconfiguration_p.h"
296 #include <QtCore/qdebug.h>
297 #include <QtCore/qdir.h>
298 #include <QtCore/qmutex.h>
299 #include <QtCore/qelapsedtimer.h>
300 #include <QtNetwork/qhostaddress.h>
301 #include <QtNetwork/qhostinfo.h>
306 Returns the difference between msecs and elapsed. If msecs is -1,
307 however, -1 is returned.
309 static int qt_timeout_value(int msecs, int elapsed)
314 int timeout = msecs - elapsed;
315 return timeout < 0 ? 0 : timeout;
318 class QSslSocketGlobalData
321 QSslSocketGlobalData() : config(new QSslConfigurationPrivate) {}
324 QList<QSslCipher> supportedCiphers;
325 QExplicitlySharedDataPointer<QSslConfigurationPrivate> config;
327 Q_GLOBAL_STATIC(QSslSocketGlobalData, globalData)
330 Constructs a QSslSocket object. \a parent is passed to QObject's
331 constructor. The new socket's \l {QSslCipher} {cipher} suite is
332 set to the one returned by the static method defaultCiphers().
334 QSslSocket::QSslSocket(QObject *parent)
335 : QTcpSocket(*new QSslSocketBackendPrivate, parent)
338 #ifdef QSSLSOCKET_DEBUG
339 qDebug() << "QSslSocket::QSslSocket(" << parent << "), this =" << (void *)this;
346 Destroys the QSslSocket.
348 QSslSocket::~QSslSocket()
351 #ifdef QSSLSOCKET_DEBUG
352 qDebug() << "QSslSocket::~QSslSocket(), this =" << (void *)this;
354 delete d->plainSocket;
363 Continues data transfer on the socket after it has been paused. If
364 "setPauseMode(QAbstractSocket::PauseOnSslErrors);" has been called on
365 this socket and a sslErrors() signal is received, calling this method
366 is necessary for the socket to continue.
368 \sa QAbstractSocket::pauseMode(), QAbstractSocket::setPauseMode()
370 void QSslSocket::resume()
372 // continuing might emit signals, rather do this through the event loop
373 QMetaObject::invokeMethod(this, "_q_resumeImplementation", Qt::QueuedConnection);
377 Starts an encrypted connection to the device \a hostName on \a
378 port, using \a mode as the \l OpenMode. This is equivalent to
379 calling connectToHost() to establish the connection, followed by a
380 call to startClientEncryption(). The \a protocol parameter can be
381 used to specify which network protocol to use (eg. IPv4 or IPv6).
383 QSslSocket first enters the HostLookupState. Then, after entering
384 either the event loop or one of the waitFor...() functions, it
385 enters the ConnectingState, emits connected(), and then initiates
386 the SSL client handshake. At each state change, QSslSocket emits
387 signal stateChanged().
389 After initiating the SSL client handshake, if the identity of the
390 peer can't be established, signal sslErrors() is emitted. If you
391 want to ignore the errors and continue connecting, you must call
392 ignoreSslErrors(), either from inside a slot function connected to
393 the sslErrors() signal, or prior to entering encrypted mode. If
394 ignoreSslErrors() is not called, the connection is dropped, signal
395 disconnected() is emitted, and QSslSocket returns to the
398 If the SSL handshake is successful, QSslSocket emits encrypted().
400 \snippet code/src_network_ssl_qsslsocket.cpp 3
402 \b{Note:} The example above shows that text can be written to
403 the socket immediately after requesting the encrypted connection,
404 before the encrypted() signal has been emitted. In such cases, the
405 text is queued in the object and written to the socket \e after
406 the connection is established and the encrypted() signal has been
409 The default for \a mode is \l ReadWrite.
411 If you want to create a QSslSocket on the server side of a connection, you
412 should instead call startServerEncryption() upon receiving the incoming
413 connection through QTcpServer.
415 \sa connectToHost(), startClientEncryption(), waitForConnected(), waitForEncrypted()
417 void QSslSocket::connectToHostEncrypted(const QString &hostName, quint16 port, OpenMode mode, NetworkLayerProtocol protocol)
420 if (d->state == ConnectedState || d->state == ConnectingState) {
421 qWarning("QSslSocket::connectToHostEncrypted() called when already connecting/connected");
426 d->autoStartHandshake = true;
427 d->initialized = true;
429 // Note: When connecting to localhost, some platforms (e.g., HP-UX and some BSDs)
430 // establish the connection immediately (i.e., first attempt).
431 connectToHost(hostName, port, mode, protocol);
438 In addition to the original behaviour of connectToHostEncrypted,
439 this overloaded method enables the usage of a different hostname
440 (\a sslPeerName) for the certificate validation instead of
441 the one used for the TCP connection (\a hostName).
443 \sa connectToHostEncrypted()
445 void QSslSocket::connectToHostEncrypted(const QString &hostName, quint16 port,
446 const QString &sslPeerName, OpenMode mode,
447 NetworkLayerProtocol protocol)
450 if (d->state == ConnectedState || d->state == ConnectingState) {
451 qWarning("QSslSocket::connectToHostEncrypted() called when already connecting/connected");
456 d->autoStartHandshake = true;
457 d->initialized = true;
458 d->verificationPeerName = sslPeerName;
460 // Note: When connecting to localhost, some platforms (e.g., HP-UX and some BSDs)
461 // establish the connection immediately (i.e., first attempt).
462 connectToHost(hostName, port, mode, protocol);
466 Initializes QSslSocket with the native socket descriptor \a
467 socketDescriptor. Returns true if \a socketDescriptor is accepted
468 as a valid socket descriptor; otherwise returns false.
469 The socket is opened in the mode specified by \a openMode, and
470 enters the socket state specified by \a state.
472 \b{Note:} It is not possible to initialize two sockets with the same
473 native socket descriptor.
475 \sa socketDescriptor()
477 bool QSslSocket::setSocketDescriptor(qintptr socketDescriptor, SocketState state, OpenMode openMode)
480 #ifdef QSSLSOCKET_DEBUG
481 qDebug() << "QSslSocket::setSocketDescriptor(" << socketDescriptor << ','
482 << state << ',' << openMode << ')';
485 d->createPlainSocket(openMode);
486 bool retVal = d->plainSocket->setSocketDescriptor(socketDescriptor, state, openMode);
487 d->cachedSocketDescriptor = d->plainSocket->socketDescriptor();
488 setSocketError(d->plainSocket->error());
489 setSocketState(state);
490 setOpenMode(openMode);
491 setLocalPort(d->plainSocket->localPort());
492 setLocalAddress(d->plainSocket->localAddress());
493 setPeerPort(d->plainSocket->peerPort());
494 setPeerAddress(d->plainSocket->peerAddress());
495 setPeerName(d->plainSocket->peerName());
501 Sets the given \a option to the value described by \a value.
505 void QSslSocket::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
509 d->plainSocket->setSocketOption(option, value);
514 Returns the value of the \a option option.
516 \sa setSocketOption()
518 QVariant QSslSocket::socketOption(QAbstractSocket::SocketOption option)
522 return d->plainSocket->socketOption(option);
528 Returns the current mode for the socket; either UnencryptedMode, where
529 QSslSocket behaves identially to QTcpSocket, or one of SslClientMode or
530 SslServerMode, where the client is either negotiating or in encrypted
533 When the mode changes, QSslSocket emits modeChanged()
537 QSslSocket::SslMode QSslSocket::mode() const
539 Q_D(const QSslSocket);
544 Returns true if the socket is encrypted; otherwise, false is returned.
546 An encrypted socket encrypts all data that is written by calling write()
547 or putChar() before the data is written to the network, and decrypts all
548 incoming data as the data is received from the network, before you call
549 read(), readLine() or getChar().
551 QSslSocket emits encrypted() when it enters encrypted mode.
553 You can call sessionCipher() to find which cryptographic cipher is used to
554 encrypt and decrypt your data.
558 bool QSslSocket::isEncrypted() const
560 Q_D(const QSslSocket);
561 return d->connectionEncrypted;
565 Returns the socket's SSL protocol. By default, \l QSsl::SecureProtocols is used.
569 QSsl::SslProtocol QSslSocket::protocol() const
571 Q_D(const QSslSocket);
572 return d->configuration.protocol;
576 Sets the socket's SSL protocol to \a protocol. This will affect the next
577 initiated handshake; calling this function on an already-encrypted socket
578 will not affect the socket's protocol.
580 void QSslSocket::setProtocol(QSsl::SslProtocol protocol)
583 d->configuration.protocol = protocol;
589 Returns the socket's verify mode. This mode mode decides whether
590 QSslSocket should request a certificate from the peer (i.e., the client
591 requests a certificate from the server, or a server requesting a
592 certificate from the client), and whether it should require that this
593 certificate is valid.
595 The default mode is AutoVerifyPeer, which tells QSslSocket to use
596 VerifyPeer for clients and QueryPeer for servers.
598 \sa setPeerVerifyMode(), peerVerifyDepth(), mode()
600 QSslSocket::PeerVerifyMode QSslSocket::peerVerifyMode() const
602 Q_D(const QSslSocket);
603 return d->configuration.peerVerifyMode;
609 Sets the socket's verify mode to \a mode. This mode decides whether
610 QSslSocket should request a certificate from the peer (i.e., the client
611 requests a certificate from the server, or a server requesting a
612 certificate from the client), and whether it should require that this
613 certificate is valid.
615 The default mode is AutoVerifyPeer, which tells QSslSocket to use
616 VerifyPeer for clients and QueryPeer for servers.
618 Setting this mode after encryption has started has no effect on the
621 \sa peerVerifyMode(), setPeerVerifyDepth(), mode()
623 void QSslSocket::setPeerVerifyMode(QSslSocket::PeerVerifyMode mode)
626 d->configuration.peerVerifyMode = mode;
632 Returns the maximum number of certificates in the peer's certificate chain
633 to be checked during the SSL handshake phase, or 0 (the default) if no
634 maximum depth has been set, indicating that the whole certificate chain
637 The certificates are checked in issuing order, starting with the peer's
638 own certificate, then its issuer's certificate, and so on.
640 \sa setPeerVerifyDepth(), peerVerifyMode()
642 int QSslSocket::peerVerifyDepth() const
644 Q_D(const QSslSocket);
645 return d->configuration.peerVerifyDepth;
651 Sets the maximum number of certificates in the peer's certificate chain to
652 be checked during the SSL handshake phase, to \a depth. Setting a depth of
653 0 means that no maximum depth is set, indicating that the whole
654 certificate chain should be checked.
656 The certificates are checked in issuing order, starting with the peer's
657 own certificate, then its issuer's certificate, and so on.
659 \sa peerVerifyDepth(), setPeerVerifyMode()
661 void QSslSocket::setPeerVerifyDepth(int depth)
665 qWarning("QSslSocket::setPeerVerifyDepth: cannot set negative depth of %d", depth);
668 d->configuration.peerVerifyDepth = depth;
674 Returns the different hostname for the certificate validation, as set by
675 setPeerVerifyName or by connectToHostEncrypted.
677 \sa setPeerVerifyName(), connectToHostEncrypted()
679 QString QSslSocket::peerVerifyName() const
681 Q_D(const QSslSocket);
682 return d->verificationPeerName;
688 Sets a different host name, given by \a hostName, for the certificate
689 validation instead of the one used for the TCP connection.
691 \sa connectToHostEncrypted()
693 void QSslSocket::setPeerVerifyName(const QString &hostName)
696 d->verificationPeerName = hostName;
702 Returns the number of decrypted bytes that are immediately available for
705 qint64 QSslSocket::bytesAvailable() const
707 Q_D(const QSslSocket);
708 if (d->mode == UnencryptedMode)
709 return QIODevice::bytesAvailable() + (d->plainSocket ? d->plainSocket->bytesAvailable() : 0);
710 return QIODevice::bytesAvailable() + d->readBuffer.size();
716 Returns the number of unencrypted bytes that are waiting to be encrypted
717 and written to the network.
719 qint64 QSslSocket::bytesToWrite() const
721 Q_D(const QSslSocket);
722 if (d->mode == UnencryptedMode)
723 return d->plainSocket ? d->plainSocket->bytesToWrite() : 0;
724 return d->writeBuffer.size();
730 Returns the number of encrypted bytes that are awaiting decryption.
731 Normally, this function will return 0 because QSslSocket decrypts its
732 incoming data as soon as it can.
734 qint64 QSslSocket::encryptedBytesAvailable() const
736 Q_D(const QSslSocket);
737 if (d->mode == UnencryptedMode)
739 return d->plainSocket->bytesAvailable();
745 Returns the number of encrypted bytes that are waiting to be written to
748 qint64 QSslSocket::encryptedBytesToWrite() const
750 Q_D(const QSslSocket);
751 if (d->mode == UnencryptedMode)
753 return d->plainSocket->bytesToWrite();
759 Returns true if you can read one while line (terminated by a single ASCII
760 '\\n' character) of decrypted characters; otherwise, false is returned.
762 bool QSslSocket::canReadLine() const
764 Q_D(const QSslSocket);
765 if (d->mode == UnencryptedMode)
766 return QIODevice::canReadLine() || (d->plainSocket && d->plainSocket->canReadLine());
767 return QIODevice::canReadLine() || (!d->readBuffer.isEmpty() && d->readBuffer.canReadLine());
773 void QSslSocket::close()
775 #ifdef QSSLSOCKET_DEBUG
776 qDebug() << "QSslSocket::close()";
780 d->plainSocket->close();
783 // must be cleared, reading/writing not possible on closed socket:
784 d->readBuffer.clear();
785 d->writeBuffer.clear();
786 // for QTcpSocket this is already done because it uses the readBuffer/writeBuffer
787 // if the QIODevice it is based on
788 // ### FIXME QSslSocket should probably do similar instead of having
789 // its own readBuffer/writeBuffer
795 bool QSslSocket::atEnd() const
797 Q_D(const QSslSocket);
798 if (d->mode == UnencryptedMode)
799 return QIODevice::atEnd() && (!d->plainSocket || d->plainSocket->atEnd());
800 return QIODevice::atEnd() && d->readBuffer.isEmpty();
804 This function writes as much as possible from the internal write buffer to
805 the underlying network socket, without blocking. If any data was written,
806 this function returns true; otherwise false is returned.
808 Call this function if you need QSslSocket to start sending buffered data
809 immediately. The number of bytes successfully written depends on the
810 operating system. In most cases, you do not need to call this function,
811 because QAbstractSocket will start sending data automatically once control
812 goes back to the event loop. In the absence of an event loop, call
813 waitForBytesWritten() instead.
815 \sa write(), waitForBytesWritten()
817 // Note! docs copied from QAbstractSocket::flush()
818 bool QSslSocket::flush()
821 #ifdef QSSLSOCKET_DEBUG
822 qDebug() << "QSslSocket::flush()";
824 if (d->mode != UnencryptedMode)
825 // encrypt any unencrypted bytes in our buffer
828 return d->plainSocket ? d->plainSocket->flush() : false;
834 Sets the size of QSslSocket's internal read buffer to be \a size bytes.
836 void QSslSocket::setReadBufferSize(qint64 size)
839 d->readBufferMaxSize = size;
842 d->plainSocket->setReadBufferSize(size);
846 Aborts the current connection and resets the socket. Unlike
847 disconnectFromHost(), this function immediately closes the socket,
848 clearing any pending data in the write buffer.
850 \sa disconnectFromHost(), close()
852 void QSslSocket::abort()
855 #ifdef QSSLSOCKET_DEBUG
856 qDebug() << "QSslSocket::abort()";
859 d->plainSocket->abort();
866 Returns the socket's SSL configuration state. The default SSL
867 configuration of a socket is to use the default ciphers,
868 default CA certificates, no local private key or certificate.
870 The SSL configuration also contains fields that can change with
873 \sa localCertificate(), peerCertificate(), peerCertificateChain(),
874 sessionCipher(), privateKey(), ciphers(), caCertificates()
876 QSslConfiguration QSslSocket::sslConfiguration() const
878 Q_D(const QSslSocket);
880 // create a deep copy of our configuration
881 QSslConfigurationPrivate *copy = new QSslConfigurationPrivate(d->configuration);
882 copy->ref.store(0); // the QSslConfiguration constructor refs up
883 copy->sessionCipher = d->sessionCipher();
885 return QSslConfiguration(copy);
891 Sets the socket's SSL configuration to be the contents of \a configuration.
892 This function sets the local certificate, the ciphers, the private key and the CA
893 certificates to those stored in \a configuration.
895 It is not possible to set the SSL-state related fields.
897 \sa setLocalCertificate(), setPrivateKey(), setCaCertificates(), setCiphers()
899 void QSslSocket::setSslConfiguration(const QSslConfiguration &configuration)
902 d->configuration.localCertificate = configuration.localCertificate();
903 d->configuration.privateKey = configuration.privateKey();
904 d->configuration.ciphers = configuration.ciphers();
905 d->configuration.caCertificates = configuration.caCertificates();
906 d->configuration.peerVerifyDepth = configuration.peerVerifyDepth();
907 d->configuration.peerVerifyMode = configuration.peerVerifyMode();
908 d->configuration.protocol = configuration.protocol();
909 d->configuration.sslOptions = configuration.d->sslOptions;
910 d->allowRootCertOnDemandLoading = false;
914 Sets the socket's local certificate to \a certificate. The local
915 certificate is necessary if you need to confirm your identity to the
916 peer. It is used together with the private key; if you set the local
917 certificate, you must also set the private key.
919 The local certificate and private key are always necessary for server
920 sockets, but are also rarely used by client sockets if the server requires
921 the client to authenticate.
923 \sa localCertificate(), setPrivateKey()
925 void QSslSocket::setLocalCertificate(const QSslCertificate &certificate)
928 d->configuration.localCertificate = certificate;
934 Sets the socket's local \l {QSslCertificate} {certificate} to the
935 first one found in file \a path, which is parsed according to the
938 void QSslSocket::setLocalCertificate(const QString &path,
939 QSsl::EncodingFormat format)
943 if (file.open(QIODevice::ReadOnly | QIODevice::Text))
944 d->configuration.localCertificate = QSslCertificate(file.readAll(), format);
948 Returns the socket's local \l {QSslCertificate} {certificate}, or
949 an empty certificate if no local certificate has been assigned.
951 \sa setLocalCertificate(), privateKey()
953 QSslCertificate QSslSocket::localCertificate() const
955 Q_D(const QSslSocket);
956 return d->configuration.localCertificate;
960 Returns the peer's digital certificate (i.e., the immediate
961 certificate of the host you are connected to), or a null
962 certificate, if the peer has not assigned a certificate.
964 The peer certificate is checked automatically during the
965 handshake phase, so this function is normally used to fetch
966 the certificate for display or for connection diagnostic
967 purposes. It contains information about the peer, including
968 its host name, the certificate issuer, and the peer's public
971 Because the peer certificate is set during the handshake phase, it
972 is safe to access the peer certificate from a slot connected to
973 the sslErrors() signal or the encrypted() signal.
975 If a null certificate is returned, it can mean the SSL handshake
976 failed, or it can mean the host you are connected to doesn't have
977 a certificate, or it can mean there is no connection.
979 If you want to check the peer's complete chain of certificates,
980 use peerCertificateChain() to get them all at once.
982 \sa peerCertificateChain()
984 QSslCertificate QSslSocket::peerCertificate() const
986 Q_D(const QSslSocket);
987 return d->configuration.peerCertificate;
991 Returns the peer's chain of digital certificates, or an empty list
994 Peer certificates are checked automatically during the handshake
995 phase. This function is normally used to fetch certificates for
996 display, or for performing connection diagnostics. Certificates
997 contain information about the peer and the certificate issuers,
998 including host name, issuer names, and issuer public keys.
1000 The peer certificates are set in QSslSocket during the handshake
1001 phase, so it is safe to call this function from a slot connected
1002 to the sslErrors() signal or the encrypted() signal.
1004 If an empty list is returned, it can mean the SSL handshake
1005 failed, or it can mean the host you are connected to doesn't have
1006 a certificate, or it can mean there is no connection.
1008 If you want to get only the peer's immediate certificate, use
1011 \sa peerCertificate()
1013 QList<QSslCertificate> QSslSocket::peerCertificateChain() const
1015 Q_D(const QSslSocket);
1016 return d->configuration.peerCertificateChain;
1020 Returns the socket's cryptographic \l {QSslCipher} {cipher}, or a
1021 null cipher if the connection isn't encrypted. The socket's cipher
1022 for the session is set during the handshake phase. The cipher is
1023 used to encrypt and decrypt data transmitted through the socket.
1025 QSslSocket also provides functions for setting the ordered list of
1026 ciphers from which the handshake phase will eventually select the
1027 session cipher. This ordered list must be in place before the
1028 handshake phase begins.
1030 \sa ciphers(), setCiphers(), setDefaultCiphers(), defaultCiphers(),
1033 QSslCipher QSslSocket::sessionCipher() const
1035 Q_D(const QSslSocket);
1036 return d->sessionCipher();
1040 Sets the socket's private \l {QSslKey} {key} to \a key. The
1041 private key and the local \l {QSslCertificate} {certificate} are
1042 used by clients and servers that must prove their identity to
1045 Both the key and the local certificate are required if you are
1046 creating an SSL server socket. If you are creating an SSL client
1047 socket, the key and local certificate are required if your client
1048 must identify itself to an SSL server.
1050 \sa privateKey(), setLocalCertificate()
1052 void QSslSocket::setPrivateKey(const QSslKey &key)
1055 d->configuration.privateKey = key;
1061 Reads the string in file \a fileName and decodes it using
1062 a specified \a algorithm and encoding \a format to construct
1063 an \l {QSslKey} {SSL key}. If the encoded key is encrypted,
1064 \a passPhrase is used to decrypt it.
1066 The socket's private key is set to the constructed key. The
1067 private key and the local \l {QSslCertificate} {certificate} are
1068 used by clients and servers that must prove their identity to SSL
1071 Both the key and the local certificate are required if you are
1072 creating an SSL server socket. If you are creating an SSL client
1073 socket, the key and local certificate are required if your client
1074 must identify itself to an SSL server.
1076 \sa privateKey(), setLocalCertificate()
1078 void QSslSocket::setPrivateKey(const QString &fileName, QSsl::KeyAlgorithm algorithm,
1079 QSsl::EncodingFormat format, const QByteArray &passPhrase)
1082 QFile file(fileName);
1083 if (file.open(QIODevice::ReadOnly)) {
1084 d->configuration.privateKey = QSslKey(file.readAll(), algorithm,
1085 format, QSsl::PrivateKey, passPhrase);
1090 Returns this socket's private key.
1092 \sa setPrivateKey(), localCertificate()
1094 QSslKey QSslSocket::privateKey() const
1096 Q_D(const QSslSocket);
1097 return d->configuration.privateKey;
1101 Returns this socket's current cryptographic cipher suite. This
1102 list is used during the socket's handshake phase for choosing a
1103 session cipher. The returned list of ciphers is ordered by
1104 descending preference. (i.e., the first cipher in the list is the
1105 most preferred cipher). The session cipher will be the first one
1106 in the list that is also supported by the peer.
1108 By default, the handshake phase can choose any of the ciphers
1109 supported by this system's SSL libraries, which may vary from
1110 system to system. The list of ciphers supported by this system's
1111 SSL libraries is returned by supportedCiphers(). You can restrict
1112 the list of ciphers used for choosing the session cipher for this
1113 socket by calling setCiphers() with a subset of the supported
1114 ciphers. You can revert to using the entire set by calling
1115 setCiphers() with the list returned by supportedCiphers().
1117 You can restrict the list of ciphers used for choosing the session
1118 cipher for \e all sockets by calling setDefaultCiphers() with a
1119 subset of the supported ciphers. You can revert to using the
1120 entire set by calling setCiphers() with the list returned by
1123 \sa setCiphers(), defaultCiphers(), setDefaultCiphers(), supportedCiphers()
1125 QList<QSslCipher> QSslSocket::ciphers() const
1127 Q_D(const QSslSocket);
1128 return d->configuration.ciphers;
1132 Sets the cryptographic cipher suite for this socket to \a ciphers,
1133 which must contain a subset of the ciphers in the list returned by
1136 Restricting the cipher suite must be done before the handshake
1137 phase, where the session cipher is chosen.
1139 \sa ciphers(), setDefaultCiphers(), supportedCiphers()
1141 void QSslSocket::setCiphers(const QList<QSslCipher> &ciphers)
1144 d->configuration.ciphers = ciphers;
1148 Sets the cryptographic cipher suite for this socket to \a ciphers, which
1149 is a colon-separated list of cipher suite names. The ciphers are listed in
1150 order of preference, starting with the most preferred cipher. For example:
1152 \snippet code/src_network_ssl_qsslsocket.cpp 4
1154 Each cipher name in \a ciphers must be the name of a cipher in the
1155 list returned by supportedCiphers(). Restricting the cipher suite
1156 must be done before the handshake phase, where the session cipher
1159 \sa ciphers(), setDefaultCiphers(), supportedCiphers()
1161 void QSslSocket::setCiphers(const QString &ciphers)
1164 d->configuration.ciphers.clear();
1165 foreach (const QString &cipherName, ciphers.split(QLatin1String(":"),QString::SkipEmptyParts)) {
1166 for (int i = 0; i < 3; ++i) {
1168 QSslCipher cipher(cipherName, QSsl::SslProtocol(i));
1169 if (!cipher.isNull())
1170 d->configuration.ciphers << cipher;
1176 Sets the default cryptographic cipher suite for all sockets in
1177 this application to \a ciphers, which must contain a subset of the
1178 ciphers in the list returned by supportedCiphers().
1180 Restricting the default cipher suite only affects SSL sockets
1181 that perform their handshake phase after the default cipher
1182 suite has been changed.
1184 \sa setCiphers(), defaultCiphers(), supportedCiphers()
1186 void QSslSocket::setDefaultCiphers(const QList<QSslCipher> &ciphers)
1188 QSslSocketPrivate::setDefaultCiphers(ciphers);
1192 Returns the default cryptographic cipher suite for all sockets in
1193 this application. This list is used during the socket's handshake
1194 phase when negotiating with the peer to choose a session cipher.
1195 The list is ordered by preference (i.e., the first cipher in the
1196 list is the most preferred cipher).
1198 By default, the handshake phase can choose any of the ciphers
1199 supported by this system's SSL libraries, which may vary from
1200 system to system. The list of ciphers supported by this system's
1201 SSL libraries is returned by supportedCiphers().
1203 \sa supportedCiphers()
1205 QList<QSslCipher> QSslSocket::defaultCiphers()
1207 return QSslSocketPrivate::defaultCiphers();
1211 Returns the list of cryptographic ciphers supported by this
1212 system. This list is set by the system's SSL libraries and may
1213 vary from system to system.
1215 \sa defaultCiphers(), ciphers(), setCiphers()
1217 QList<QSslCipher> QSslSocket::supportedCiphers()
1219 return QSslSocketPrivate::supportedCiphers();
1223 Searches all files in the \a path for certificates encoded in the
1224 specified \a format and adds them to this socket's CA certificate
1225 database. \a path can be explicit, or it can contain wildcards in
1226 the format specified by \a syntax. Returns true if one or more
1227 certificates are added to the socket's CA certificate database;
1228 otherwise returns false.
1230 The CA certificate database is used by the socket during the
1231 handshake phase to validate the peer's certificate.
1233 For more precise control, use addCaCertificate().
1235 \sa addCaCertificate(), QSslCertificate::fromPath()
1237 bool QSslSocket::addCaCertificates(const QString &path, QSsl::EncodingFormat format,
1238 QRegExp::PatternSyntax syntax)
1241 QList<QSslCertificate> certs = QSslCertificate::fromPath(path, format, syntax);
1242 if (certs.isEmpty())
1245 d->configuration.caCertificates += certs;
1250 Adds the \a certificate to this socket's CA certificate database.
1251 The CA certificate database is used by the socket during the
1252 handshake phase to validate the peer's certificate.
1254 To add multiple certificates, use addCaCertificates().
1256 \sa caCertificates(), setCaCertificates()
1258 void QSslSocket::addCaCertificate(const QSslCertificate &certificate)
1261 d->configuration.caCertificates += certificate;
1265 Adds the \a certificates to this socket's CA certificate database.
1266 The CA certificate database is used by the socket during the
1267 handshake phase to validate the peer's certificate.
1269 For more precise control, use addCaCertificate().
1271 \sa caCertificates(), addDefaultCaCertificate()
1273 void QSslSocket::addCaCertificates(const QList<QSslCertificate> &certificates)
1276 d->configuration.caCertificates += certificates;
1280 Sets this socket's CA certificate database to be \a certificates.
1281 The certificate database must be set prior to the SSL handshake.
1282 The CA certificate database is used by the socket during the
1283 handshake phase to validate the peer's certificate.
1285 The CA certificate database can be reset to the current default CA
1286 certificate database by calling this function with the list of CA
1287 certificates returned by defaultCaCertificates().
1289 \sa defaultCaCertificates()
1291 void QSslSocket::setCaCertificates(const QList<QSslCertificate> &certificates)
1294 d->configuration.caCertificates = certificates;
1295 d->allowRootCertOnDemandLoading = false;
1299 Returns this socket's CA certificate database. The CA certificate
1300 database is used by the socket during the handshake phase to
1301 validate the peer's certificate. It can be moodified prior to the
1302 handshake with addCaCertificate(), addCaCertificates(), and
1303 setCaCertificates().
1305 \note On Unix, this method may return an empty list if the root
1306 certificates are loaded on demand.
1308 \sa addCaCertificate(), addCaCertificates(), setCaCertificates()
1310 QList<QSslCertificate> QSslSocket::caCertificates() const
1312 Q_D(const QSslSocket);
1313 return d->configuration.caCertificates;
1317 Searches all files in the \a path for certificates with the
1318 specified \a encoding and adds them to the default CA certificate
1319 database. \a path can be an explicit file, or it can contain
1320 wildcards in the format specified by \a syntax. Returns true if
1321 any CA certificates are added to the default database.
1323 Each SSL socket's CA certificate database is initialized to the
1324 default CA certificate database.
1326 \sa defaultCaCertificates(), addCaCertificates(), addDefaultCaCertificate()
1328 bool QSslSocket::addDefaultCaCertificates(const QString &path, QSsl::EncodingFormat encoding,
1329 QRegExp::PatternSyntax syntax)
1331 return QSslSocketPrivate::addDefaultCaCertificates(path, encoding, syntax);
1335 Adds \a certificate to the default CA certificate database. Each
1336 SSL socket's CA certificate database is initialized to the default
1337 CA certificate database.
1339 \sa defaultCaCertificates(), addCaCertificates()
1341 void QSslSocket::addDefaultCaCertificate(const QSslCertificate &certificate)
1343 QSslSocketPrivate::addDefaultCaCertificate(certificate);
1347 Adds \a certificates to the default CA certificate database. Each
1348 SSL socket's CA certificate database is initialized to the default
1349 CA certificate database.
1351 \sa defaultCaCertificates(), addCaCertificates()
1353 void QSslSocket::addDefaultCaCertificates(const QList<QSslCertificate> &certificates)
1355 QSslSocketPrivate::addDefaultCaCertificates(certificates);
1359 Sets the default CA certificate database to \a certificates. The
1360 default CA certificate database is originally set to your system's
1361 default CA certificate database. You can override the default CA
1362 certificate database with your own CA certificate database using
1365 Each SSL socket's CA certificate database is initialized to the
1366 default CA certificate database.
1368 \sa addDefaultCaCertificate()
1370 void QSslSocket::setDefaultCaCertificates(const QList<QSslCertificate> &certificates)
1372 QSslSocketPrivate::setDefaultCaCertificates(certificates);
1376 Returns the current default CA certificate database. This database
1377 is originally set to your system's default CA certificate database.
1378 If no system default database is found, an empty database will be
1379 returned. You can override the default CA certificate database
1380 with your own CA certificate database using setDefaultCaCertificates().
1382 Each SSL socket's CA certificate database is initialized to the
1383 default CA certificate database.
1385 \note On Unix, this method may return an empty list if the root
1386 certificates are loaded on demand.
1388 \sa caCertificates()
1390 QList<QSslCertificate> QSslSocket::defaultCaCertificates()
1392 return QSslSocketPrivate::defaultCaCertificates();
1396 This function provides the CA certificate database
1397 provided by the operating system. The CA certificate database
1398 returned by this function is used to initialize the database
1399 returned by defaultCaCertificates(). You can replace that database
1400 with your own with setDefaultCaCertificates().
1402 \sa caCertificates(), defaultCaCertificates(), setDefaultCaCertificates()
1404 QList<QSslCertificate> QSslSocket::systemCaCertificates()
1406 // we are calling ensureInitialized() in the method below
1407 return QSslSocketPrivate::systemCaCertificates();
1411 Waits until the socket is connected, or \a msecs milliseconds,
1412 whichever happens first. If the connection has been established,
1413 this function returns true; otherwise it returns false.
1415 \sa QAbstractSocket::waitForConnected()
1417 bool QSslSocket::waitForConnected(int msecs)
1420 if (!d->plainSocket)
1422 bool retVal = d->plainSocket->waitForConnected(msecs);
1424 setSocketState(d->plainSocket->state());
1425 setSocketError(d->plainSocket->error());
1426 setErrorString(d->plainSocket->errorString());
1432 Waits until the socket has completed the SSL handshake and has
1433 emitted encrypted(), or \a msecs milliseconds, whichever comes
1434 first. If encrypted() has been emitted, this function returns
1435 true; otherwise (e.g., the socket is disconnected, or the SSL
1436 handshake fails), false is returned.
1438 The following example waits up to one second for the socket to be
1441 \snippet code/src_network_ssl_qsslsocket.cpp 5
1443 If msecs is -1, this function will not time out.
1445 \sa startClientEncryption(), startServerEncryption(), encrypted(), isEncrypted()
1447 bool QSslSocket::waitForEncrypted(int msecs)
1450 if (!d->plainSocket || d->connectionEncrypted)
1452 if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1455 QElapsedTimer stopWatch;
1458 if (d->plainSocket->state() != QAbstractSocket::ConnectedState) {
1459 // Wait until we've entered connected state.
1460 if (!d->plainSocket->waitForConnected(msecs))
1464 while (!d->connectionEncrypted) {
1465 // Start the handshake, if this hasn't been started yet.
1466 if (d->mode == UnencryptedMode)
1467 startClientEncryption();
1468 // Loop, waiting until the connection has been encrypted or an error
1470 if (!d->plainSocket->waitForReadyRead(qt_timeout_value(msecs, stopWatch.elapsed())))
1473 return d->connectionEncrypted;
1479 bool QSslSocket::waitForReadyRead(int msecs)
1482 if (!d->plainSocket)
1484 if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1485 return d->plainSocket->waitForReadyRead(msecs);
1487 // This function must return true if and only if readyRead() *was* emitted.
1488 // So we initialize "readyReadEmitted" to false and check if it was set to true.
1489 // waitForReadyRead() could be called recursively, so we can't use the same variable
1490 // (the inner waitForReadyRead() may fail, but the outer one still succeeded)
1491 bool readyReadEmitted = false;
1492 bool *previousReadyReadEmittedPointer = d->readyReadEmittedPointer;
1493 d->readyReadEmittedPointer = &readyReadEmitted;
1495 QElapsedTimer stopWatch;
1498 if (!d->connectionEncrypted) {
1499 // Wait until we've entered encrypted mode, or until a failure occurs.
1500 if (!waitForEncrypted(msecs)) {
1501 d->readyReadEmittedPointer = previousReadyReadEmittedPointer;
1506 if (!d->writeBuffer.isEmpty()) {
1507 // empty our cleartext write buffer first
1511 // test readyReadEmitted first because either operation above
1512 // (waitForEncrypted or transmit) may have set it
1513 while (!readyReadEmitted &&
1514 d->plainSocket->waitForReadyRead(qt_timeout_value(msecs, stopWatch.elapsed()))) {
1517 d->readyReadEmittedPointer = previousReadyReadEmittedPointer;
1518 return readyReadEmitted;
1524 bool QSslSocket::waitForBytesWritten(int msecs)
1527 if (!d->plainSocket)
1529 if (d->mode == UnencryptedMode)
1530 return d->plainSocket->waitForBytesWritten(msecs);
1532 QElapsedTimer stopWatch;
1535 if (!d->connectionEncrypted) {
1536 // Wait until we've entered encrypted mode, or until a failure occurs.
1537 if (!waitForEncrypted(msecs))
1540 if (!d->writeBuffer.isEmpty()) {
1541 // empty our cleartext write buffer first
1545 return d->plainSocket->waitForBytesWritten(qt_timeout_value(msecs, stopWatch.elapsed()));
1549 Waits until the socket has disconnected or \a msecs milliseconds,
1550 whichever comes first. If the connection has been disconnected,
1551 this function returns true; otherwise it returns false.
1553 \sa QAbstractSocket::waitForDisconnected()
1555 bool QSslSocket::waitForDisconnected(int msecs)
1559 // require calling connectToHost() before waitForDisconnected()
1560 if (state() == UnconnectedState) {
1561 qWarning("QSslSocket::waitForDisconnected() is not allowed in UnconnectedState");
1565 if (!d->plainSocket)
1567 if (d->mode == UnencryptedMode)
1568 return d->plainSocket->waitForDisconnected(msecs);
1570 QElapsedTimer stopWatch;
1573 if (!d->connectionEncrypted) {
1574 // Wait until we've entered encrypted mode, or until a failure occurs.
1575 if (!waitForEncrypted(msecs))
1578 bool retVal = d->plainSocket->waitForDisconnected(qt_timeout_value(msecs, stopWatch.elapsed()));
1580 setSocketState(d->plainSocket->state());
1581 setSocketError(d->plainSocket->error());
1582 setErrorString(d->plainSocket->errorString());
1588 Returns a list of the last SSL errors that occurred. This is the
1589 same list as QSslSocket passes via the sslErrors() signal. If the
1590 connection has been encrypted with no errors, this function will
1591 return an empty list.
1593 \sa connectToHostEncrypted()
1595 QList<QSslError> QSslSocket::sslErrors() const
1597 Q_D(const QSslSocket);
1598 return d->sslErrors;
1602 Returns true if this platform supports SSL; otherwise, returns
1603 false. If the platform doesn't support SSL, the socket will fail
1604 in the connection phase.
1606 bool QSslSocket::supportsSsl()
1608 return QSslSocketPrivate::supportsSsl();
1613 Returns the version number of the SSL library in use. Note that
1614 this is the version of the library in use at run-time not compile
1615 time. If no SSL support is available then this will return an
1618 long QSslSocket::sslLibraryVersionNumber()
1620 return QSslSocketPrivate::sslLibraryVersionNumber();
1625 Returns the version string of the SSL library in use. Note that
1626 this is the version of the library in use at run-time not compile
1627 time. If no SSL support is available then this will return an empty value.
1629 QString QSslSocket::sslLibraryVersionString()
1631 return QSslSocketPrivate::sslLibraryVersionString();
1635 Starts a delayed SSL handshake for a client connection. This
1636 function can be called when the socket is in the \l ConnectedState
1637 but still in the \l UnencryptedMode. If it is not yet connected,
1638 or if it is already encrypted, this function has no effect.
1640 Clients that implement STARTTLS functionality often make use of
1641 delayed SSL handshakes. Most other clients can avoid calling this
1642 function directly by using connectToHostEncrypted() instead, which
1643 automatically performs the handshake.
1645 \sa connectToHostEncrypted(), startServerEncryption()
1647 void QSslSocket::startClientEncryption()
1650 if (d->mode != UnencryptedMode) {
1651 qWarning("QSslSocket::startClientEncryption: cannot start handshake on non-plain connection");
1654 if (state() != ConnectedState) {
1655 qWarning("QSslSocket::startClientEncryption: cannot start handshake when not connected");
1658 #ifdef QSSLSOCKET_DEBUG
1659 qDebug() << "QSslSocket::startClientEncryption()";
1661 d->mode = SslClientMode;
1662 emit modeChanged(d->mode);
1663 d->startClientEncryption();
1667 Starts a delayed SSL handshake for a server connection. This
1668 function can be called when the socket is in the \l ConnectedState
1669 but still in \l UnencryptedMode. If it is not connected or it is
1670 already encrypted, the function has no effect.
1672 For server sockets, calling this function is the only way to
1673 initiate the SSL handshake. Most servers will call this function
1674 immediately upon receiving a connection, or as a result of having
1675 received a protocol-specific command to enter SSL mode (e.g, the
1676 server may respond to receiving the string "STARTTLS\\r\\n" by
1677 calling this function).
1679 The most common way to implement an SSL server is to create a
1680 subclass of QTcpServer and reimplement
1681 QTcpServer::incomingConnection(). The returned socket descriptor
1682 is then passed to QSslSocket::setSocketDescriptor().
1684 \sa connectToHostEncrypted(), startClientEncryption()
1686 void QSslSocket::startServerEncryption()
1689 if (d->mode != UnencryptedMode) {
1690 qWarning("QSslSocket::startServerEncryption: cannot start handshake on non-plain connection");
1693 #ifdef QSSLSOCKET_DEBUG
1694 qDebug() << "QSslSocket::startServerEncryption()";
1696 d->mode = SslServerMode;
1697 emit modeChanged(d->mode);
1698 d->startServerEncryption();
1702 This slot tells QSslSocket to ignore errors during QSslSocket's
1703 handshake phase and continue connecting. If you want to continue
1704 with the connection even if errors occur during the handshake
1705 phase, then you must call this slot, either from a slot connected
1706 to sslErrors(), or before the handshake phase. If you don't call
1707 this slot, either in response to errors or before the handshake,
1708 the connection will be dropped after the sslErrors() signal has
1711 If there are no errors during the SSL handshake phase (i.e., the
1712 identity of the peer is established with no problems), QSslSocket
1713 will not emit the sslErrors() signal, and it is unnecessary to
1716 Ignoring errors that occur during an SSL handshake should be done
1717 with caution. A fundamental characteristic of secure connections
1718 is that they should be established with an error free handshake.
1722 void QSslSocket::ignoreSslErrors()
1725 d->ignoreAllSslErrors = true;
1732 This method tells QSslSocket to ignore only the errors given in \a
1735 Note that you can set the expected certificate in the SSL error:
1736 If, for instance, you want to connect to a server that uses
1737 a self-signed certificate, consider the following snippet:
1739 \snippet code/src_network_ssl_qsslsocket.cpp 6
1741 Multiple calls to this function will replace the list of errors that
1742 were passed in previous calls.
1743 You can clear the list of errors you want to ignore by calling this
1744 function with an empty list.
1748 void QSslSocket::ignoreSslErrors(const QList<QSslError> &errors)
1751 d->ignoreErrorsList = errors;
1757 void QSslSocket::connectToHost(const QString &hostName, quint16 port, OpenMode openMode, NetworkLayerProtocol protocol)
1760 d->preferredNetworkLayerProtocol = protocol;
1761 if (!d->initialized)
1763 d->initialized = false;
1765 #ifdef QSSLSOCKET_DEBUG
1766 qDebug() << "QSslSocket::connectToHost("
1767 << hostName << ',' << port << ',' << openMode << ')';
1769 if (!d->plainSocket) {
1770 #ifdef QSSLSOCKET_DEBUG
1771 qDebug() << "\tcreating internal plain socket";
1773 d->createPlainSocket(openMode);
1775 #ifndef QT_NO_NETWORKPROXY
1776 d->plainSocket->setProxy(proxy());
1778 QIODevice::open(openMode);
1779 d->plainSocket->connectToHost(hostName, port, openMode, d->preferredNetworkLayerProtocol);
1780 d->cachedSocketDescriptor = d->plainSocket->socketDescriptor();
1786 void QSslSocket::disconnectFromHost()
1789 #ifdef QSSLSOCKET_DEBUG
1790 qDebug() << "QSslSocket::disconnectFromHost()";
1792 if (!d->plainSocket)
1794 if (d->state == UnconnectedState)
1796 if (d->mode == UnencryptedMode && !d->autoStartHandshake) {
1797 d->plainSocket->disconnectFromHost();
1800 if (d->state <= ConnectingState) {
1801 d->pendingClose = true;
1805 // Perhaps emit closing()
1806 if (d->state != ClosingState) {
1807 d->state = ClosingState;
1808 emit stateChanged(d->state);
1811 if (!d->writeBuffer.isEmpty())
1814 if (d->mode == UnencryptedMode) {
1815 d->plainSocket->disconnectFromHost();
1817 d->disconnectFromHost();
1824 qint64 QSslSocket::readData(char *data, qint64 maxlen)
1827 qint64 readBytes = 0;
1829 if (d->mode == UnencryptedMode && !d->autoStartHandshake) {
1830 readBytes = d->plainSocket->read(data, maxlen);
1833 const char *readPtr = d->readBuffer.readPointer();
1834 int bytesToRead = qMin<int>(maxlen - readBytes, d->readBuffer.nextDataBlockSize());
1835 ::memcpy(data + readBytes, readPtr, bytesToRead);
1836 readBytes += bytesToRead;
1837 d->readBuffer.free(bytesToRead);
1838 } while (!d->readBuffer.isEmpty() && readBytes < maxlen);
1840 #ifdef QSSLSOCKET_DEBUG
1841 qDebug() << "QSslSocket::readData(" << (void *)data << ',' << maxlen << ") ==" << readBytes;
1844 // possibly trigger another transmit() to decrypt more data from the socket
1845 if (d->readBuffer.isEmpty() && d->plainSocket->bytesAvailable())
1846 QMetaObject::invokeMethod(this, "_q_flushReadBuffer", Qt::QueuedConnection);
1854 qint64 QSslSocket::writeData(const char *data, qint64 len)
1857 #ifdef QSSLSOCKET_DEBUG
1858 qDebug() << "QSslSocket::writeData(" << (void *)data << ',' << len << ')';
1860 if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1861 return d->plainSocket->write(data, len);
1863 char *writePtr = d->writeBuffer.reserve(len);
1864 ::memcpy(writePtr, data, len);
1866 // make sure we flush to the plain socket's buffer
1867 QMetaObject::invokeMethod(this, "_q_flushWriteBuffer", Qt::QueuedConnection);
1875 QSslSocketPrivate::QSslSocketPrivate()
1876 : initialized(false)
1877 , mode(QSslSocket::UnencryptedMode)
1878 , autoStartHandshake(false)
1879 , connectionEncrypted(false)
1880 , ignoreAllSslErrors(false)
1881 , readyReadEmittedPointer(0)
1882 , allowRootCertOnDemandLoading(true)
1886 QSslConfigurationPrivate::deepCopyDefaultConfiguration(&configuration);
1892 QSslSocketPrivate::~QSslSocketPrivate()
1899 void QSslSocketPrivate::init()
1901 mode = QSslSocket::UnencryptedMode;
1902 autoStartHandshake = false;
1903 connectionEncrypted = false;
1904 ignoreAllSslErrors = false;
1906 // we don't want to clear the ignoreErrorsList, so
1907 // that it is possible setting it before connecting
1908 // ignoreErrorsList.clear();
1911 writeBuffer.clear();
1912 configuration.peerCertificate.clear();
1913 configuration.peerCertificateChain.clear();
1919 QList<QSslCipher> QSslSocketPrivate::defaultCiphers()
1921 QMutexLocker locker(&globalData()->mutex);
1922 return globalData()->config->ciphers;
1928 QList<QSslCipher> QSslSocketPrivate::supportedCiphers()
1930 QSslSocketPrivate::ensureInitialized();
1931 QMutexLocker locker(&globalData()->mutex);
1932 return globalData()->supportedCiphers;
1938 void QSslSocketPrivate::setDefaultCiphers(const QList<QSslCipher> &ciphers)
1940 QMutexLocker locker(&globalData()->mutex);
1941 globalData()->config.detach();
1942 globalData()->config->ciphers = ciphers;
1948 void QSslSocketPrivate::setDefaultSupportedCiphers(const QList<QSslCipher> &ciphers)
1950 QMutexLocker locker(&globalData()->mutex);
1951 globalData()->config.detach();
1952 globalData()->supportedCiphers = ciphers;
1958 QList<QSslCertificate> QSslSocketPrivate::defaultCaCertificates()
1960 QSslSocketPrivate::ensureInitialized();
1961 QMutexLocker locker(&globalData()->mutex);
1962 return globalData()->config->caCertificates;
1968 void QSslSocketPrivate::setDefaultCaCertificates(const QList<QSslCertificate> &certs)
1970 QSslSocketPrivate::ensureInitialized();
1971 QMutexLocker locker(&globalData()->mutex);
1972 globalData()->config.detach();
1973 globalData()->config->caCertificates = certs;
1974 // when the certificates are set explicitly, we do not want to
1975 // load the system certificates on demand
1976 s_loadRootCertsOnDemand = false;
1982 bool QSslSocketPrivate::addDefaultCaCertificates(const QString &path, QSsl::EncodingFormat format,
1983 QRegExp::PatternSyntax syntax)
1985 QSslSocketPrivate::ensureInitialized();
1986 QList<QSslCertificate> certs = QSslCertificate::fromPath(path, format, syntax);
1987 if (certs.isEmpty())
1990 QMutexLocker locker(&globalData()->mutex);
1991 globalData()->config.detach();
1992 globalData()->config->caCertificates += certs;
1999 void QSslSocketPrivate::addDefaultCaCertificate(const QSslCertificate &cert)
2001 QSslSocketPrivate::ensureInitialized();
2002 QMutexLocker locker(&globalData()->mutex);
2003 globalData()->config.detach();
2004 globalData()->config->caCertificates += cert;
2010 void QSslSocketPrivate::addDefaultCaCertificates(const QList<QSslCertificate> &certs)
2012 QSslSocketPrivate::ensureInitialized();
2013 QMutexLocker locker(&globalData()->mutex);
2014 globalData()->config.detach();
2015 globalData()->config->caCertificates += certs;
2021 QSslConfiguration QSslConfigurationPrivate::defaultConfiguration()
2023 QSslSocketPrivate::ensureInitialized();
2024 QMutexLocker locker(&globalData()->mutex);
2025 return QSslConfiguration(globalData()->config.data());
2031 void QSslConfigurationPrivate::setDefaultConfiguration(const QSslConfiguration &configuration)
2033 QSslSocketPrivate::ensureInitialized();
2034 QMutexLocker locker(&globalData()->mutex);
2035 if (globalData()->config == configuration.d)
2036 return; // nothing to do
2038 globalData()->config = const_cast<QSslConfigurationPrivate*>(configuration.d.constData());
2044 void QSslConfigurationPrivate::deepCopyDefaultConfiguration(QSslConfigurationPrivate *ptr)
2046 QSslSocketPrivate::ensureInitialized();
2047 QMutexLocker locker(&globalData()->mutex);
2048 const QSslConfigurationPrivate *global = globalData()->config.constData();
2056 ptr->peerCertificate = global->peerCertificate;
2057 ptr->peerCertificateChain = global->peerCertificateChain;
2058 ptr->localCertificate = global->localCertificate;
2059 ptr->privateKey = global->privateKey;
2060 ptr->sessionCipher = global->sessionCipher;
2061 ptr->ciphers = global->ciphers;
2062 ptr->caCertificates = global->caCertificates;
2063 ptr->protocol = global->protocol;
2064 ptr->peerVerifyMode = global->peerVerifyMode;
2065 ptr->peerVerifyDepth = global->peerVerifyDepth;
2066 ptr->sslOptions = global->sslOptions;
2072 void QSslSocketPrivate::createPlainSocket(QIODevice::OpenMode openMode)
2075 q->setOpenMode(openMode); // <- from QIODevice
2076 q->setSocketState(QAbstractSocket::UnconnectedState);
2077 q->setSocketError(QAbstractSocket::UnknownSocketError);
2079 q->setLocalAddress(QHostAddress());
2081 q->setPeerAddress(QHostAddress());
2082 q->setPeerName(QString());
2084 plainSocket = new QTcpSocket(q);
2085 #ifndef QT_NO_BEARERMANAGEMENT
2086 //copy network session down to the plain socket (if it has been set)
2087 plainSocket->setProperty("_q_networksession", q->property("_q_networksession"));
2089 q->connect(plainSocket, SIGNAL(connected()),
2090 q, SLOT(_q_connectedSlot()),
2091 Qt::DirectConnection);
2092 q->connect(plainSocket, SIGNAL(hostFound()),
2093 q, SLOT(_q_hostFoundSlot()),
2094 Qt::DirectConnection);
2095 q->connect(plainSocket, SIGNAL(disconnected()),
2096 q, SLOT(_q_disconnectedSlot()),
2097 Qt::DirectConnection);
2098 q->connect(plainSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
2099 q, SLOT(_q_stateChangedSlot(QAbstractSocket::SocketState)),
2100 Qt::DirectConnection);
2101 q->connect(plainSocket, SIGNAL(error(QAbstractSocket::SocketError)),
2102 q, SLOT(_q_errorSlot(QAbstractSocket::SocketError)),
2103 Qt::DirectConnection);
2104 q->connect(plainSocket, SIGNAL(readyRead()),
2105 q, SLOT(_q_readyReadSlot()),
2106 Qt::DirectConnection);
2107 q->connect(plainSocket, SIGNAL(bytesWritten(qint64)),
2108 q, SLOT(_q_bytesWrittenSlot(qint64)),
2109 Qt::DirectConnection);
2110 #ifndef QT_NO_NETWORKPROXY
2111 q->connect(plainSocket, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
2112 q, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
2116 writeBuffer.clear();
2117 connectionEncrypted = false;
2118 configuration.peerCertificate.clear();
2119 configuration.peerCertificateChain.clear();
2120 mode = QSslSocket::UnencryptedMode;
2121 q->setReadBufferSize(readBufferMaxSize);
2124 void QSslSocketPrivate::pauseSocketNotifiers(QSslSocket *socket)
2126 if (!socket->d_func()->plainSocket)
2128 QAbstractSocketPrivate::pauseSocketNotifiers(socket->d_func()->plainSocket);
2131 void QSslSocketPrivate::resumeSocketNotifiers(QSslSocket *socket)
2133 if (!socket->d_func()->plainSocket)
2135 QAbstractSocketPrivate::resumeSocketNotifiers(socket->d_func()->plainSocket);
2138 bool QSslSocketPrivate::isPaused() const
2146 void QSslSocketPrivate::_q_connectedSlot()
2149 q->setLocalPort(plainSocket->localPort());
2150 q->setLocalAddress(plainSocket->localAddress());
2151 q->setPeerPort(plainSocket->peerPort());
2152 q->setPeerAddress(plainSocket->peerAddress());
2153 q->setPeerName(plainSocket->peerName());
2154 cachedSocketDescriptor = plainSocket->socketDescriptor();
2156 #ifdef QSSLSOCKET_DEBUG
2157 qDebug() << "QSslSocket::_q_connectedSlot()";
2158 qDebug() << "\tstate =" << q->state();
2159 qDebug() << "\tpeer =" << q->peerName() << q->peerAddress() << q->peerPort();
2160 qDebug() << "\tlocal =" << QHostInfo::fromName(q->localAddress().toString()).hostName()
2161 << q->localAddress() << q->localPort();
2163 emit q->connected();
2165 if (autoStartHandshake) {
2166 q->startClientEncryption();
2167 } else if (pendingClose) {
2168 pendingClose = false;
2169 q->disconnectFromHost();
2176 void QSslSocketPrivate::_q_hostFoundSlot()
2179 #ifdef QSSLSOCKET_DEBUG
2180 qDebug() << "QSslSocket::_q_hostFoundSlot()";
2181 qDebug() << "\tstate =" << q->state();
2183 emit q->hostFound();
2189 void QSslSocketPrivate::_q_disconnectedSlot()
2192 #ifdef QSSLSOCKET_DEBUG
2193 qDebug() << "QSslSocket::_q_disconnectedSlot()";
2194 qDebug() << "\tstate =" << q->state();
2197 emit q->disconnected();
2203 void QSslSocketPrivate::_q_stateChangedSlot(QAbstractSocket::SocketState state)
2206 #ifdef QSSLSOCKET_DEBUG
2207 qDebug() << "QSslSocket::_q_stateChangedSlot(" << state << ')';
2209 q->setSocketState(state);
2210 emit q->stateChanged(state);
2216 void QSslSocketPrivate::_q_errorSlot(QAbstractSocket::SocketError error)
2219 #ifdef QSSLSOCKET_DEBUG
2220 qDebug() << "QSslSocket::_q_errorSlot(" << error << ')';
2221 qDebug() << "\tstate =" << q->state();
2222 qDebug() << "\terrorString =" << q->errorString();
2224 q->setSocketError(plainSocket->error());
2225 q->setErrorString(plainSocket->errorString());
2226 emit q->error(error);
2232 void QSslSocketPrivate::_q_readyReadSlot()
2235 #ifdef QSSLSOCKET_DEBUG
2236 qDebug() << "QSslSocket::_q_readyReadSlot() -" << plainSocket->bytesAvailable() << "bytes available";
2238 if (mode == QSslSocket::UnencryptedMode) {
2239 if (readyReadEmittedPointer)
2240 *readyReadEmittedPointer = true;
2241 emit q->readyRead();
2251 void QSslSocketPrivate::_q_bytesWrittenSlot(qint64 written)
2254 #ifdef QSSLSOCKET_DEBUG
2255 qDebug() << "QSslSocket::_q_bytesWrittenSlot(" << written << ')';
2258 if (mode == QSslSocket::UnencryptedMode)
2259 emit q->bytesWritten(written);
2261 emit q->encryptedBytesWritten(written);
2262 if (state == QAbstractSocket::ClosingState && writeBuffer.isEmpty())
2263 q->disconnectFromHost();
2269 void QSslSocketPrivate::_q_flushWriteBuffer()
2272 if (!writeBuffer.isEmpty())
2279 void QSslSocketPrivate::_q_flushReadBuffer()
2281 // trigger a read from the plainSocket into SSL
2282 if (mode != QSslSocket::UnencryptedMode)
2289 void QSslSocketPrivate::_q_resumeImplementation()
2293 plainSocket->resume();
2295 if (!connectionEncrypted) {
2296 if (verifyErrorsHaveBeenIgnored()) {
2297 continueHandshake();
2299 q->setErrorString(sslErrors.first().errorString());
2300 q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
2301 emit q->error(QAbstractSocket::SslHandshakeFailedError);
2302 plainSocket->disconnectFromHost();
2312 bool QSslSocketPrivate::verifyErrorsHaveBeenIgnored()
2314 bool doEmitSslError;
2315 if (!ignoreErrorsList.empty()) {
2316 // check whether the errors we got are all in the list of expected errors
2317 // (applies only if the method QSslSocket::ignoreSslErrors(const QList<QSslError> &errors)
2319 doEmitSslError = false;
2320 for (int a = 0; a < sslErrors.count(); a++) {
2321 if (!ignoreErrorsList.contains(sslErrors.at(a))) {
2322 doEmitSslError = true;
2327 // if QSslSocket::ignoreSslErrors(const QList<QSslError> &errors) was not called and
2328 // we get an SSL error, emit a signal unless we ignored all errors (by calling
2329 // QSslSocket::ignoreSslErrors() )
2330 doEmitSslError = !ignoreAllSslErrors;
2332 return !doEmitSslError;
2338 qint64 QSslSocketPrivate::peek(char *data, qint64 maxSize)
2340 if (mode == QSslSocket::UnencryptedMode && !autoStartHandshake) {
2341 //unencrypted mode - do not use QIODevice::peek, as it reads ahead data from the plain socket
2342 //peek at data already in the QIODevice buffer (from a previous read)
2343 qint64 r = buffer.peek(data, maxSize);
2347 //peek at data in the plain socket
2349 qint64 r2 = plainSocket->peek(data, maxSize - r);
2351 return (r > 0 ? r : r2);
2357 //encrypted mode - the socket engine will read and decrypt data into the QIODevice buffer
2358 return QTcpSocketPrivate::peek(data, maxSize);
2365 QByteArray QSslSocketPrivate::peek(qint64 maxSize)
2367 if (mode == QSslSocket::UnencryptedMode && !autoStartHandshake) {
2368 //unencrypted mode - do not use QIODevice::peek, as it reads ahead data from the plain socket
2369 //peek at data already in the QIODevice buffer (from a previous read)
2371 ret.reserve(maxSize);
2372 ret.resize(buffer.peek(ret.data(), maxSize));
2373 if (ret.length() == maxSize)
2375 //peek at data in the plain socket
2377 return ret + plainSocket->peek(maxSize - ret.length());
2379 return QByteArray();
2381 //encrypted mode - the socket engine will read and decrypt data into the QIODevice buffer
2382 return QTcpSocketPrivate::peek(maxSize);
2389 QList<QByteArray> QSslSocketPrivate::unixRootCertDirectories()
2391 return QList<QByteArray>() << "/etc/ssl/certs/" // (K)ubuntu, OpenSUSE, Mandriva, MeeGo ...
2392 << "/usr/lib/ssl/certs/" // Gentoo, Mandrake
2393 << "/usr/share/ssl/" // Centos, Redhat, SuSE
2394 << "/usr/local/ssl/" // Normal OpenSSL Tarball
2395 << "/var/ssl/certs/" // AIX
2396 << "/usr/local/ssl/certs/" // Solaris
2397 << "/opt/openssl/certs/"; // HP-UX
2402 #include "moc_qsslsocket.cpp"