Home

QtSSLSocket Class Reference

The QtSSLSocket class provides a socket with SSL encryption support. More...

#include <qtsslsocket.h>

List of all member functions.

Public Members

Public Slots

Signals

Protected Members


Detailed Description

The QtSSLSocket class provides a socket with SSL encryption support.

It provides some extra functionality which is needed for working with SSL, but otherwise there is no difference from QSocket. Example:

    void MyClient::connectToHost(const QString &host, int port)
    {
        // Create a new SSL socket
        socket = new QtSSLSocket();

        // Set the path to the CA certificates
        socket->setPathToCACertDir("/etc/ssl/certs/");

        // Connect the socket's signals to slots in our client
        // implementation.
        connect(socket, SIGNAL(connected()), SLOT(connectedToHost()));
        connect(socket, SIGNAL(readyRead()), SLOT(readData()));
        connect(socket, SIGNAL(connectionClosed()), SLOT(connectionClosed()));
        connect(socket, SIGNAL(error(int)), SLOT(inspectError(int)));
        connect(socket, SIGNAL(certCheckFailed(int, const QString &)),
                        SLOT(checkCertError(int, const QString &)));

        // Initiate a connection.
        socket->connectToHost(host, port);
    }
    

Use connectToHost() when connecting to an SSL server. This will eventually emit the connected() signal if the connection was established, or the error(int) signal if the connection failed.

An alternative approach is to call connectToHost() on a QSocket, and when the socket's connected() signal is emitted, pass the socket to a QtSSLSocket via the constructor. If you use this approach, you must call QtSSLSocket::sslConnect() explicitly to initiate the client side SSL handshake; QtSSLSocket's connected() signal is emitted when the SSL link is established.

In the case of accepting incoming connections, it is common practice to create a subclass of QServerSocket and to reimplement QServerSocket::newConnection(). In newConnection(), a QSSLSocket is created, setSocket() is called, and QtSSLSocket's signals accepted(), readyRead(), connectionClosed(), delayedCloseFinished() and error(int) are connected to slots in the server class. The path to a file containing a PEM encoded certificate is set with setPathToCertificate(). The path to the private key file is set with setPathToPrivateKey(). Finally, to prepare for the client's SSL handshake, sslAccept() is called. When QtSSLSocket emits accepted(), the SSL encrypted link is established. Example:

    void MyServer::newConnection(int socket)
    {
        // Create a new socket and pass it a new QSocket
        socket = new QtSSLSocket(QtSSLSocket::Server);
        socket->setSocket(new QSocket(socket));

        // Set up the certificate and private key.
        socket->setPathToCertificate("/etc/ssl/servercert.pem");
        socket->setPathToPrivateKey("/etc/ssl/serverkey.pem");

        // Connect the socket's signals to slots in our server
        // implementation
        connect(socket, SIGNAL(accepted()), SLOT(acceptedClient()));
        connect(socket, SIGNAL(connectionClosed()), SLOT(connectionClosed()));
        connect(socket, SIGNAL(readyRead()), SLOT(readData()));
        connect(socket, SIGNAL(error(int)), SLOT(error(int)));

        // Initiate SSL handshake.
        socket->sslAccept();
    }
    

Most often clients, but sometimes also servers need a set of certificate authority (CA) certificates to verify the identity of their peer. Use setPathToCACertFile() and setPathToCACertDir() for this. Sometimes, it is useful to restrict the encryption ciphers available to the client or server with setCiphers().

As mentioned, QtSSLSocket emits connected() when the connection has been established and the SSL handshake has been completed. Make sure to connect to error() and certCheckFailed() to catch errors. The readyRead() signal is emitted when there is new incoming data. Call readBlock() to read the new data into a buffer. For server implementations, the accepted() signal is emitted when the SSL handshake has been completed with an incoming client connection. When connectionClosed() is emitted, the other peer has closed the connection. If there is pending data that has not been written to the peer when close() is called, the delayedCloseFinished() signal will be emitted after the data was written and the connection was closed.

If certCheckFailed() is emitted, it is often useful to display details about the failing certificate to the user. peerCertificate() returns information about this certificate. To get the local certificate, call localCertificate().

When building an application that uses QtSSLSocket, you must link your application against the SSL library. Include the bundled .pri file, or add the following line to your .pro file, modified with the path to your installation of OpenSSL:

    unix:LIBS += -L/usr/lib -lssl -lcrypto
    win32:INCLUDEPATH += /openssl/include
    win32:LIBS += -L/openssl/lib ssleay32.lib libeay32.lib
    

The pri file must be edited to set the paths of the SSL files.

