Home · All Classes · Main Classes · Grouped Classes · Modules · Functions

QSslSocket Class Reference
[QtNetwork module]

The QSslSocket class provides an SSL encrypted socket for both clients and servers. More...

 #include <QSslSocket>

Inherits QTcpSocket.

Note: All the functions in this class are reentrant.

This class was introduced in Qt 4.3.

Public Types

Public Functions

Public Slots

Signals

Static Public Members

Additional Inherited Members


Detailed Description

The QSslSocket class provides an SSL encrypted socket for both clients and servers.

QSslSocket 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 SSLv3, but you can 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.

 QSslSocket *socket = new QSslSocket(this);
 connect(socket, SIGNAL(encrypted()), this, SLOT(ready()));

 socket->connectToHostEncrypted("imap.example.com", 993);

As with a plain QTcpSocket, QSslSocket enters the HostLookupState, ConnectingState, and finally the ConnectedState, if the connection is successful. The hand shake 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.

Note that 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 exiasting one passed in. It then initiates the SSL handshake by calling startServerEncryption().

 void SslServer::incomingConnection(int socketDescriptor)
 {
     QSslSocket *serverSocket = new QSslSocket;
     if (serverSocket->setSocketDescriptor(socketDescriptor)) {
         connect(serverSocket, SIGNAL(encrypted()), this, SLOT(ready()));
         serverSocket->startServerEncryption();
     } else {
         delete serverSocket;
     }
 }

If an error occurs, QSslSocket emits signal sslErrors. In this case, if no action is taken to ignore the error(s), the connection is dropped. To continue, despite the occurrance of an error, you can call ignoreSslErrors(), either from within this slot after the error occurs, or anytime 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, you use QSslSocket 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 bytesWritten() once the data has been written to the peer.

As a convenience, QSslSocket supports QTcpSocket's blocking functions waitForConnected(), waitForReadyRead(), waitForBytesWritten(), and waitForDisconnected(). It also provides waitForEncrypted(), which will block the calling thread until an encrypted connection has been established.

 QSslSocket socket;
 socket.connectToHostEncrypted("http.example.com", 443);
 if (!socket.waitForEncrypted()) {
     qDebug() << socket.errorString();
     return false;
 }

 socket.write("GET / HTTP/1.0\r\n\r\n");
 while (socket.waitForReadyRead())
     qDebug() << socket.readAll().data();

QSslSocket provides an extensive, easy-to-use API for handling SSL certificates, ciphers, and for managing errors. You can customize the socket's cryptographic cipher suite and CA database by calling setCiphers() or setCaCertificates(). For more information about ciphers, refer to QSslCipher's documentation. You can read about SSL certificates in the class documentation for QSslCertificate.

This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/).

See also QSslCertificate, QSslCipher, and QSslError.


Member Type Documentation

enum QSslSocket::Protocol

Describes the protocols avaialable for the connection.

ConstantValueDescription
QSslSocket::SslV30SSLv3
QSslSocket::SslV21SSLv2
QSslSocket::TlsV12TLSv1
QSslSocket::AnyProtocol3The socket understands SSLv2, SSLv3 and TLSv1.

enum QSslSocket::SslMode

Describes the connection modes available for QSslSocket.

ConstantValueDescription
QSslSocket::UnencryptedMode0The socket is unencrypted. Its behavior is identical to QTcpSocket.
QSslSocket::SslClientMode1The socket is a client-side SSL socket. It is either alreayd encrypted, or it is in the SSL handshake phase (see QSslSocket::isEncrypted()).
QSslSocket::SslServerMode2The socket is a client-side SSL socket. It is either already encrypted, or it is in the SSL handshake phase (see QSslSocket::isEncrypted()).


Member Function Documentation

QSslSocket::QSslSocket ( QObject * parent = 0 )

Constructs a QSslSocket object. parent is passed to QObject's constructor. The new socket's cipher suite is set to the one returned by the static method defaultCiphers().

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.

See also disconnectFromHost() and close().

