CopperSpice API
1.9.2
|
QSslSocket class provides an SSL encrypted socket for both clients and servers. More...
Public Types | |
enum | PeerVerifyMode |
enum | SslMode |
Public Types inherited from QAbstractSocket | |
enum | BindFlag |
enum | NetworkLayerProtocol |
enum | PauseMode |
enum | SocketError |
enum | SocketOption |
enum | SocketState |
enum | SocketType |
Public Types inherited from QIODevice | |
enum | OpenModeFlag |
Public Signals | |
void | encrypted () |
void | encryptedBytesWritten (qint64 totalBytes) |
void | modeChanged (QSslSocket::SslMode newMode) |
void | peerVerifyError (const QSslError &error) |
void | preSharedKeyAuthenticationRequired (QSslPreSharedKeyAuthenticator *authenticator) |
void | sslErrors (const QList< QSslError > &errors) |
Public Signals inherited from QAbstractSocket | |
void | connected () |
void | disconnected () |
void | error (QAbstractSocket::SocketError socketError) |
void | hostFound () |
void | proxyAuthenticationRequired (const QNetworkProxy &proxy, QAuthenticator *authenticator) |
void | stateChanged (QAbstractSocket::SocketState socketState) |
Public Signals inherited from QIODevice | |
void | aboutToClose () |
void | bytesWritten (qint64 bytes) |
void | readChannelFinished () |
void | readyRead () |
Public Signals inherited from QObject | |
void | destroyed (QObject *obj=nullptr) |
void | objectNameChanged (const QString &objectName) |
Public Slots | |
void | ignoreSslErrors () |
void | startClientEncryption () |
void | startServerEncryption () |
Public Slots inherited from QObject | |
void | deleteLater () |
Public Methods | |
QSslSocket (QObject *parent=nullptr) | |
~QSslSocket () | |
void | abort () |
void | addCaCertificate (const QSslCertificate &certificate) |
void | addCaCertificates (const QList< QSslCertificate > &certificates) |
bool | addCaCertificates (const QString &path, QSsl::EncodingFormat format=QSsl::Pem, QPatternOption syntax=QPatternOption::FixedStringOption) |
bool | atEnd () const override |
qint64 | bytesAvailable () const override |
qint64 | bytesToWrite () const override |
bool | canReadLine () const override |
void | close () override |
virtual void | connectToHost (const QHostAddress &address, quint16 port, OpenMode openMode=ReadWrite) |
virtual void | connectToHost (const QString &hostName, quint16 port, OpenMode openMode=ReadWrite, NetworkLayerProtocol protocol=AnyIPProtocol) |
void | connectToHost (const QString &hostName, quint16 port, OpenMode openMode=ReadWrite, NetworkLayerProtocol protocol=AnyIPProtocol) override |
void | connectToHostEncrypted (const QString &hostName, quint16 port, const QString &sslPeerName, OpenMode mode=ReadWrite, NetworkLayerProtocol protocol=AnyIPProtocol) |
void | connectToHostEncrypted (const QString &hostName, quint16 port, OpenMode mode=ReadWrite, NetworkLayerProtocol protocol=AnyIPProtocol) |
void | disconnectFromHost () override |
qint64 | encryptedBytesAvailable () const |
qint64 | encryptedBytesToWrite () const |
bool | flush () |
void | ignoreSslErrors (const QList< QSslError > &errors) |
bool | isEncrypted () const |
QSslCertificate | localCertificate () const |
QList< QSslCertificate > | localCertificateChain () const |
SslMode | mode () const |
QSslCertificate | peerCertificate () const |
QList< QSslCertificate > | peerCertificateChain () const |
int | peerVerifyDepth () const |
QSslSocket::PeerVerifyMode | peerVerifyMode () const |
QString | peerVerifyName () const |
QSslKey | privateKey () const |
QSsl::SslProtocol | protocol () const |
void | resume () override |
QSslCipher | sessionCipher () const |
QSsl::SslProtocol | sessionProtocol () const |
void | setLocalCertificate (const QSslCertificate &certificate) |
void | setLocalCertificate (const QString &fileName, QSsl::EncodingFormat format=QSsl::Pem) |
void | setLocalCertificateChain (const QList< QSslCertificate > &localChain) |
void | setPeerVerifyDepth (int depth) |
void | setPeerVerifyMode (QSslSocket::PeerVerifyMode mode) |
void | setPeerVerifyName (const QString &hostName) |
void | setPrivateKey (const QSslKey &key) |
void | setPrivateKey (const QString &fileName, QSsl::KeyAlgorithm algorithm=QSsl::Rsa, QSsl::EncodingFormat format=QSsl::Pem, const QByteArray &passPhrase=QByteArray ()) |
void | setProtocol (QSsl::SslProtocol protocol) |
void | setReadBufferSize (qint64 size) override |
bool | setSocketDescriptor (qintptr socketDescriptor, SocketState state=ConnectedState, OpenMode openMode=ReadWrite) override |
void | setSocketOption (QAbstractSocket::SocketOption option, const QVariant &value) override |
void | setSslConfiguration (const QSslConfiguration &configuration) |
QVariant | socketOption (QAbstractSocket::SocketOption option) override |
QSslConfiguration | sslConfiguration () const |
QList< QSslError > | sslErrors () const |
bool | waitForBytesWritten (int msecs=30000) override |
bool | waitForConnected (int msecs=30000) override |
bool | waitForDisconnected (int msecs=30000) override |
bool | waitForEncrypted (int msecs=30000) |
bool | waitForReadyRead (int msecs=30000) override |
Public Methods inherited from QTcpSocket | |
QTcpSocket (QObject *parent=nullptr) | |
virtual | ~QTcpSocket () |
Public Methods inherited from QAbstractSocket | |
QAbstractSocket (SocketType socketType, QObject *parent) | |
virtual | ~QAbstractSocket () |
void | abort () |
bool | bind (const QHostAddress &address, quint16 port=0, BindMode mode=DefaultForPlatform) |
bool | bind (quint16 port=0, BindMode mode=DefaultForPlatform) |
virtual void | connectToHost (const QHostAddress &address, quint16 port, OpenMode openMode=ReadWrite) |
SocketError | error () const |
bool | flush () |
bool | isSequential () const override |
bool | isValid () const |
QHostAddress | localAddress () const |
quint16 | localPort () const |
PauseModes | pauseMode () const |
QHostAddress | peerAddress () const |
QString | peerName () const |
quint16 | peerPort () const |
QNetworkProxy | proxy () const |
qint64 | readBufferSize () const |
void | setPauseMode (PauseModes pauseMode) |
void | setProxy (const QNetworkProxy &networkProxy) |
virtual qintptr | socketDescriptor () const |
SocketType | socketType () const |
SocketState | state () const |
Public Methods inherited from QIODevice | |
QIODevice () | |
QIODevice (QObject *parent) | |
virtual | ~QIODevice () |
QString | errorString () const |
bool | getChar (char *c) |
bool | isOpen () const |
bool | isReadable () const |
bool | isTextModeEnabled () const |
bool | isWritable () const |
virtual bool | open (OpenMode mode) |
OpenMode | openMode () const |
qint64 | peek (char *data, qint64 maxSize) |
QByteArray | peek (qint64 maxSize) |
virtual qint64 | pos () const |
bool | putChar (char c) |
qint64 | read (char *data, qint64 maxSize) |
QByteArray | read (qint64 maxSize) |
QByteArray | readAll () |
qint64 | readLine (char *data, qint64 maxSize) |
QByteArray | readLine (qint64 maxSize=0) |
virtual bool | reset () |
virtual bool | seek (qint64 pos) |
void | setTextModeEnabled (bool enabled) |
virtual qint64 | size () const |
void | ungetChar (char c) |
qint64 | write (const char *data) |
qint64 | write (const char *data, qint64 maxSize) |
qint64 | write (const QByteArray &data) |
Public Methods inherited from QObject | |
QObject (QObject *parent=nullptr) | |
~QObject () | |
bool | blockSignals (bool block) |
const QList< QObject * > & | children () const |
bool | connect (const QObject *sender, const QString &signalMethod, const QString &location, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection) |
bool | connect (const QObject *sender, const QString &signalMethod, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection) |
bool | disconnect (const QObject *receiver, const QString &slotMethod=QString ()) const |
bool | disconnect (const QString &signalMethod, const QString &location, const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const |
bool | disconnect (const QString &signalMethod=QString (), const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const |
void | dumpObjectInfo () |
void | dumpObjectTree () |
QList< QString > | dynamicPropertyNames () const |
virtual bool | event (QEvent *event) |
virtual bool | eventFilter (QObject *watched, QEvent *event) |
template<typename T > | |
T | findChild (const QString &childName=QString ()) const |
template<class T > | |
QList< T > | findChildren (const QRegularExpression ®Exp, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const |
template<class T > | |
QList< T > | findChildren (const QString &childName=QString (), Qt::FindChildOptions options=Qt::FindChildrenRecursively) const |
bool | inherits (const QString &className) const |
void | installEventFilter (QObject *filterObj) |
bool | isWidgetType () const |
bool | isWindowType () const |
void | killTimer (int id) |
const QMetaObject * | metaObject () const |
void | moveToThread (QThread *targetThread) |
QString | objectName () const |
QObject * | parent () const |
template<class T = QVariant> | |
T | property (const QString &name) const |
void | removeEventFilter (QObject *obj) |
void | setObjectName (const QString &name) |
void | setParent (QObject *parent) |
bool | setProperty (const QString &name, const QVariant &value) |
bool | signalsBlocked () const |
int | startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer) |
QThread * | thread () const |
Static Public Methods | |
static void | addDefaultCaCertificate (const QSslCertificate &certificate) |
static void | addDefaultCaCertificates (const QList< QSslCertificate > &certificates) |
static bool | addDefaultCaCertificates (const QString &path, QSsl::EncodingFormat format=QSsl::Pem, QPatternOption syntax=QPatternOption::FixedStringOption) |
static long | sslLibraryBuildVersionNumber () |
static QString | sslLibraryBuildVersionString () |
static long | sslLibraryVersionNumber () |
static QString | sslLibraryVersionString () |
static bool | supportsSsl () |
Static Public Methods inherited from QObject | |
static bool | connect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod, Qt::ConnectionType type=Qt::AutoConnection) |
static bool | connect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection, const QString &location=QString ()) |
static bool | connect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection) |
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn > | |
static bool | connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...), Qt::ConnectionType type=Qt::AutoConnection) |
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T > | |
static bool | connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotLambda, Qt::ConnectionType type=Qt::AutoConnection) |
static bool | disconnect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod) |
static bool | disconnect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod) |
static bool | disconnect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod) |
static bool | disconnect (const QObject *sender, std::nullptr_t, const QObject *receiver, std::nullptr_t) |
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn > | |
static bool | disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...)) |
template<class Sender , class SignalClass , class... SignalArgs, class Receiver > | |
static bool | disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, std::nullptr_t slotMethod=nullptr) |
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T > | |
static bool | disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotMethod) |
static QMetaObject & | staticMetaObject () |
static QString | tr (const char *text, const char *comment=nullptr, std::optional< int > numArg=std::optional< int >()) |
Protected Methods | |
qint64 | readData (char *data, qint64 maxlen) override |
qint64 | writeData (const char *data, qint64 len) override |
Protected Methods inherited from QAbstractSocket | |
qint64 | readLineData (char *data, qint64 maxlen) override |
void | setLocalAddress (const QHostAddress &address) |
void | setLocalPort (quint16 port) |
void | setPeerAddress (const QHostAddress &address) |
void | setPeerName (const QString &name) |
void | setPeerPort (quint16 port) |
void | setSocketError (SocketError socketError) |
void | setSocketState (SocketState state) |
Protected Methods inherited from QIODevice | |
void | setErrorString (const QString &errorString) |
void | setOpenMode (OpenMode openMode) |
Protected Methods inherited from QObject | |
virtual void | childEvent (QChildEvent *event) |
virtual void | connectNotify (const QMetaMethod &signalMethod) const |
virtual void | customEvent (QEvent *event) |
virtual void | disconnectNotify (const QMetaMethod &signalMethod) const |
bool | isSignalConnected (const QMetaMethod &signalMethod) const |
int | receivers (const QString &signal) const |
QObject * | sender () const |
int | senderSignalIndex () const |
virtual void | timerEvent (QTimerEvent *event) |
Additional Inherited Members | |
Public Typedefs inherited from QAbstractSocket | |
using | BindMode = QFlags< BindFlag > |
using | PauseModes = QFlags< PauseMode > |
Public Typedefs inherited from QIODevice | |
using | OpenMode = QFlags< OpenModeFlag > |
Properties inherited from QObject | |
objectName | |
Related Functions inherited from QObject | |
T | qobject_cast (QObject *object) |
QObjectList | |
The QSslSocket class provides an SSL encrypted socket for both clients and servers. This class establishes a secure, encrypted TCP connection you can use for transmitting encrypted data. It can operate in both client and server mode, and it supports modern SSL protocols, including SSLv3 and TLSv1. By default, QSslSocket uses TLSv1, however you change the SSL protocol by calling setProtocol() as long as you do it before the handshake has started.
SSL encryption operates on top of the existing TCP stream after the socket enters the ConnectedState. There are two simple ways to establish a secure connection using QSslSocket: With an immediate SSL handshake, or with a delayed SSL handshake occurring after the connection has been established in unencrypted mode.
The most common way to use QSslSocket is to construct an object and start a secure connection by calling connectToHostEncrypted(). This method starts an immediate SSL handshake once the connection has been established.
As with a plain QTcpSocket, QSslSocket enters the HostLookupState, ConnectingState, and finally the ConnectedState, if the connection is successful. The handshake then starts automatically, and if it succeeds, the encrypted() signal is emitted to indicate the socket has entered the encrypted state and is ready for use.
The data can be written to the socket immediately after the return from connectToHostEncrypted() (i.e., before the encrypted() signal is emitted). The data is queued in QSslSocket until after the encrypted() signal is emitted.
An example of using the delayed SSL handshake to secure an existing connection is the case where an SSL server secures an incoming connection. Suppose you create an SSL server class as a subclass of QTcpServer. You would override QTcpServer::incomingConnection() with something like the example below, which first constructs an instance of QSslSocket and then calls setSocketDescriptor() to set the new socket's descriptor to the existing one passed in. It then initiates the SSL handshake by calling startServerEncryption().
If an error occurs QSslSocket emits the sslErrors() signal. If no action is taken to ignore the error the connection will be dropped. To continue, despite the occurrence of an error, call ignoreSslErrors() either from within this slot after the error occurs or any time after construction of the QSslSocket and before the connection is attempted. This will allow QSslSocket to ignore the errors it encounters when establishing the identity of the peer. Ignoring errors during an SSL handshake should be used with caution, since a fundamental characteristic of secure connections is that they should be established with a successful handshake.
Once encrypted a QSslSocket can be used as a regular QTcpSocket. When readyRead() is emitted, you can call read(), canReadLine() and readLine(), or getChar() to read decrypted data from QSslSocket's internal buffer, and you can call write() or putChar() to write data back to the peer. QSslSocket will automatically encrypt the written data for you, and emit encryptedBytesWritten() once the data has been written to the peer.
QSslSocket supports QTcpSocket's blocking methods waitForConnected(), waitForReadyRead(), waitForBytesWritten(), and waitForDisconnected(). It also provides waitForEncrypted() which will block the calling thread until an encrypted connection has been established.
QSslSocket provides an extensive, easy-to-use API for handling cryptographic ciphers, private keys, and local, peer, and Certification Authority (CA) certificates. It also provides an API for handling errors that occur during the handshake phase.
If available root certificates on Unix will be loaded on demand from the standard certificate directories. If you do not want to load root certificates on demand call QSslConfiguration::defaultConfiguration().setCaCertificates() before the first SSL handshake is made in your application.
For more information about ciphers and certificates refer to QSslCipher and QSslCertificate.
There is an important difference between the bytesWritten() signal and the encryptedBytesWritten() signal. For a QTcpSocket bytesWritten() will get emitted as soon as data has been written to the TCP socket. For a QSslSocket, bytesWritten() will get emitted when the data is being encrypted and encryptedBytesWritten() will get emitted as soon as data has been written to the TCP socket.
Describes the peer verification modes for QSslSocket. The default mode is AutoVerifyPeer, which selects an appropriate mode depending on the socket's QSocket::SslMode.
Constant | Value | Description |
---|---|---|
QSslSocket::VerifyNone | 0 | QSslSocket will not request a certificate from the peer. You can set this mode if you are not interested in the identity of the other side of the connection. The connection will still be encrypted, and your socket will still send its local certificate to the peer if it's requested. |
QSslSocket::QueryPeer | 1 | QSslSocket will request a certificate from the peer, but does not require this certificate to be valid. This is useful when you want to display peer certificate details to the user without affecting the actual SSL handshake. This mode is the default for servers. |
QSslSocket::VerifyPeer | 2 | QSslSocket will request a certificate from the peer during the SSL handshake phase, and requires that this certificate is valid. On failure, QSslSocket will emit the QSslSocket::sslErrors() signal. This mode is the default for clients. |
QSslSocket::AutoVerifyPeer | 3 | QSslSocket will automatically use QueryPeer for server sockets and VerifyPeer for client sockets. |
enum QSslSocket::SslMode |
Describes the connection modes available for QSslSocket.
Constant | Value | Description |
---|---|---|
QSslSocket::UnencryptedMode | 0 | The socket is unencrypted. Its behavior is identical to QTcpSocket. |
QSslSocket::SslClientMode | 1 | The socket is a client-side SSL socket. It is either already encrypted, or it is in the SSL handshake phase (see QSslSocket::isEncrypted()). |
QSslSocket::SslServerMode | 2 | The socket is a server-side SSL socket. It is either already encrypted, or it is in the SSL handshake phase (see QSslSocket::isEncrypted()). |
QSslSocket::QSslSocket | ( | QObject * | parent = nullptr | ) |
Constructs a QSslSocket object. The parent object is passed to the QObject constructor. The new socket's cipher suite is set to the one returned by the static method QSslConfiguration::setCiphers().
QSslSocket::~QSslSocket | ( | ) |
Destroys the QSslSocket.
void QSslSocket::abort | ( | ) |
Aborts the current connection and resets the socket. Unlike disconnectFromHost(), this function immediately closes the socket, clearing any pending data in the write buffer.
void QSslSocket::addCaCertificate | ( | const QSslCertificate & | certificate | ) |
Adds the certificate to this socket's CA certificate database. The CA certificate database is used by the socket during the handshake phase to validate the peer's certificate.
To add multiple certificates use addCaCertificates().
void QSslSocket::addCaCertificates | ( | const QList< QSslCertificate > & | certificates | ) |
Adds the certificates to this socket's CA certificate database. The CA certificate database is used by the socket during the handshake phase to validate the peer's certificate.
For more precise control, use addCaCertificate().
bool QSslSocket::addCaCertificates | ( | const QString & | path, |
QSsl::EncodingFormat | format = QSsl::Pem , |
||
QPatternOption | syntax = QPatternOption::FixedStringOption |
||
) |
Searches all files in the path for certificates encoded in the specified format and adds them to this socket's CA certificate database. Path can be explicit, or it can contain wildcards in the format specified by syntax. Returns true if one or more certificates are added to the socket's CA certificate database; otherwise returns false.
The CA certificate database is used by the socket during the handshake phase to validate the peer's certificate.
For more precise control use addCaCertificate().
|
static |
Adds certificate to the default CA certificate database. Each SSL socket's CA certificate database is initialized to the default CA certificate database.
|
static |
Adds certificates to the default CA certificate database. Each SSL socket's CA certificate database is initialized to the default CA certificate database.
|
static |
Searches all files in the path for certificates with the specified format and adds them to the default CA certificate database. The path can be an explicit file, or it can contain wildcards in the format specified by syntax. Returns true if any CA certificates are added to the default database.
Each SSL socket's CA certificate database is initialized to the default CA certificate database.
|
overridevirtual |
Reimplemented from QAbstractSocket::atEnd()
|
overridevirtual |
Returns the number of decrypted bytes that are immediately available for reading.
Reimplemented from QAbstractSocket::bytesAvailable()
|
overridevirtual |
Returns the number of unencrypted bytes that are waiting to be encrypted and written to the network.
Reimplemented from QAbstractSocket::bytesToWrite()
|
overridevirtual |
Returns true if one entire line terminated by a single '\n' character can be read, otherwise false is returned.
Reimplemented from QAbstractSocket::canReadLine()
|
overridevirtual |
Reimplemented from QAbstractSocket::close()
|
using |
Attempts to make a connection to address on the given port.
|
using |
Attempts to make a connection to hostname on the given port.
The socket is opened in the given openMode and first enters HostLookupState, then performs a host name lookup of hostName. If the lookup succeeds, hostFound() is emitted and QAbstractSocket enters ConnectingState. It then attempts to connect to the address or addresses returned by the lookup. Finally, if a connection is established, QAbstractSocket enters ConnectedState and emits connected().
At any point the socket can emit error() to signal that an error occurred.
The parameter hostName can be an IP address like "127.0.0.1" or it can be a host name like "example.com". QAbstractSocket will do a lookup only if required. The port is in native byte order.
|
overridevirtual |
Attempts to make a connection to hostname on the given port.
The socket is opened in the given openMode and first enters HostLookupState, then performs a host name lookup of hostName. If the lookup succeeds, hostFound() is emitted and QAbstractSocket enters ConnectingState. It then attempts to connect to the address or addresses returned by the lookup. Finally, if a connection is established, QAbstractSocket enters ConnectedState and emits connected().
At any point the socket can emit error() to signal that an error occurred.
The parameter hostName can be an IP address like "127.0.0.1" or it can be a host name like "example.com". QAbstractSocket will do a lookup only if required. The port is in native byte order.
Reimplemented from QAbstractSocket::connectToHost()
void QSslSocket::connectToHostEncrypted | ( | const QString & | hostName, |
quint16 | port, | ||
const QString & | sslPeerName, | ||
OpenMode | mode = ReadWrite , |
||
NetworkLayerProtocol | protocol = AnyIPProtocol |
||
) |
In addition to the original behavior of connectToHostEncrypted, this overloaded method enables the usage of a different hostname (sslPeerName) for the certificate validation instead of the one used for the TCP connection (hostname).
void QSslSocket::connectToHostEncrypted | ( | const QString & | hostName, |
quint16 | port, | ||
OpenMode | mode = ReadWrite , |
||
NetworkLayerProtocol | protocol = AnyIPProtocol |
||
) |
Starts an encrypted connection to the device hostName on port using mode as the OpenMode. This is equivalent to calling connectToHost() to establish the connection followed by a call to startClientEncryption(). The default for mode is ReadWrite.
QSslSocket first enters the HostLookupState. Then, after entering either the event loop or one of the waitFor...() functions, it enters the ConnectingState, emits connected(), and then initiates the SSL client handshake. At each state change, QSslSocket emits signal stateChanged().
After initiating the SSL client handshake, if the identity of the peer can not be established, signal sslErrors() is emitted. If you want to ignore the errors and continue connecting, you must call ignoreSslErrors(), either from inside a slot function connected to the sslErrors() signal, or prior to entering encrypted mode. If ignoreSslErrors() is not called, the connection is dropped, signal disconnected() is emitted, and QSslSocket returns to the UnconnectedState.
If the SSL handshake is successful, QSslSocket emits encrypted().
The example above shows that text can be written to the socket immediately after requesting the encrypted connection, before the encrypted() signal has been emitted. In such cases, the text is queued in the object and written to the socket after the connection is established and the encrypted() signal has been emitted.
If you want to create a QSslSocket on the server side of a connection you should instead call startServerEncryption() upon receiving the incoming connection through QTcpServer.
|
overridevirtual |
Attempts to close the socket. If there is pending data waiting to be written, QAbstractSocket will enter ClosingState and wait until all data has been written. Eventually, it will enter UnconnectedState and emit the disconnected() signal.
Reimplemented from QAbstractSocket::disconnectFromHost()
|
signal |
This signal is emitted when QSslSocket enters encrypted mode. After this signal has been emitted, QSslSocket::isEncrypted() will return true, and all further transmissions on the socket will be encrypted.
qint64 QSslSocket::encryptedBytesAvailable | ( | ) | const |
Returns the number of encrypted bytes that are awaiting decryption. Normally, this function will return 0 because QSslSocket decrypts its incoming data as soon as it can.
qint64 QSslSocket::encryptedBytesToWrite | ( | ) | const |
Returns the number of encrypted bytes that are waiting to be written to the network.
|
signal |
This signal is emitted when QSslSocket writes its encrypted data to the network. The totalBytes parameter contains the number of bytes that were successfully written.
bool QSslSocket::flush | ( | ) |
This method writes as much as possible from the internal write buffer to the underlying network socket, without blocking. If any data was written, this function returns true, otherwise false is returned.
Call this method if you need QSslSocket to start sending buffered data immediately. The number of bytes successfully written depends on the operating system. In most cases, you do not need to call this function, because QAbstractSocket will start sending data automatically once control goes back to the event loop. In the absence of an event loop, call waitForBytesWritten() instead.
|
slot |
This slot tells QSslSocket to ignore errors during QSslSocket's handshake phase and continue connecting. If you want to continue with the connection even if errors occur during the handshake phase, then you must call this slot, either from a slot connected to sslErrors(), or before the handshake phase. If you do not call this slot, either in response to errors or before the handshake, the connection will be dropped after the sslErrors() signal has been emitted.
If there are no errors during the SSL handshake phase (i.e., the identity of the peer is established with no problems), QSslSocket will not emit the sslErrors() signal, and it is unnecessary to call this function.
This method configures QSslSocket to ignore a specific set of errors given in errors. Multiple calls to this method will replace the list of errors that were passed in previous calls. You can clear the list of errors you want to ignore by calling this function with an empty list.
For example, if you want to connect to a Server and allow a self signed certificate use code similar to the following.
bool QSslSocket::isEncrypted | ( | ) | const |
Returns true if the socket is encrypted, otherwise false is returned.
An encrypted socket encrypts all data that is written by calling write() or putChar() before the data is written to the network, and decrypts all incoming data as the data is received from the network, before you call read(), readLine() or getChar().
QSslSocket emits encrypted() when it enters encrypted mode.
You can call sessionCipher() to find which cryptographic cipher is used to encrypt and decrypt your data.
QSslCertificate QSslSocket::localCertificate | ( | ) | const |
Returns the socket's local certificate, or an empty certificate if no local certificate has been assigned.
QList< QSslCertificate > QSslSocket::localCertificateChain | ( | ) | const |
Returns the socket's local certificate chain, or an empty list if no local certificates have been assigned.
SslMode QSslSocket::mode | ( | ) | const |
Returns the current mode for the socket. The value can be either UnencryptedMode, where QSslSocket behaves identically to QTcpSocket, or one of SslClientMode or SslServerMode, where the client is either negotiating or in encrypted mode. When the mode changes, QSslSocket emits modeChanged()
|
signal |
This signal is emitted when QSslSocket changes from QSslSocket::UnencryptedMode to either QSslSocket::SslClientMode or QSslSocket::SslServerMode. The newMode is the new mode.
QSslCertificate QSslSocket::peerCertificate | ( | ) | const |
Returns the peer's digital certificate (i.e., the immediate certificate of the host you are connected to), or a null certificate, if the peer has not assigned a certificate.
The peer certificate is checked automatically during the handshake phase, so this function is normally used to fetch the certificate for display or for connection diagnostic purposes. It contains information about the peer, including its host name, the certificate issuer, and the peer's public key.
Because the peer certificate is set during the handshake phase, it is safe to access the peer certificate from a slot connected to the sslErrors() signal or the encrypted() signal.
If a null certificate is returned, it can mean the SSL handshake failed, or it can mean the host you are connected to does not have a certificate, or it can mean there is no connection.
If you want to check the peer's complete chain of certificates, use peerCertificateChain() to get them all at once.
QList< QSslCertificate > QSslSocket::peerCertificateChain | ( | ) | const |
Returns the peer's chain of digital certificates, or an empty list of certificates.
Peer certificates are checked automatically during the handshake phase. This function is normally used to fetch certificates for display, or for performing connection diagnostics. Certificates contain information about the peer and the certificate issuers, including host name, issuer names, and issuer public keys.
The peer certificates are set in QSslSocket during the handshake phase, so it is safe to call this function from a slot connected to the sslErrors() signal or the encrypted() signal.
If an empty list is returned, it can mean the SSL handshake failed, or it can mean the host you are connected to does not have a certificate, or it can mean there is no connection.
If you want to get only the peer's immediate certificate, use peerCertificate().
int QSslSocket::peerVerifyDepth | ( | ) | const |
Returns the maximum number of certificates in the peer's certificate chain to be checked during the SSL handshake phase, or 0 (the default) if no maximum depth has been set, indicating that the whole certificate chain should be checked.
The certificates are checked in issuing order, starting with the peer's own certificate, then its issuer's certificate, and so on.
|
signal |
QSslSocket can emit this signal several times during the SSL handshake, before encryption has been established, to indicate that an error has occurred while establishing the identity of the peer. The error is usually an indication that QSslSocket is unable to securely identify the peer.
This signal provides you with an early indication when something's wrong. By connecting to this signal, you can manually choose to tear down the connection from inside the connected slot before the handshake has completed. If no action is taken, QSslSocket will proceed to emitting QSslSocket::sslErrors().
PeerVerifyMode QSslSocket::peerVerifyMode | ( | ) | const |
Returns the socket's verify mode. The mode decides whether QSslSocket should request a certificate from the peer (i.e., the client requests a certificate from the server, or a server requesting a certificate from the client), and whether it should require that this certificate is valid.
The default mode is AutoVerifyPeer which informs QSslSocket to use VerifyPeer for clients and QueryPeer for servers.
QString QSslSocket::peerVerifyName | ( | ) | const |
Returns the different hostname for the certificate validation, as set by setPeerVerifyName or by connectToHostEncrypted.
|
signal |
QSslSocket emits this signal when it negotiates a PSK ciphersuite, and therefore a PSK authentication is then required.
When using PSK, the client must send to the server a valid identity and a valid pre shared key, in order for the SSL handshake to continue. Applications can provide this information in a slot connected to this signal, by filling in the passed authenticator object according to their needs.
Ignoring this signal, or failing to provide the required credentials, will cause the handshake to fail, and therefore the connection to be aborted.
The authenticator object is owned by the socket and must not be deleted by the application.
QSslKey QSslSocket::privateKey | ( | ) | const |
Returns this socket's private key.
QSsl::SslProtocol QSslSocket::protocol | ( | ) | const |
Returns the socket's SSL protocol. By default, QSsl::SecureProtocols is used.
Reimplemented from QAbstractSocket::readData()
|
overridevirtual |
Continues data transfer on the socket. This method should only be used after the socket has been set to pause upon notifications and a notification has been received. The only notification currently supported is QSslSocket::sslErrors(). Calling this method if the socket is not paused results in undefined behavior.
Reimplemented from QAbstractSocket::resume()
QSslCipher QSslSocket::sessionCipher | ( | ) | const |
Returns the socket's cryptographic cipher, or a null cipher if the connection is not encrypted. The socket's cipher for the session is set during the handshake phase. The cipher is used to encrypt and decrypt data transmitted through the socket.
QSslSocket also provides functions for setting the ordered list of ciphers from which the handshake phase will eventually select the session cipher. This ordered list must be in place before the handshake phase begins.
QSsl::SslProtocol QSslSocket::sessionProtocol | ( | ) | const |
Returns the socket's SSL/TLS protocol or UnknownProtocol if the connection is not encrypted. The socket protocol for the session is set during the handshake phase.
void QSslSocket::setLocalCertificate | ( | const QSslCertificate & | certificate | ) |
Sets the socket's local certificate to certificate. The local certificate is necessary if you need to confirm your identity to the peer. It is used together with the private key. If you set the local certificate you must also set the private key.
The local certificate and private key are always necessary for server sockets, but are also rarely used by client sockets if the server requires the client to authenticate.
Sets the socket's local certificate to certificate. The local certificate is necessary if you need to confirm your identity to the peer. It is used together with the private key; if you set the local certificate, you must also set the private key.
The local certificate and private key are always necessary for server sockets, but are also rarely used by client sockets if the server requires the client to authenticate.
void QSslSocket::setLocalCertificate | ( | const QString & | fileName, |
QSsl::EncodingFormat | format = QSsl::Pem |
||
) |
Sets the socket's local certificate to the first one found in fileName, which is parsed according to the specified format.
void QSslSocket::setLocalCertificateChain | ( | const QList< QSslCertificate > & | localChain | ) |
Sets the certificate chain to be presented to the peer during the SSL handshake to be localChain.
void QSslSocket::setPeerVerifyDepth | ( | int | depth | ) |
Sets the maximum number of certificates in the peer's certificate chain to be checked during the SSL handshake phase, to depth. Setting a depth of 0 means that no maximum depth is set, indicating that the whole certificate chain should be checked.
The certificates are checked in issuing order, starting with the peer's own certificate, then its issuer's certificate, and so on.
void QSslSocket::setPeerVerifyMode | ( | QSslSocket::PeerVerifyMode | mode | ) |
Sets the socket's verify mode to mode. This mode decides whether QSslSocket should request a certificate from the peer (i.e., the client requests a certificate from the server, or a server requesting a certificate from the client), and whether it should require that this certificate is valid.
The default mode is AutoVerifyPeer, which tells QSslSocket to use VerifyPeer for clients and QueryPeer for servers. Setting this mode after encryption has started has no effect on the current connection.
void QSslSocket::setPeerVerifyName | ( | const QString & | hostName | ) |
Sets a different host name, given by hostname, for the certificate validation instead of the one used for the TCP connection.
void QSslSocket::setPrivateKey | ( | const QSslKey & | key | ) |
Sets the socket's private key to key. The private key and the local certificate are used by clients and servers that must prove their identity to SSL peers.
Both the key and the local certificate are required if you are creating an SSL server socket. If you are creating an SSL client socket, the key and local certificate are required if your client must identify itself to an SSL server.
void QSslSocket::setPrivateKey | ( | const QString & | fileName, |
QSsl::KeyAlgorithm | algorithm = QSsl::Rsa , |
||
QSsl::EncodingFormat | format = QSsl::Pem , |
||
const QByteArray & | passPhrase = QByteArray() |
||
) |
Reads the string in file fileName and decodes it using a specified algorithm and encoding format to construct an SSL key. If the encoded key is encrypted, passPhrase is used to decrypt it.
The socket's private key is set to the constructed key. The private key and the local certificate are used by clients and servers that must prove their identity to SSL peers. Both the key and the local certificate are required if you are creating an SSL server socket. If you are creating an SSL client socket, the key and local certificate are required if your client must identify itself to an SSL server.
void QSslSocket::setProtocol | ( | QSsl::SslProtocol | protocol | ) |
Sets the socket's SSL protocol to protocol. This will affect the next initiated handshake; calling this function on an already-encrypted socket will not affect the socket's protocol.
|
overridevirtual |
Sets the size of QSslSocket's internal read buffer to be size bytes.
Reimplemented from QAbstractSocket::setReadBufferSize()
|
overridevirtual |
Initializes QSslSocket with the native socket descriptor socketDescriptor. Returns true if socketDescriptor is accepted as a valid socket descriptor, otherwise returns false. The socket is opened in the mode specified by openMode, and enters the socket state specified by state.
Reimplemented from QAbstractSocket::setSocketDescriptor()
|
overridevirtual |
Sets the given option to the value described by value.
Reimplemented from QAbstractSocket::setSocketOption()
void QSslSocket::setSslConfiguration | ( | const QSslConfiguration & | configuration | ) |
Sets the socket's SSL configuration to be the contents of configuration. This method sets the local certificate, the ciphers, the private key and the CA certificates to those stored in configuration. It is not possible to set the SSL-state related fields.
|
overridevirtual |
Returns the value of option.
Reimplemented from QAbstractSocket::socketOption()
QSslConfiguration QSslSocket::sslConfiguration | ( | ) | const |
Returns the socket's SSL configuration state. The default SSL configuration of a socket is to use the default ciphers, default CA certificates, no local private key or certificate.
The SSL configuration also contains fields that can change with time without notice.
Returns a list of the last SSL errors that occurred. This is the same list as QSslSocket passes via the sslErrors() signal. If the connection has been encrypted with no errors, this function will return an empty list.
QSslSocket emits this signal after the SSL handshake to indicate that one or more errors have occurred while establishing the identity of the peer. The errors are usually an indication that QSslSocket is unable to securely identify the peer. Unless any action is taken, the connection will be dropped after this signal has been emitted.
If you want to continue connecting despite the errors that have occurred, you must call QSslSocket::ignoreSslErrors() from inside a slot connected to this signal. If you need to access the error list at a later point, you can call sslErrors() (without arguments).
errors contains one or more errors that prevent QSslSocket from verifying the identity of the peer.
Note: You can not use Qt::QueuedConnection when connecting to this signal, or calling QSslSocket::ignoreSslErrors() will have no effect.
|
static |
Returns the version number of the SSL library in use at compile time. If no SSL support is available then this will return an undefined value.
|
static |
Returns the version string of the SSL library in use at compile time. If no SSL support is available then this will return an empty value.
|
static |
Returns the version number of the SSL library in use. Note that this is the version of the library in use at runtime not compile time. If no SSL support is available then this will return an undefined value.
|
static |
Returns the version string of the SSL library in use. Note that this is the version of the library in use at runtime not compile time. If no SSL support is available then this will return an empty value.
|
slot |
Starts a delayed SSL handshake for a client connection. This function can be called when the socket is in the ConnectedState but still in the UnencryptedMode. If it is not yet connected, or if it is already encrypted, this function has no effect.
Clients that implement STARTTLS functionality often make use of delayed SSL handshakes. Most other clients can avoid calling this function directly by using connectToHostEncrypted() instead, which automatically performs the handshake.
|
slot |
Starts a delayed SSL handshake for a server connection. This function can be called when the socket is in the ConnectedState but still in UnencryptedMode. If it is not connected or it is already encrypted, the function has no effect.
For server sockets, calling this function is the only way to initiate the SSL handshake. Most servers will call this function immediately upon receiving a connection, or as a result of having received a protocol-specific command to enter SSL mode (e.g, the server may respond to receiving the string "STARTTLS\r\n" by calling this function).
The most common way to implement an SSL server is to create a subclass of QTcpServer and reimplement QTcpServer::incomingConnection(). The returned socket descriptor is then passed to QSslSocket::setSocketDescriptor().
|
static |
Returns true if this platform supports SSL encryption, otherwise returns false. If SSL encryption is not supported the socket will fail in the connection phase.
On most platforms SSL support depends on the OpenSSL library. Mac OS X uses the SecureTransport library.
|
overridevirtual |
Reimplemented from QAbstractSocket::waitForBytesWritten()
|
overridevirtual |
Waits until the socket is connected or msecs, whichever happens first. If the connection has been established this method returns true, otherwise it returns false.
Reimplemented from QAbstractSocket::waitForConnected()
|
overridevirtual |
Waits until the socket has disconnected or msecs, whichever comes first. If the connection has been disconnected, this method returns true, otherwise it returns false.
Reimplemented from QAbstractSocket::waitForDisconnected()
bool QSslSocket::waitForEncrypted | ( | int | msecs = 30000 | ) |
Waits until the socket has completed the SSL handshake and has emitted encrypted() or msecs, whichever comes first. If encrypted() has been emitted, this method returns true, otherwise false is returned.
The following example waits up to one second for the socket to be encrypted:
If msecs is -1, this function will not time out.
|
overridevirtual |
Reimplemented from QAbstractSocket::waitForReadyRead()
Reimplemented from QAbstractSocket::writeData()