Note: QtSSLSocket requires OpenSSL. The OpenSSL toolkit is licensed under an Apache-style licence, which basically means that you are free to get and use it for commercial and non-commercial purposes subject to certain license conditions. The official web site is: http://www.openssl.org/ . Windows binaries are available from: http://www.openssl.org/related/binaries.html .

See also QSocket and QServerSocket.


Member Type Documentation

QtSSLSocket::Error

This enum describes the different error codes emitted through the signal error(). All error codes describe a state in which it is impossible to continue communication on the existing link.

Calling errorString() immediately after the error() signal is emitted will give more information about the error condition.

QtSSLSocket::Mode

This enum describes the two modes QtSSLSocket can run in.

QtSSLSocket::State

This enum describes the different states the SSL socket can be in:

QtSSLSocket::VerifyResult

This enum describes the results of the peer certificate verification process. If the certificate check fails for some reason, the certCheckFailed() signal is emitted and one of the following results will be passed:

errorString() will give a more detailed description of the actual error that occurred.


Member Function Documentation

QtSSLSocket::QtSSLSocket ( Mode mode = Client, QSocket * sock = 0, QObject * parent = 0, const char * name = 0 )

Constructs an SSL socket and initializes the SSL library. mode decides in which mode the socket should run: Client or Server. If a QSocket sock is passed, this will be used to establish the SSL link. If sock is 0, a QSocket will be created automatically.

The parent and name arguments are passed to QObject's constructor.

QtSSLSocket::~QtSSLSocket ()

Destructs the SSL socket and closes the socket. The associated socket is deleted if it was created automatically.

void QtSSLSocket::accepted () [signal]

When in server mode, this signal is emitted when the SSL link is estalished. It is then safe to call readBlock() and writeBlock().

Example: sslserver.cpp.

int QtSSLSocket::bytesAvailable () const

Returns the number of bytes available in the read buffer.

Warning: QSocket::bytesAvailable() is not virtual. In order to get a reliable return value from this function, a QtSSLSocket pointer or reference must be used.

bool QtSSLSocket::canReadLine () const

Returns true if it's possible to read an entire line of text from this socket at this time; otherwise returns false.

Notice that QSocket::canReadLine() is non-virtual, so this function does not work polymorphically (i.e., calling this function on a QSocket* pointer will call QSocket::canReadLine() and not QtSSLSocket::canReadLine()). When operating on a QSocket* pointer, you must call readBlock() or readAll() instead.

See also readLine().

void QtSSLSocket::certCheckFailed ( int code, const QString & description ) [signal]

This signal is emitted if there was an error when verifying the identity of the peer. There can be many reasons for this, among others that the peer's SSL certificate has expired, that the peer uses a self-signed certificate and that there are problems with the certificate authorities.

code is of the type VerifyResult, and can be checked to determine the reason for the failure. description contains a human readable description of the cause of the error.

Example: sslclient.cpp.

QString QtSSLSocket::ciphers () const

Returns a list of ciphers available to the underlying SSL session.

void QtSSLSocket::close () [slot]

Closes the socket. The read buffer is cleared.

Example: sslserver.cpp.

void QtSSLSocket::connectToHost ( const QString & host, Q_UINT16 port )

Initiates a connection to the host whose name or address is host, on port port. The SSL handshake is performed automatically.

QtSSLSocket will emit connected() or error(), depending on the result of the connection attempt.

If during the SSL handshake there was an error with verifying the identity of the server host, certCheckFailed() is emitted.

int QtSSLSocket::error () const [protected]

Gives the most recent error type.

Examples: sslclient.cpp and sslserver.cpp.

QString QtSSLSocket::errorString () const

Returns more information about the most recent error.

Example: sslserver.cpp.

QString QtSSLSocket::localCertificate () const

Returns the local certificate if available; otherwise QString::null is returned. The local certificate is always available when in server mode. It is available in client mode only if the client has set up a local certificate.

The certificate is encoded as a sequence of key-value pairs delimited by the '/' character. The keys and values are delimited with '='.

See also peerCertificate().

QString QtSSLSocket::pathToCACertDir () const

Returns the path to a directory containing CA certificate files.

See also setPathToCACertDir() and setPathToCACertFile().

QString QtSSLSocket::pathToCACertFile () const

Returns the path to the file containing certificates of this host's certificate authorities.

See also setPathToCACertFile().

QString QtSSLSocket::pathToCertificate () const

For servers, returns the path of the PEM encoded certificate file.

QString QtSSLSocket::pathToPrivateKey () const

For servers, returns the path of the PEM encoded private key file.