void QSslSocket::addCaCertificate ( const QSslCertificate & certificate )

Adds certificate to this socket's CA certificate database.

See also caCertificates() and addDefaultCaCertificate().

bool QSslSocket::addCaCertificates ( const QString & path, QSsl::EncodingFormat format = QSsl::Pem, QRegExp::PatternSyntax syntax = QRegExp::FixedString )

Adds all CA certificates in path using format encoding, which may be a file, or a directory with syntax formatted wildcards. Returns true on success; otherwise returns false.

For more fine grained control, you can call addCaCertificate() instead.

See also addCaCertificate().

void QSslSocket::addCaCertificates ( const QList<QSslCertificate> & certificates )

This is an overloaded member function, provided for convenience.

Adds certificates to this socket's CA certificate database.

See also caCertificates() and addDefaultCaCertificate().

void QSslSocket::addDefaultCaCertificate ( const QSslCertificate & certificate )   [static]

Adds certificate to the global CA certificate database.

See also defaultCaCertificates() and addCaCertificates().

bool QSslSocket::addDefaultCaCertificates ( const QString & path, QSsl::EncodingFormat encoding = QSsl::Pem, QRegExp::PatternSyntax syntax = QRegExp::FixedString )   [static]

Adds all CA certificates in path, using encoding, to the global CA certificate database. path can be a file, or a directory with syntax formatted wildcards. Returns true on success; otherwise returns false.

See also defaultCaCertificates(), addCaCertificates(), and addDefaultCaCertificate().

void QSslSocket::addDefaultCaCertificates ( const QList<QSslCertificate> & certificates )   [static]

This is an overloaded member function, provided for convenience.

Adds certificates to the global CA certificate database.

See also defaultCaCertificates() and addCaCertificates().

QList<QSslCertificate> QSslSocket::caCertificates () const

Returns this socket's CA certificate database.

See also setCaCertificates(), addCaCertificates(), and defaultCaCertificates().

QList<QSslCipher> QSslSocket::ciphers () const

Returns this socket's current cryptographic cipher suite. This list is used during the socket's handshake phase when negotiating ciphers with the peer. The list is returned in descending preferred order (i.e., the first cipher in the list is the most preferred cipher).

By default, the socket will use supportedCiphers(), a predefined set of ciphers that works for most common cases. This predefined set is defined by the current SSL libraries, and may vary from system to system. If you change the ciphers for this socket, you can later call setCiphers() at any time to revert to using the default set.

See also setCiphers(), defaultCiphers(), and supportedCiphers().

void QSslSocket::connectToHostEncrypted ( const QString & hostName, quint16 port, OpenMode mode = ReadWrite )

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().

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't 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().

 QSslSocket socket;
 connect(&socket, SIGNAL(encrypted()), receiver, SLOT(socketEncrypted()));

 socket.connectToHostEncrypted("imap", 993);
 socket->write("1 CAPABILITY\r\n");

Note: 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.

The default for mode is ReadWrite.

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.

See also connectToHost(), startClientEncryption(), waitForConnected(), and waitForEncrypted().

QList<QSslCertificate> QSslSocket::defaultCaCertificates ()   [static]

Returns the global CA certificate database.

See also setDefaultCaCertificates() and caCertificates().

QList<QSslCipher> QSslSocket::defaultCiphers ()   [static]

Returns the default cryptographic cipher suite for all sockets in this application. This list is used during the socket's handshake phase when negotiating ciphers with the peer. The list is returned in descending preferred order (i.e., the first cipher in the list is the most preferred cipher).

By default, the system will use a predefined set of ciphers that works for most common cases. This set is defined by the current SSL libraries, and may vary from system to system.

See also setDefaultCiphers() and supportedCiphers().