QString QtSSLSocket::peerCertificate () const

Returns the peer certificate if available; otherwise QString::null is returned. The peer certificate is available to the client when connecting to a server, but only optionally available to a server accepting connections from a client. This function is usually called from a slot invoked by the certCheckFailed() signal.

The certificate is encoded as a sequence of key-value pairs delimited by the '/' character. The keys and values are delimited with '='.

See also localCertificate().

Example: sslclient.cpp.

QByteArray QtSSLSocket::readAll ()

This convenience function returns all of the remaining data in the read buffer.

Example: sslserver.cpp.

Q_LONG QtSSLSocket::readBlock ( char * data, Q_ULONG maxlen )

Reads at most maxlen bytes of data from the read buffer, decrypts it and places the unencrypted data in the buffer data.

Returns the number of unencrypted bytes read, or 0 if there was no more data to read. This function is usually called after the readyRead() signal is emitted.

See also readyRead() and bytesAvailable().

QString QtSSLSocket::readLine ()

Returns a line of text including a terminating newline character (\n). Returns "" if canReadLine() returns false.

See also canReadLine().

void QtSSLSocket::setCiphers ( const QString & ciph )

For both clients and servers, restricts the ciphers available to the underlying SSL session to ciph.

Read more about the format of the input string ciph in the OpenSSL cipher documentation: http://www.openssl.org/docs/apps/ciphers.html

void QtSSLSocket::setPathToCACertDir ( const QString & path )

This function basically does the same as setPathToCACertFile(), but instead of passing the path to one CA certificate file, you pass the path path to a directory that can contain several CA certificate files.

This is useful if the server has one or more files with the root CA certificates that came with the operating system, in addition to several self-created unofficial CA certificates.

The certificates in the CA certificate file are used before those in the CA certificate directory.

See also setPathToCACertFile() and pathToCACertDir().

Examples: sslclient.cpp and sslserver.cpp.

void QtSSLSocket::setPathToCACertFile ( const QString & path )

Sets the path path to a file containing one or more CA certificates. The certificates in this file are used to verify the authenticity of the certificate presented by server that you connect to.

Use setPAthToCACertDir() if there is need to use more than one CA certificate.

See also pathToCACertFile() and setPathToCACertDir().

void QtSSLSocket::setPathToCertificate ( const QString & path )

Sets the path path to a file containing the server's PEM encoded SSL certificate. If this file also contains the server's private key, you must also call setPathToPrivateKey() with the same path. The order in which these functions are called is not significant, but they must be called before sslAccept().

Calling this function is necessary when running QtSSLSocket in Server mode. Clients do not call this function.

The file, which must be readable by the server application, is used internally to negotiate an SSL connection. For more information on how to generate such files see the official OpenSSL FAQ at: http://www.openssl.org/support/faq.html.

See also pathToCertificate() and setPathToPrivateKey().

Example: sslserver.cpp.

void QtSSLSocket::setPathToPrivateKey ( const QString & path )

Sets the path path to a file containing the server's PEM encoded SSL private key. If this file also contains the server's certificate, you must also call setCertificate(). The order in which these function are called is not significant, but they must be called before sslAccept().

Calling this function is necessary when running QtSSLSocket in Server mode. Clients do not call this function.

The file, which must be readable by the server application, is used internally to negotiate an SSL connection. For more information on how to generate such files see the official OpenSSL FAQ at: http://www.openssl.org/support/faq.html.

See also pathToPrivateKey() and setPathToCertificate().

Example: sslserver.cpp.

void QtSSLSocket::setSocket ( QSocket * sock )

Makes QtSSLSocket use sock internally.

QSocket * QtSSLSocket::socket () const

Returns a pointer to the internal QSocket object, or 0 if there is none.

Example: sslserver.cpp.

bool QtSSLSocket::sslAccept () [slot]

Initiates an SSL server side handshake.

Example: sslserver.cpp.

bool QtSSLSocket::sslConnect () [slot]

Initiates an SSL client handshake.

State QtSSLSocket::state () const

Returns the current state of the socket connection.

See also QtSSLSocket::State.

Q_LONG QtSSLSocket::writeBlock ( const char * data, Q_ULONG len )

Encrypts and sends all len bytes from the buffer data to the peer.

The data is dispatched immediately, but it may take some time before the data is received by the remote peer.

Returns the number of bytes written, or -1 if an error occurred.

Example: sslserver.cpp.


This file is part of the Qt Solutions. Copyright © 2003-2006 Trolltech. All Rights Reserved.

Copyright © 2003-2006 TrolltechTrademarks
Qt Solutions