void QSslSocket::encrypted ()   [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.

See also QSslSocket::connectToHostEncrypted() and QSslSocket::isEncrypted().

bool QSslSocket::flush ()

This function 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 function 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.

See also write() and waitForBytesWritten().

void QSslSocket::ignoreSslErrors ()   [slot]

This slot tells QSslSocket to ignore errors during QSslSocket's handshake phase and continue connecting. If an error occurs during the handshake phase, but you want to continue with the connection anyway, then you must call this slot, either from a slot connected to sslErrors(), or before the attempt to enter encrypted mode. If you don't call this slot, either in response to errors or before connecting, 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.

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.

See also sslErrors().

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 descrypts 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.

See also mode().

QSslCertificate QSslSocket::localCertificate () const

Returns the socket's local certificate, or an empty certificate if no local certificate has been assigned.

See also setLocalCertificate() and privateKey().

SslMode QSslSocket::mode () const

Returns the current mode for the socket; either UnencryptedMode, where QSslSocket behaves identially 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()

See also SslMode.

void QSslSocket::modeChanged ( QSslSocket::SslMode mode )   [signal]

This signal is emitted when QSslSocket changes from QSslSocket::UnencryptedMode to either QSslSocket::SslClientMode or QSslSocket::SslServerMode. mode is the new mode.

See also QSslSocket::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.

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.

The peer certificate is set during the handshake phase, so it's safe to check this certificate from inside a slot connected to the sslErrors() or encrypted() signals.

If a null certificate is returned, it can mean the SSL handshake failed, or it can mean the host you are connected to doesn't 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.

See also peerCertificateChain().

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. This function is normally only 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's safe to check the certificate chain from inside a slot connected to the encrypted() or the sslErrors() signal.

If an empty list is returned, it can mean the SSL handshake failed, or it can mean the host you are connected to doesn't have a certificate, or it can mean there is no connection.

If you want to get only the peer's immediate certificate, use peerCertificate().

See also peerCertificate().

QSslKey QSslSocket::privateKey () const

Returns this socket's private key.

See also setPrivateKey() and localCertificate().

Protocol QSslSocket::protocol () const

Returns the socket's SSL protocol. By default, SslV3 is used.

ConstantValue
QSslSocket::setProtocol()?

See also setProtocol().

QSslCipher QSslSocket::sessionCipher () const

Returns the socket's cryptographic cipher, or a null cipher if the connection isn't encrypted. The socket's cipher is set during the handshake. It is used to encrypt and decrypt all data transmitted through the socket during the session.

QSslSocket also provides functions for setting the ordered list of ciphers from which the handshake will select the cipher that will be used for encrypting and decrypting data. The list of ciphers must be set before the handshake phase.

See also ciphers(), setCiphers(), setDefaultCiphers(), defaultCiphers(), and supportedCiphers().

void QSslSocket::setCaCertificates ( const QList<QSslCertificate> & certificates )

Sets certificates to be this socket's CA certificate database. Any global CA certificates are ignored.

You can later call setCaCertificates() to restore the global CA certificate defaults.

See also caCertificates() and addDefaultCaCertificate().

void QSslSocket::setCiphers ( const QList<QSslCipher> & ciphers )

Sets the cryptographic cipher suite for this socket to ciphers.

See also ciphers(), setDefaultCiphers(), and supportedCiphers().

void QSslSocket::setCiphers ( const QString & ciphers )

This is an overloaded member function, provided for convenience.

Sets the cryptographic cipher suite for this socket to ciphers, which is a colon-separated list of cipher names. The ciphers are listed in order of preference, starting with the most preferred cipher. For example:

 QSslSocket socket;
 socket.setCiphers("!ADH:RC4+RSA:HIGH:MEDIUM:LOW:EXP:+SSLv2:+EXP");

See also ciphers(), setDefaultCiphers(), and supportedCiphers().

void QSslSocket::setDefaultCaCertificates ( const QList<QSslCertificate> & certificates )   [static]

Sets certificates to be QSslSocket's global CA certificate database.

See also defaultCaCertificates() and addDefaultCaCertificate().

void QSslSocket::setDefaultCiphers ( const QList<QSslCipher> & ciphers )   [static]

Sets the default cryptographic cipher suite for all sockets in this application to ciphers.

See also setCiphers(), defaultCiphers(), and supportedCiphers().

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.

See also localCertificate() and setPrivateKey().

void QSslSocket::setLocalCertificate ( const QString & path, QSsl::EncodingFormat format = QSsl::Pem )

This is an overloaded member function, provided for convenience.

Sets the socket's local certificate to a QSslCertificate constructed from the first certificate found in the file at path, which is expected to be encoded in the specified format.

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.

See also privateKey() and setLocalCertificate().

void QSslSocket::setPrivateKey ( const QString & fileName, QSsl::Algorithm algorithm = QSsl::Rsa, QSsl::EncodingFormat format = QSsl::Pem, const QByteArray & passPhrase = QByteArray() )

This is an overloaded member function, provided for convenience.

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.

See also privateKey() and setLocalCertificate().

void QSslSocket::setProtocol ( Protocol 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.

See also protocol().

bool QSslSocket::setSocketDescriptor ( int socketDescriptor, SocketState state = ConnectedState, OpenMode openMode = ReadWrite )

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.

Note: It is not possible to initialize two sockets with the same native socket descriptor.

See also socketDescriptor().

QList<QSslError> QSslSocket::sslErrors () const

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.

See also connectToHostEncrypted().

void QSslSocket::sslErrors ( const QList<QSslError> & errors )   [signal]

This is an overloaded member function, provided for convenience.

QSslSocket emits this signal during the SSL handshake 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. 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::ignoreErrors() 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 cannot use Qt::QueuedConnection when connecting to this signal, or calling QSslSocket::ignoreErrors() will have no effect.

void QSslSocket::startClientEncryption ()   [slot]

Starts a delayed SSL handshake for a client connection. This function must be called when the socket is in UnencryptedMode, and ConnectedState; otherwise, it 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.

See also connectToHostEncrypted() and startServerEncryption().

void QSslSocket::startServerEncryption ()   [slot]

Starts a delayed SSL handshake for a server connection. This function must be called when the socket is in UnencryptedMode, and ConnectedState; otherwise, it 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 SSL servers is to create a subclass of QTcpServer, and reimplement QTcpServer::incomingConnection(). The provided socket descriptor is then passed to QSslSocket::setSocketDescriptor().

See also connectToHostEncrypted() and startClientEncryption().

QList<QSslCipher> QSslSocket::supportedCiphers ()   [static]

Returns the list of cryptographic ciphers supported by this system.

This list is determined by the current SSL libraries, and may vary from system to system.

See also defaultCiphers(), ciphers(), and setCiphers().

bool QSslSocket::supportsSsl ()   [static]

Returns true if this platform supports SSL; otherwise, returns false.

If the platform doesn't support SSL, the socket will fail in the connection phase.

QList<QSslCertificate> QSslSocket::systemCaCertificates ()   [static]

Returns the default CA certificate database for the system.

See also caCertificates().

bool QSslSocket::waitForConnected ( int msecs = 30000 )

Waits until the socket is connected, up to msecs milliseconds. If the connection has been established, this function returns true; otherwise it returns false.

See also QAbstractSocket::waitForConnected().

bool QSslSocket::waitForDisconnected ( int msecs = 30000 )

Waits until the socket has disconnected, up to msecs milliseconds. If the connection has been disconnected, this function returns true; otherwise it returns false.

See also QAbstractSocket::waitForDisconnected().

bool QSslSocket::waitForEncrypted ( int msecs = 30000 )

Waits until the socket has completed the SSL handshake and has emitted encrypted(), up to msecs milliseconds. If encrypted() has been emitted, this function returns true; otherwise (e.g., the socket is disconnected, or the SSL handshake fails), false is returned.

The following example waits up to one second for the socket to be encrypted:

 socket->connectToHostEncrypted("imap", 993);
 if (socket->waitForEncrypted(1000))
     qDebug("Encrypted!");

If msecs is -1, this function will not time out.

See also startClientEncryption(), startServerEncryption(), encrypted(), and isEncrypted().


Copyright © 2007 Trolltech Trademarks
Qt 4.3.0rc1