Qt 4.8
Public Types | Public Slots | Signals | Public Functions | Static Public Functions | Protected Slots | Protected Functions | Friends | List of all members
QSslSocket Class Reference

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

#include <qsslsocket.h>

Inheritance diagram for QSslSocket:
QTcpSocket QAbstractSocket QIODevice QObject

Public Types

enum  PeerVerifyMode { VerifyNone, QueryPeer, VerifyPeer, AutoVerifyPeer }
 Describes the peer verification modes for QSslSocket. More...
 
enum  SslMode { UnencryptedMode, SslClientMode, SslServerMode }
 Describes the connection modes available for QSslSocket. More...
 
- Public Types inherited from QAbstractSocket
enum  NetworkLayerProtocol { IPv4Protocol, IPv6Protocol, UnknownNetworkLayerProtocol = -1 }
 This enum describes the network layer protocol values used in Qt. More...
 
enum  SocketError {
  ConnectionRefusedError, RemoteHostClosedError, HostNotFoundError, SocketAccessError,
  SocketResourceError, SocketTimeoutError, DatagramTooLargeError, NetworkError,
  AddressInUseError, SocketAddressNotAvailableError, UnsupportedSocketOperationError, UnfinishedSocketOperationError,
  ProxyAuthenticationRequiredError, SslHandshakeFailedError, ProxyConnectionRefusedError, ProxyConnectionClosedError,
  ProxyConnectionTimeoutError, ProxyNotFoundError, ProxyProtocolError, UnknownSocketError = -1
}
 This enum describes the socket errors that can occur. More...
 
enum  SocketOption { LowDelayOption, KeepAliveOption, MulticastTtlOption, MulticastLoopbackOption }
 This enum represents the options that can be set on a socket. More...
 
enum  SocketState {
  UnconnectedState, HostLookupState, ConnectingState, ConnectedState,
  BoundState, ListeningState, ClosingState
}
 This enum describes the different states in which a socket can be. More...
 
enum  SocketType { TcpSocket, UdpSocket, UnknownSocketType = -1 }
 This enum describes the transport layer protocol. More...
 
- Public Types inherited from QIODevice
enum  OpenModeFlag {
  NotOpen = 0x0000, ReadOnly = 0x0001, WriteOnly = 0x0002, ReadWrite = ReadOnly | WriteOnly,
  Append = 0x0004, Truncate = 0x0008, Text = 0x0010, Unbuffered = 0x0020
}
 This enum is used with open() to describe the mode in which a device is opened. More...
 

Public Slots

void ignoreSslErrors ()
 This slot tells QSslSocket to ignore errors during QSslSocket's handshake phase and continue connecting. More...
 
void startClientEncryption ()
 Starts a delayed SSL handshake for a client connection. More...
 
void startServerEncryption ()
 Starts a delayed SSL handshake for a server connection. More...
 
- Public Slots inherited from QObject
void deleteLater ()
 Schedules this object for deletion. More...
 

Signals

void encrypted ()
 This signal is emitted when QSslSocket enters encrypted mode. More...
 
void encryptedBytesWritten (qint64 totalBytes)
 This signal is emitted when QSslSocket writes its encrypted data to the network. More...
 
void modeChanged (QSslSocket::SslMode newMode)
 This signal is emitted when QSslSocket changes from QSslSocket::UnencryptedMode to either QSslSocket::SslClientMode or QSslSocket::SslServerMode . More...
 
void peerVerifyError (const QSslError &error)
 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. More...
 
void sslErrors (const QList< QSslError > &errors)
 QSslSocket emits this signal after the SSL handshake to indicate that one or more errors have occurred while establishing the identity of the peer. More...
 
- Signals inherited from QAbstractSocket
void connected ()
 This signal is emitted after connectToHost() has been called and a connection has been successfully established. More...
 
void disconnected ()
 This signal is emitted when the socket has been disconnected. More...
 
void error (QAbstractSocket::SocketError)
 This signal is emitted after an error occurred. More...
 
void hostFound ()
 This signal is emitted after connectToHost() has been called and the host lookup has succeeded. More...
 
void proxyAuthenticationRequired (const QNetworkProxy &proxy, QAuthenticator *authenticator)
 
void stateChanged (QAbstractSocket::SocketState)
 This signal is emitted whenever QAbstractSocket's state changes. More...
 
- Signals inherited from QIODevice
void aboutToClose ()
 This signal is emitted when the device is about to close. More...
 
void bytesWritten (qint64 bytes)
 This signal is emitted every time a payload of data has been written to the device. More...
 
void readChannelFinished ()
 This signal is emitted when the input (reading) stream is closed in this device. More...
 
void readyRead ()
 This signal is emitted once every time new data is available for reading from the device. More...
 
- Signals inherited from QObject
void destroyed (QObject *=0)
 This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More...
 

Public Functions

void abort ()
 Aborts the current connection and resets the socket. More...
 
void addCaCertificate (const QSslCertificate &certificate)
 Adds the certificate to this socket's CA certificate database. More...
 
bool addCaCertificates (const QString &path, QSsl::EncodingFormat format=QSsl::Pem, QRegExp::PatternSyntax syntax=QRegExp::FixedString)
 Searches all files in the path for certificates encoded in the specified format and adds them to this socket's CA certificate database. More...
 
void addCaCertificates (const QList< QSslCertificate > &certificates)
 Adds the certificates to this socket's CA certificate database. More...
 
bool atEnd () const
 Reimplemented Function More...
 
qint64 bytesAvailable () const
 Returns the number of decrypted bytes that are immediately available for reading. More...
 
qint64 bytesToWrite () const
 Returns the number of unencrypted bytes that are waiting to be encrypted and written to the network. More...
 
QList< QSslCertificatecaCertificates () const
 Returns this socket's CA certificate database. More...
 
bool canReadLine () const
 Returns true if you can read one while line (terminated by a single ASCII '
' character) of decrypted characters; otherwise, false is returned. More...
 
QList< QSslCipherciphers () const
 Returns this socket's current cryptographic cipher suite. More...
 
void close ()
 Reimplemented Function More...
 
void connectToHostEncrypted (const QString &hostName, quint16 port, OpenMode mode=ReadWrite)
 Starts an encrypted connection to the device hostName on port, using mode as the OpenMode . More...
 
void connectToHostEncrypted (const QString &hostName, quint16 port, const QString &sslPeerName, OpenMode mode=ReadWrite)
 In addition to the original behaviour 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). More...
 
qint64 encryptedBytesAvailable () const
 Returns the number of encrypted bytes that are awaiting decryption. More...
 
qint64 encryptedBytesToWrite () const
 Returns the number of encrypted bytes that are waiting to be written to the network. More...
 
bool flush ()
 This function writes as much as possible from the internal write buffer to the underlying network socket, without blocking. More...
 
void ignoreSslErrors (const QList< QSslError > &errors)
 This method tells QSslSocket to ignore only the errors given in errors. More...
 
bool isEncrypted () const
 Returns true if the socket is encrypted; otherwise, false is returned. More...
 
QSslCertificate localCertificate () const
 Returns the socket's local QSslCertificate {certificate}, or an empty certificate if no local certificate has been assigned. More...
 
SslMode 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. More...
 
QSslCertificate 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. More...
 
QList< QSslCertificatepeerCertificateChain () const
 Returns the peer's chain of digital certificates, or an empty list of certificates. More...
 
int 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. More...
 
QSslSocket::PeerVerifyMode peerVerifyMode () const
 Returns the socket's verify mode. More...
 
QString peerVerifyName () const
 Returns the different hostname for the certificate validation, as set by setPeerVerifyName or by connectToHostEncrypted. More...
 
QSslKey privateKey () const
 Returns this socket's private key. More...
 
QSsl::SslProtocol protocol () const
 Returns the socket's SSL protocol. More...
 
 QSslSocket (QObject *parent=0)
 Constructs a QSslSocket object. More...
 
QSslCipher sessionCipher () const
 Returns the socket's cryptographic QSslCipher {cipher}, or a null cipher if the connection isn't encrypted. More...
 
void setCaCertificates (const QList< QSslCertificate > &certificates)
 Sets this socket's CA certificate database to be certificates. More...
 
void setCiphers (const QList< QSslCipher > &ciphers)
 Sets the cryptographic cipher suite for this socket to ciphers, which must contain a subset of the ciphers in the list returned by supportedCiphers(). More...
 
void setCiphers (const QString &ciphers)
 Sets the cryptographic cipher suite for this socket to ciphers, which is a colon-separated list of cipher suite names. More...
 
void setLocalCertificate (const QSslCertificate &certificate)
 Sets the socket's local certificate to certificate. More...
 
void setLocalCertificate (const QString &fileName, QSsl::EncodingFormat format=QSsl::Pem)
 Sets the socket's local QSslCertificate {certificate} to the first one found in file path, which is parsed according to the specified format. More...
 
void 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. More...
 
void setPeerVerifyMode (QSslSocket::PeerVerifyMode mode)
 Sets the socket's verify mode to mode. More...
 
void 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. More...
 
void setPrivateKey (const QSslKey &key)
 Sets the socket's private QSslKey {key} to key. More...
 
void 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 QSslKey {SSL key}. More...
 
void setProtocol (QSsl::SslProtocol protocol)
 Sets the socket's SSL protocol to protocol. More...
 
void setReadBufferSize (qint64 size)
 Sets the size of QSslSocket's internal read buffer to be size bytes. More...
 
bool setSocketDescriptor (int socketDescriptor, SocketState state=ConnectedState, OpenMode openMode=ReadWrite)
 Initializes QSslSocket with the native socket descriptor socketDescriptor. More...
 
void setSocketOption (QAbstractSocket::SocketOption option, const QVariant &value)
 Sets the given option to the value described by value. More...
 
void setSslConfiguration (const QSslConfiguration &config)
 Sets the socket's SSL configuration to be the contents of configuration. More...
 
QVariant socketOption (QAbstractSocket::SocketOption option)
 Returns the value of the option option. More...
 
QSslConfiguration sslConfiguration () const
 Returns the socket's SSL configuration state. More...
 
QList< QSslErrorsslErrors () const
 Returns a list of the last SSL errors that occurred. More...
 
bool waitForBytesWritten (int msecs=30000)
 Reimplemented Function More...
 
bool waitForConnected (int msecs=30000)
 Waits until the socket is connected, or msecs milliseconds, whichever happens first. More...
 
bool waitForDisconnected (int msecs=30000)
 Waits until the socket has disconnected or msecs milliseconds, whichever comes first. More...
 
bool waitForEncrypted (int msecs=30000)
 Waits until the socket has completed the SSL handshake and has emitted encrypted(), or msecs milliseconds, whichever comes first. More...
 
bool waitForReadyRead (int msecs=30000)
 Reimplemented Function More...
 
 ~QSslSocket ()
 Destroys the QSslSocket. More...
 
- Public Functions inherited from QTcpSocket
 QTcpSocket (QObject *parent=0)
 Creates a QTcpSocket object in state UnconnectedState. More...
 
virtual ~QTcpSocket ()
 Destroys the socket, closing the connection if necessary. More...
 
- Public Functions inherited from QAbstractSocket
void abort ()
 Aborts the current connection and resets the socket. More...
 
void connectToHost (const QString &hostName, quint16 port, OpenMode mode=ReadWrite)
 Attempts to make a connection to hostName on the given port. More...
 
void connectToHost (const QHostAddress &address, quint16 port, OpenMode mode=ReadWrite)
 Attempts to make a connection to address on port port. More...
 
void disconnectFromHost ()
 Attempts to close the socket. More...
 
SocketError error () const
 Returns the type of error that last occurred. More...
 
bool flush ()
 This function writes as much as possible from the internal write buffer to the underlying network socket, without blocking. More...
 
bool isSequential () const
 Reimplemented Function More...
 
bool isValid () const
 Returns true if the socket is valid and ready for use; otherwise returns false. More...
 
QHostAddress localAddress () const
 Returns the host address of the local socket if available; otherwise returns QHostAddress::Null. More...
 
quint16 localPort () const
 Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0. More...
 
QHostAddress peerAddress () const
 Returns the address of the connected peer if the socket is in ConnectedState; otherwise returns QHostAddress::Null. More...
 
QString peerName () const
 Returns the name of the peer as specified by connectToHost(), or an empty QString if connectToHost() has not been called. More...
 
quint16 peerPort () const
 Returns the port of the connected peer if the socket is in ConnectedState; otherwise returns 0. More...
 
QNetworkProxy proxy () const
 Returns the network proxy for this socket. More...
 
 QAbstractSocket (SocketType socketType, QObject *parent)
 Creates a new abstract socket of type socketType. More...
 
qint64 readBufferSize () const
 Returns the size of the internal read buffer. More...
 
void setProxy (const QNetworkProxy &networkProxy)
 Sets the explicit network proxy for this socket to networkProxy. More...
 
void setReadBufferSize (qint64 size)
 Sets the size of QAbstractSocket's internal read buffer to be size bytes. More...
 
bool setSocketDescriptor (int socketDescriptor, SocketState state=ConnectedState, OpenMode openMode=ReadWrite)
 Initializes QAbstractSocket with the native socket descriptor socketDescriptor. More...
 
void setSocketOption (QAbstractSocket::SocketOption option, const QVariant &value)
 Sets the given option to the value described by value. More...
 
int socketDescriptor () const
 Returns the native socket descriptor of the QAbstractSocket object if this is available; otherwise returns -1. More...
 
QVariant socketOption (QAbstractSocket::SocketOption option)
 Returns the value of the option option. More...
 
SocketType socketType () const
 Returns the socket type (TCP, UDP, or other). More...
 
SocketState state () const
 Returns the state of the socket. More...
 
bool waitForConnected (int msecs=30000)
 Waits until the socket is connected, up to msecs milliseconds. More...
 
bool waitForDisconnected (int msecs=30000)
 Waits until the socket has disconnected, up to msecs milliseconds. More...
 
virtual ~QAbstractSocket ()
 Destroys the socket. More...
 
- Public Functions inherited from QIODevice
QString errorString () const
 Returns a human-readable description of the last device error that occurred. More...
 
bool getChar (char *c)
 Reads one character from the device and stores it in c. More...
 
bool isOpen () const
 Returns true if the device is open; otherwise returns false. More...
 
bool isReadable () const
 Returns true if data can be read from the device; otherwise returns false. More...
 
bool isTextModeEnabled () const
 Returns true if the Text flag is enabled; otherwise returns false. More...
 
bool isWritable () const
 Returns true if data can be written to the device; otherwise returns false. More...
 
virtual bool open (OpenMode mode)
 Opens the device and sets its OpenMode to mode. More...
 
OpenMode openMode () const
 Returns the mode in which the device has been opened; i.e. More...
 
qint64 peek (char *data, qint64 maxlen)
 Reads at most maxSize bytes from the device into data, without side effects (i. More...
 
QByteArray peek (qint64 maxlen)
 Peeks at most maxSize bytes from the device, returning the data peeked as a QByteArray. More...
 
virtual qint64 pos () const
 For random-access devices, this function returns the position that data is written to or read from. More...
 
bool putChar (char c)
 Writes the character c to the device. More...
 
 QIODevice ()
 Constructs a QIODevice object. More...
 
 QIODevice (QObject *parent)
 Constructs a QIODevice object with the given parent. More...
 
qint64 read (char *data, qint64 maxlen)
 Reads at most maxSize bytes from the device into data, and returns the number of bytes read. More...
 
QByteArray read (qint64 maxlen)
 Reads at most maxSize bytes from the device, and returns the data read as a QByteArray. More...
 
QByteArray readAll ()
 Reads all available data from the device, and returns it as a QByteArray. More...
 
qint64 readLine (char *data, qint64 maxlen)
 This function reads a line of ASCII characters from the device, up to a maximum of maxSize - 1 bytes, stores the characters in data, and returns the number of bytes read. More...
 
QByteArray readLine (qint64 maxlen=0)
 Reads a line from the device, but no more than maxSize characters, and returns the result as a QByteArray. More...
 
virtual bool reset ()
 Seeks to the start of input for random-access devices. More...
 
virtual bool seek (qint64 pos)
 For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred. More...
 
void setTextModeEnabled (bool enabled)
 If enabled is true, this function sets the Text flag on the device; otherwise the Text flag is removed. More...
 
virtual qint64 size () const
 For open random-access devices, this function returns the size of the device. More...
 
void ungetChar (char c)
 Puts the character c back into the device, and decrements the current position unless the position is 0. More...
 
qint64 write (const char *data, qint64 len)
 Writes at most maxSize bytes of data from data to the device. More...
 
qint64 write (const char *data)
 Writes data from a zero-terminated string of 8-bit characters to the device. More...
 
qint64 write (const QByteArray &data)
 Writes the content of byteArray to the device. More...
 
virtual ~QIODevice ()
 The destructor is virtual, and QIODevice is an abstract base class. More...
 
- Public Functions inherited from QObject
bool blockSignals (bool b)
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More...
 
const QObjectListchildren () const
 Returns a list of child objects. More...
 
bool connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool disconnect (const QObject *receiver, const char *member=0)
 
void dumpObjectInfo ()
 Dumps information about signal connections, etc. More...
 
void dumpObjectTree ()
 Dumps a tree of children to the debug output. More...
 
QList< QByteArraydynamicPropertyNames () const
 Returns the names of all properties that were dynamically added to the object using setProperty(). More...
 
virtual bool event (QEvent *)
 This virtual function receives events to an object and should return true if the event e was recognized and processed. More...
 
virtual bool eventFilter (QObject *, QEvent *)
 Filters events if this object has been installed as an event filter for the watched object. More...
 
template<typename T >
findChild (const QString &aName=QString()) const
 Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More...
 
template<typename T >
QList< T > findChildren (const QString &aName=QString()) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More...
 
template<typename T >
QList< T > findChildren (const QRegExp &re) const
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More...
 
void installEventFilter (QObject *)
 Installs an event filter filterObj on this object. More...
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false. More...
 
void killTimer (int id)
 Kills the timer with timer identifier, id. More...
 
virtual const QMetaObjectmetaObject () const
 Returns a pointer to the meta-object of this object. More...
 
void moveToThread (QThread *thread)
 Changes the thread affinity for this object and its children. More...
 
QString objectName () const
 
QObjectparent () const
 Returns a pointer to the parent object. More...
 
QVariant property (const char *name) const
 Returns the value of the object's name property. More...
 
Q_INVOKABLE QObject (QObject *parent=0)
 Constructs an object with parent object parent. More...
 
void removeEventFilter (QObject *)
 Removes an event filter object obj from this object. More...
 
void setObjectName (const QString &name)
 
void setParent (QObject *)
 Makes the object a child of parent. More...
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value. More...
 
void setUserData (uint id, QObjectUserData *data)
 
bool signalsBlocked () const
 Returns true if signals are blocked; otherwise returns false. More...
 
int startTimer (int interval)
 Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (uint id) const
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects. More...
 

Static Public Functions

static void addDefaultCaCertificate (const QSslCertificate &certificate)
 Adds certificate to the default CA certificate database. More...
 
static bool addDefaultCaCertificates (const QString &path, QSsl::EncodingFormat format=QSsl::Pem, QRegExp::PatternSyntax syntax=QRegExp::FixedString)
 Searches all files in the path for certificates with the specified encoding and adds them to the default CA certificate database. More...
 
static void addDefaultCaCertificates (const QList< QSslCertificate > &certificates)
 Adds certificates to the default CA certificate database. More...
 
static QList< QSslCertificatedefaultCaCertificates ()
 Returns the current default CA certificate database. More...
 
static QList< QSslCipherdefaultCiphers ()
 Returns the default cryptographic cipher suite for all sockets in this application. More...
 
static void setDefaultCaCertificates (const QList< QSslCertificate > &certificates)
 Sets the default CA certificate database to certificates. More...
 
static void setDefaultCiphers (const QList< QSslCipher > &ciphers)
 Sets the default cryptographic cipher suite for all sockets in this application to ciphers, which must contain a subset of the ciphers in the list returned by supportedCiphers(). More...
 
static QList< QSslCiphersupportedCiphers ()
 Returns the list of cryptographic ciphers supported by this system. More...
 
static bool supportsSsl ()
 Returns true if this platform supports SSL; otherwise, returns false. More...
 
static QList< QSslCertificatesystemCaCertificates ()
 This function provides the CA certificate database provided by the operating system. More...
 
- Static Public Functions inherited from QObject
static bool connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More...
 
static bool connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 Disconnects signal in object sender from method in object receiver. More...
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint registerUserData ()
 
static QString tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 

Protected Slots

void connectToHostImplementation (const QString &hostName, quint16 port, OpenMode openMode)
 
void disconnectFromHostImplementation ()
 
- Protected Slots inherited from QAbstractSocket
void connectToHostImplementation (const QString &hostName, quint16 port, OpenMode mode=ReadWrite)
 Contains the implementation of connectToHost(). More...
 
void disconnectFromHostImplementation ()
 Contains the implementation of disconnectFromHost(). More...
 

Protected Functions

qint64 readData (char *data, qint64 maxlen)
 Reimplemented Function More...
 
qint64 writeData (const char *data, qint64 len)
 Reimplemented Function More...
 
- Protected Functions inherited from QTcpSocket
 QTcpSocket (QTcpSocketPrivate &dd, QObject *parent=0)
 
- Protected Functions inherited from QAbstractSocket
 QAbstractSocket (SocketType socketType, QAbstractSocketPrivate &dd, QObject *parent=0)
 Constructs a new abstract socket of type socketType. More...
 
qint64 readLineData (char *data, qint64 maxlen)
 Reimplemented Function More...
 
void setLocalAddress (const QHostAddress &address)
 Sets the address on the local side of a connection to address. More...
 
void setLocalPort (quint16 port)
 Sets the port on the local side of a connection to port. More...
 
void setPeerAddress (const QHostAddress &address)
 Sets the address of the remote side of the connection to address. More...
 
void setPeerName (const QString &name)
 Sets the host name of the remote peer to name. More...
 
void setPeerPort (quint16 port)
 Sets the port of the remote side of the connection to port. More...
 
void setSocketError (SocketError socketError)
 Sets the type of error that last occurred to socketError. More...
 
void setSocketState (SocketState state)
 Sets the state of the socket to state. More...
 
- Protected Functions inherited from QIODevice
 QIODevice (QIODevicePrivate &dd, QObject *parent=0)
 
void setErrorString (const QString &errorString)
 Sets the human readable description of the last device error that occurred to str. More...
 
void setOpenMode (OpenMode openMode)
 Sets the OpenMode of the device to openMode. More...
 
- Protected Functions inherited from QObject
virtual void childEvent (QChildEvent *)
 This event handler can be reimplemented in a subclass to receive child events. More...
 
virtual void connectNotify (const char *signal)
 This virtual function is called when something has been connected to signal in this object. More...
 
virtual void customEvent (QEvent *)
 This event handler can be reimplemented in a subclass to receive custom events. More...
 
virtual void disconnectNotify (const char *signal)
 This virtual function is called when something has been disconnected from signal in this object. More...
 
 QObject (QObjectPrivate &dd, QObject *parent=0)
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal. More...
 
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More...
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *)
 This event handler can be reimplemented in a subclass to receive timer events for the object. More...
 

Friends

class QSslSocketBackendPrivate
 

Additional Inherited Members

- Static Public Variables inherited from QObject
static const QMetaObject staticMetaObject
 This variable stores the meta-object for the class. More...
 
- Protected Variables inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject staticQtMetaObject
 

Detailed Description

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

Since
4.3
Note
This class or function is reentrant.
Attention
Module: QtNetwork

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 TLSv1, 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 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.

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 existing 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 the sslErrors() signal. In this case, if no action is taken to ignore the error(s), the connection is dropped. To continue, despite the occurrence of an error, you can 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, 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 encryptedBytesWritten() 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 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.

The following features can also be customized:

Note
If available, root certificates on Unix (excluding Mac OS X) will be loaded on demand from the standard certificate directories. If you do not want to load root certificates on demand, you need to call either the static function setDefaultCaCertificates() before the first SSL handshake is made in your application, (e.g. via "QSslSocket::setDefaultCaCertificates(QSslSocket::systemCaCertificates());"), or call setCaCertificates() on your QSslSocket instance prior to the SSL handshake.

For more information about ciphers and certificates, refer to QSslCipher and QSslCertificate.

This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (qmake-variable-reference.html#target-capability{TARGET.CAPABILITY} qmake variable.

See also
QSslCertificate, QSslCipher, QSslError

Definition at line 67 of file qsslsocket.h.

Enumerations

◆ PeerVerifyMode

Describes the peer verification modes for QSslSocket.

Since
4.4

The default mode is AutoVerifyPeer, which selects an appropriate mode depending on the socket's QSocket::SslMode.

  • VerifyNone 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.
  • QueryPeer 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.
  • VerifyPeer 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.
  • AutoVerifyPeer QSslSocket will automatically use QueryPeer for server sockets and VerifyPeer for client sockets.
See also
QSslSocket::peerVerifyMode()
Enumerator
VerifyNone 
QueryPeer 
VerifyPeer 
AutoVerifyPeer 

Definition at line 77 of file qsslsocket.h.

◆ SslMode

Describes the connection modes available for QSslSocket.

  • UnencryptedMode The socket is unencrypted. Its behavior is identical to QTcpSocket.
  • SslClientMode The socket is a client-side SSL socket. It is either alreayd encrypted, or it is in the SSL handshake phase (see QSslSocket::isEncrypted()).
  • SslServerMode The socket is a server-side SSL socket. It is either already encrypted, or it is in the SSL handshake phase (see QSslSocket::isEncrypted()).
Enumerator
UnencryptedMode 
SslClientMode 
SslServerMode 

Definition at line 71 of file qsslsocket.h.

Constructors and Destructors

◆ QSslSocket()

QSslSocket::QSslSocket ( QObject parent = 0)

Constructs a QSslSocket object.

parent is passed to QObject's constructor. The new socket's QSslCipher {cipher} suite is set to the one returned by the static method defaultCiphers().

Definition at line 350 of file qsslsocket.cpp.

351  : QTcpSocket(*new QSslSocketBackendPrivate, parent)
352 {
353  Q_D(QSslSocket);
354 #ifdef QSSLSOCKET_DEBUG
355  qDebug() << "QSslSocket::QSslSocket(" << parent << "), this =" << (void *)this;
356 #endif
357  d->q_ptr = this;
358  d->init();
359 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
QTcpSocket(QObject *parent=0)
Creates a QTcpSocket object in state UnconnectedState.
Definition: qtcpsocket.cpp:96
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define d

◆ ~QSslSocket()

QSslSocket::~QSslSocket ( )

Destroys the QSslSocket.

Definition at line 364 of file qsslsocket.cpp.

365 {
366  Q_D(QSslSocket);
367 #ifdef QSSLSOCKET_DEBUG
368  qDebug() << "QSslSocket::~QSslSocket(), this =" << (void *)this;
369 #endif
370  delete d->plainSocket;
371  d->plainSocket = 0;
372 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define d

Functions

◆ abort()

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(), close()

Definition at line 893 of file qsslsocket.cpp.

894 {
895  Q_D(QSslSocket);
896 #ifdef QSSLSOCKET_DEBUG
897  qDebug() << "QSslSocket::abort()";
898 #endif
899  if (d->plainSocket)
900  d->plainSocket->abort();
901  close();
902 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define d
void close()
Reimplemented Function
Definition: qsslsocket.cpp:811

◆ addCaCertificate()

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

See also
caCertificates(), setCaCertificates()

Definition at line 1316 of file qsslsocket.cpp.

1317 {
1318  Q_D(QSslSocket);
1319  d->configuration.caCertificates += certificate;
1320 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ addCaCertificates() [1/2]

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

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

See also
addCaCertificate(), QSslCertificate::fromPath()

Definition at line 1295 of file qsslsocket.cpp.

1297 {
1298  Q_D(QSslSocket);
1300  if (certs.isEmpty())
1301  return false;
1302 
1303  d->configuration.caCertificates += certs;
1304  return true;
1305 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152
#define d
static QList< QSslCertificate > fromPath(const QString &path, QSsl::EncodingFormat format=QSsl::Pem, QRegExp::PatternSyntax syntax=QRegExp::FixedString)
Searches all files in the path for certificates encoded in the specified format and returns them in a...

◆ addCaCertificates() [2/2]

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

See also
caCertificates(), addDefaultCaCertificate()

Definition at line 1331 of file qsslsocket.cpp.

1332 {
1333  Q_D(QSslSocket);
1334  d->configuration.caCertificates += certificates;
1335 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ addDefaultCaCertificate()

void QSslSocket::addDefaultCaCertificate ( const QSslCertificate certificate)
static

Adds certificate to the default CA certificate database.

Each SSL socket's CA certificate database is initialized to the default CA certificate database.

See also
defaultCaCertificates(), addCaCertificates()

Definition at line 1399 of file qsslsocket.cpp.

1400 {
1402 }
static void addDefaultCaCertificate(const QSslCertificate &cert)

◆ addDefaultCaCertificates() [1/2]

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

Searches all files in the path for certificates with the specified encoding and adds them to the default CA certificate database.

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.

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

Definition at line 1386 of file qsslsocket.cpp.

1388 {
1389  return QSslSocketPrivate::addDefaultCaCertificates(path, encoding, syntax);
1390 }
static bool addDefaultCaCertificates(const QString &path, QSsl::EncodingFormat format, QRegExp::PatternSyntax syntax)

◆ addDefaultCaCertificates() [2/2]

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

Adds certificates to the default CA certificate database.

Each SSL socket's CA certificate database is initialized to the default CA certificate database.

See also
defaultCaCertificates(), addCaCertificates()

Definition at line 1411 of file qsslsocket.cpp.

1412 {
1414 }
static bool addDefaultCaCertificates(const QString &path, QSsl::EncodingFormat format, QRegExp::PatternSyntax syntax)

◆ atEnd()

bool QSslSocket::atEnd ( ) const
virtual

Reimplemented Function

Reimplemented from QAbstractSocket.

Definition at line 833 of file qsslsocket.cpp.

834 {
835  Q_D(const QSslSocket);
836  if (d->mode == UnencryptedMode)
837  return QIODevice::atEnd() && (!d->plainSocket || d->plainSocket->atEnd());
838  return QIODevice::atEnd() && d->readBuffer.isEmpty();
839 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
virtual bool atEnd() const
Returns true if the current read and write position is at the end of the device (i.e.
Definition: qiodevice.cpp:711
#define d

◆ bytesAvailable()

qint64 QSslSocket::bytesAvailable ( ) const
virtual

Returns the number of decrypted bytes that are immediately available for reading.

Reimplemented Function

Reimplemented from QAbstractSocket.

Definition at line 731 of file qsslsocket.cpp.

732 {
733  Q_D(const QSslSocket);
734  if (d->mode == UnencryptedMode)
735  return QIODevice::bytesAvailable() + (d->plainSocket ? d->plainSocket->bytesAvailable() : 0);
736  return QIODevice::bytesAvailable() + d->readBuffer.size();
737 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d
virtual qint64 bytesAvailable() const
Returns the number of bytes that are available for reading.
Definition: qiodevice.cpp:752

◆ bytesToWrite()

qint64 QSslSocket::bytesToWrite ( ) const
virtual

Returns the number of unencrypted bytes that are waiting to be encrypted and written to the network.

Reimplemented Function

Reimplemented from QAbstractSocket.

Definition at line 748 of file qsslsocket.cpp.

749 {
750  Q_D(const QSslSocket);
751  if (d->mode == UnencryptedMode)
752  return d->plainSocket ? d->plainSocket->bytesToWrite() : 0;
753  return d->writeBuffer.size();
754 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ caCertificates()

QList< QSslCertificate > QSslSocket::caCertificates ( ) const

Returns 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. It can be moodified prior to the handshake with addCaCertificate(), addCaCertificates(), and setCaCertificates().

Note
On Unix, this method may return an empty list if the root certificates are loaded on demand.
See also
addCaCertificate(), addCaCertificates(), setCaCertificates()

Definition at line 1368 of file qsslsocket.cpp.

1369 {
1370  Q_D(const QSslSocket);
1371  return d->configuration.caCertificates;
1372 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ canReadLine()

bool QSslSocket::canReadLine ( ) const
virtual

Returns true if you can read one while line (terminated by a single ASCII '
' character) of decrypted characters; otherwise, false is returned.

Reimplemented Function

Reimplemented from QAbstractSocket.

Definition at line 800 of file qsslsocket.cpp.

801 {
802  Q_D(const QSslSocket);
803  if (d->mode == UnencryptedMode)
804  return QIODevice::canReadLine() || (d->plainSocket && d->plainSocket->canReadLine());
805  return QIODevice::canReadLine() || (!d->readBuffer.isEmpty() && d->readBuffer.canReadLine());
806 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d
virtual bool canReadLine() const
Returns true if a complete line of data can be read from the device; otherwise returns false...
Definition: qiodevice.cpp:1330

◆ ciphers()

QList< QSslCipher > QSslSocket::ciphers ( ) const

Returns this socket's current cryptographic cipher suite.

This list is used during the socket's handshake phase for choosing a session cipher. The returned list of ciphers is ordered by descending preference. (i.e., the first cipher in the list is the most preferred cipher). The session cipher will be the first one in the list that is also supported by the peer.

By default, the handshake phase can choose any of the ciphers supported by this system's SSL libraries, which may vary from system to system. The list of ciphers supported by this system's SSL libraries is returned by supportedCiphers(). You can restrict the list of ciphers used for choosing the session cipher for this socket by calling setCiphers() with a subset of the supported ciphers. You can revert to using the entire set by calling setCiphers() with the list returned by supportedCiphers().

You can restrict the list of ciphers used for choosing the session cipher for all sockets by calling setDefaultCiphers() with a subset of the supported ciphers. You can revert to using the entire set by calling setCiphers() with the list returned by supportedCiphers().

See also
setCiphers(), defaultCiphers(), setDefaultCiphers(), supportedCiphers()

Definition at line 1183 of file qsslsocket.cpp.

1184 {
1185  Q_D(const QSslSocket);
1186  return d->configuration.ciphers;
1187 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ close()

void QSslSocket::close ( )
virtual

Reimplemented Function

Reimplemented from QAbstractSocket.

Definition at line 811 of file qsslsocket.cpp.

812 {
813 #ifdef QSSLSOCKET_DEBUG
814  qDebug() << "QSslSocket::close()";
815 #endif
816  Q_D(QSslSocket);
817  if (d->plainSocket)
818  d->plainSocket->close();
820 
821  // must be cleared, reading/writing not possible on closed socket:
822  d->readBuffer.clear();
823  d->writeBuffer.clear();
824  // for QTcpSocket this is already done because it uses the readBuffer/writeBuffer
825  // if the QIODevice it is based on
826  // ### FIXME QSslSocket should probably do similar instead of having
827  // its own readBuffer/writeBuffer
828 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define d
void close()
Closes the I/O device for the socket, disconnects the socket&#39;s connection with the host...

◆ connectToHostEncrypted() [1/2]

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(), waitForEncrypted()

Definition at line 414 of file qsslsocket.cpp.

Referenced by QHttpPrivate::_q_slotSendRequest(), and QHttpNetworkConnectionChannel::ensureConnection().

415 {
416  Q_D(QSslSocket);
417  if (d->state == ConnectedState || d->state == ConnectingState) {
418  qWarning("QSslSocket::connectToHostEncrypted() called when already connecting/connected");
419  return;
420  }
421 
422  d->init();
423  d->autoStartHandshake = true;
424  d->initialized = true;
425 
426  // Note: When connecting to localhost, some platforms (e.g., HP-UX and some BSDs)
427  // establish the connection immediately (i.e., first attempt).
428  connectToHost(hostName, port, mode);
429 }
SslMode mode() const
Returns the current mode for the socket; either UnencryptedMode, where QSslSocket behaves identially ...
Definition: qsslsocket.cpp:542
void connectToHost(const QString &hostName, quint16 port, OpenMode mode=ReadWrite)
Attempts to make a connection to hostName on the given port.
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d
Q_CORE_EXPORT void qWarning(const char *,...)

◆ connectToHostEncrypted() [2/2]

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

In addition to the original behaviour 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).

Since
4.6 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
See also
connectToHostEncrypted()

Definition at line 445 of file qsslsocket.cpp.

447 {
448  Q_D(QSslSocket);
449  if (d->state == ConnectedState || d->state == ConnectingState) {
450  qWarning("QSslSocket::connectToHostEncrypted() called when already connecting/connected");
451  return;
452  }
453 
454  d->init();
455  d->autoStartHandshake = true;
456  d->initialized = true;
457  d->verificationPeerName = sslPeerName;
458 
459  // Note: When connecting to localhost, some platforms (e.g., HP-UX and some BSDs)
460  // establish the connection immediately (i.e., first attempt).
461  connectToHost(hostName, port, mode);
462 }
SslMode mode() const
Returns the current mode for the socket; either UnencryptedMode, where QSslSocket behaves identially ...
Definition: qsslsocket.cpp:542
void connectToHost(const QString &hostName, quint16 port, OpenMode mode=ReadWrite)
Attempts to make a connection to hostName on the given port.
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d
Q_CORE_EXPORT void qWarning(const char *,...)

◆ connectToHostImplementation

void QSslSocket::connectToHostImplementation ( const QString hostName,
quint16  port,
OpenMode  openMode 
)
protectedslot
Warning
This function is not part of the public interface.

Definition at line 1795 of file qsslsocket.cpp.

1797 {
1798  Q_D(QSslSocket);
1799  if (!d->initialized)
1800  d->init();
1801  d->initialized = false;
1802 
1803 #ifdef QSSLSOCKET_DEBUG
1804  qDebug() << "QSslSocket::connectToHostImplementation("
1805  << hostName << ',' << port << ',' << openMode << ')';
1806 #endif
1807  if (!d->plainSocket) {
1808 #ifdef QSSLSOCKET_DEBUG
1809  qDebug() << "\tcreating internal plain socket";
1810 #endif
1811  d->createPlainSocket(openMode);
1812  }
1813 #ifndef QT_NO_NETWORKPROXY
1814  d->plainSocket->setProxy(proxy());
1815  //copy user agent down to the plain socket (if it has been set)
1816  d->plainSocket->setProperty("_q_user-agent", property("_q_user-agent"));
1817 #endif
1818  QIODevice::open(openMode);
1819  d->plainSocket->connectToHost(hostName, port, openMode);
1820  d->cachedSocketDescriptor = d->plainSocket->socketDescriptor();
1821 }
QNetworkProxy proxy() const
Returns the network proxy for this socket.
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define d
OpenMode openMode() const
Returns the mode in which the device has been opened; i.e.
Definition: qiodevice.cpp:465
virtual bool open(OpenMode mode)
Opens the device and sets its OpenMode to mode.
Definition: qiodevice.cpp:570
QVariant property(const char *name) const
Returns the value of the object&#39;s name property.
Definition: qobject.cpp:3807

◆ defaultCaCertificates()

QList< QSslCertificate > QSslSocket::defaultCaCertificates ( )
static

Returns the current default CA certificate database.

This database is originally set to your system's default CA certificate database. If no system default database is found, an empty database will be returned. You can override the default CA certificate database with your own CA certificate database using setDefaultCaCertificates().

Each SSL socket's CA certificate database is initialized to the default CA certificate database.

Note
On Unix, this method may return an empty list if the root certificates are loaded on demand.
See also
caCertificates()

Definition at line 1448 of file qsslsocket.cpp.

1449 {
1451 }
static QList< QSslCertificate > defaultCaCertificates()

◆ defaultCiphers()

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 with the peer to choose a session cipher. The list is ordered by preference (i.e., the first cipher in the list is the most preferred cipher).

By default, the handshake phase can choose any of the ciphers supported by this system's SSL libraries, which may vary from system to system. The list of ciphers supported by this system's SSL libraries is returned by supportedCiphers().

See also
supportedCiphers()

Definition at line 1263 of file qsslsocket.cpp.

1264 {
1266 }
static QList< QSslCipher > defaultCiphers()

◆ disconnectFromHostImplementation

void QSslSocket::disconnectFromHostImplementation ( )
protectedslot
Warning
This function is not part of the public interface.

Definition at line 1826 of file qsslsocket.cpp.

1827 {
1828  Q_D(QSslSocket);
1829 #ifdef QSSLSOCKET_DEBUG
1830  qDebug() << "QSslSocket::disconnectFromHostImplementation()";
1831 #endif
1832  if (!d->plainSocket)
1833  return;
1834  if (d->state == UnconnectedState)
1835  return;
1836  if (d->mode == UnencryptedMode && !d->autoStartHandshake) {
1837  d->plainSocket->disconnectFromHost();
1838  return;
1839  }
1840  if (d->state <= ConnectingState) {
1841  d->pendingClose = true;
1842  return;
1843  }
1844 
1845  // Perhaps emit closing()
1846  if (d->state != ClosingState) {
1847  d->state = ClosingState;
1848  emit stateChanged(d->state);
1849  }
1850 
1851  if (!d->writeBuffer.isEmpty())
1852  return;
1853 
1854  if (d->mode == UnencryptedMode) {
1855  d->plainSocket->disconnectFromHost();
1856  } else {
1857  d->disconnectFromHost();
1858  }
1859 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define emit
Definition: qobjectdefs.h:76
#define d
void stateChanged(QAbstractSocket::SocketState)
This signal is emitted whenever QAbstractSocket&#39;s state changes.

◆ encrypted

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(), QSslSocket::isEncrypted()

◆ encryptedBytesAvailable()

qint64 QSslSocket::encryptedBytesAvailable ( ) const

Returns the number of encrypted bytes that are awaiting decryption.

Since
4.4

Normally, this function will return 0 because QSslSocket decrypts its incoming data as soon as it can.

Definition at line 766 of file qsslsocket.cpp.

Referenced by QHttpNetworkConnectionChannel::_q_error().

767 {
768  Q_D(const QSslSocket);
769  if (d->mode == UnencryptedMode)
770  return 0;
771  return d->plainSocket->bytesAvailable();
772 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ encryptedBytesToWrite()

qint64 QSslSocket::encryptedBytesToWrite ( ) const

Returns the number of encrypted bytes that are waiting to be written to the network.

Since
4.4

Definition at line 783 of file qsslsocket.cpp.

Referenced by QHttpPrivate::postMoreData(), and QHttpNetworkConnectionChannel::sendRequest().

784 {
785  Q_D(const QSslSocket);
786  if (d->mode == UnencryptedMode)
787  return 0;
788  return d->plainSocket->bytesToWrite();
789 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ encryptedBytesWritten

QSslSocket::encryptedBytesWritten ( qint64  written)
signal

This signal is emitted when QSslSocket writes its encrypted data to the network.

Since
4.4

The written parameter contains the number of bytes that were successfully written.

See also
QIODevice::bytesWritten()

◆ flush()

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(), waitForBytesWritten()

Definition at line 856 of file qsslsocket.cpp.

Referenced by QHttpNetworkConnectionChannel::_q_error().

857 {
858  Q_D(QSslSocket);
859 #ifdef QSSLSOCKET_DEBUG
860  qDebug() << "QSslSocket::flush()";
861 #endif
862  if (d->mode != UnencryptedMode)
863  // encrypt any unencrypted bytes in our buffer
864  d->transmit();
865 
866  return d->plainSocket ? d->plainSocket->flush() : false;
867 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define d

◆ ignoreSslErrors() [1/2]

void QSslSocket::ignoreSslErrors ( const QList< QSslError > &  errors)

This method tells QSslSocket to ignore only the errors given in errors.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Since
4.6

Note that you can set the expected certificate in the SSL error: If, for instance, you want to connect to a server that uses a self-signed certificate, consider the following snippet:

QList<QSslError> expectedSslErrors;
expectedSslErrors.append(error);
QSslSocket socket;
socket.ignoreSslErrors(expectedSslErrors);
socket.connectToHostEncrypted("server.tld", 443);

Multiple calls to this function 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.

See also
sslErrors()

Definition at line 1786 of file qsslsocket.cpp.

Referenced by QHttpNetworkConnectionChannel::ensureConnection(), and QHttp::ignoreSslErrors().

1787 {
1788  Q_D(QSslSocket);
1789  d->ignoreErrorsList = errors;
1790 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ ignoreSslErrors [2/2]

void QSslSocket::ignoreSslErrors ( )
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 don't 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.

Warning
Be sure to always let the user inspect the errors reported by the sslErrors() signal, and only call this method upon confirmation from the user that proceeding is ok. If there are unexpected errors, the connection should be aborted. Calling this method without inspecting the actual errors will most likely pose a security risk for your application. Use it with great care!
See also
sslErrors()

Definition at line 1757 of file qsslsocket.cpp.

1758 {
1759  Q_D(QSslSocket);
1760  d->ignoreAllSslErrors = true;
1761 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ isEncrypted()

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.

See also
mode()

Definition at line 563 of file qsslsocket.cpp.

Referenced by QHttpPrivate::_q_slotSendRequest().

564 {
565  Q_D(const QSslSocket);
566  return d->connectionEncrypted;
567 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ localCertificate()

QSslCertificate QSslSocket::localCertificate ( ) const

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

See also
setLocalCertificate(), privateKey()

Definition at line 1008 of file qsslsocket.cpp.

1009 {
1010  Q_D(const QSslSocket);
1011  return d->configuration.localCertificate;
1012 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ mode()

QSslSocket::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

Definition at line 542 of file qsslsocket.cpp.

543 {
544  Q_D(const QSslSocket);
545  return d->mode;
546 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ modeChanged

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

◆ peerCertificate()

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

Definition at line 1039 of file qsslsocket.cpp.

1040 {
1041  Q_D(const QSslSocket);
1042  return d->configuration.peerCertificate;
1043 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

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

Definition at line 1068 of file qsslsocket.cpp.

1069 {
1070  Q_D(const QSslSocket);
1071  return d->configuration.peerCertificateChain;
1072 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ peerVerifyDepth()

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.

Since
4.4

The certificates are checked in issuing order, starting with the peer's own certificate, then its issuer's certificate, and so on.

See also
setPeerVerifyDepth(), peerVerifyMode()

Definition at line 656 of file qsslsocket.cpp.

657 {
658  Q_D(const QSslSocket);
659  return d->configuration.peerVerifyDepth;
660 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ peerVerifyError

void QSslSocket::peerVerifyError ( const QSslError error)
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.

Since
4.4

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

See also
sslErrors()

◆ peerVerifyMode()

QSslSocket::PeerVerifyMode QSslSocket::peerVerifyMode ( ) const

Returns the socket's verify mode.

Since
4.4

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

See also
setPeerVerifyMode(), peerVerifyDepth(), mode()

Definition at line 608 of file qsslsocket.cpp.

609 {
610  Q_D(const QSslSocket);
611  return d->configuration.peerVerifyMode;
612 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ peerVerifyName()

QString QSslSocket::peerVerifyName ( ) const

Returns the different hostname for the certificate validation, as set by setPeerVerifyName or by connectToHostEncrypted.

Since
4.8
See also
setPeerVerifyName(), connectToHostEncrypted()

Definition at line 699 of file qsslsocket.cpp.

700 {
701  Q_D(const QSslSocket);
702  return d->verificationPeerName;
703 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ privateKey()

QSslKey QSslSocket::privateKey ( ) const

Returns this socket's private key.

See also
setPrivateKey(), localCertificate()

Definition at line 1152 of file qsslsocket.cpp.

1153 {
1154  Q_D(const QSslSocket);
1155  return d->configuration.privateKey;
1156 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ protocol()

QSsl::SslProtocol QSslSocket::protocol ( ) const

Returns the socket's SSL protocol.

By default, QSsl::SecureProtocols is used.

See also
setProtocol()

Definition at line 574 of file qsslsocket.cpp.

575 {
576  Q_D(const QSslSocket);
577  return d->configuration.protocol;
578 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ readData()

qint64 QSslSocket::readData ( char *  data,
qint64  maxlen 
)
protectedvirtual

Reimplemented Function

Reimplemented from QAbstractSocket.

Definition at line 1864 of file qsslsocket.cpp.

1865 {
1866  Q_D(QSslSocket);
1867  qint64 readBytes = 0;
1868 
1869  if (d->mode == UnencryptedMode && !d->autoStartHandshake) {
1870  readBytes = d->plainSocket->read(data, maxlen);
1871  } else {
1872  do {
1873  const char *readPtr = d->readBuffer.readPointer();
1874  int bytesToRead = qMin<int>(maxlen - readBytes, d->readBuffer.nextDataBlockSize());
1875  ::memcpy(data + readBytes, readPtr, bytesToRead);
1876  readBytes += bytesToRead;
1877  d->readBuffer.free(bytesToRead);
1878  } while (!d->readBuffer.isEmpty() && readBytes < maxlen);
1879  }
1880 #ifdef QSSLSOCKET_DEBUG
1881  qDebug() << "QSslSocket::readData(" << (void *)data << ',' << maxlen << ") ==" << readBytes;
1882 #endif
1883 
1884  // possibly trigger another transmit() to decrypt more data from the socket
1885  if (d->readBuffer.isEmpty() && d->plainSocket->bytesAvailable())
1886  QMetaObject::invokeMethod(this, "_q_flushReadBuffer", Qt::QueuedConnection);
1887 
1888  return readBytes;
1889 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define d
static const char * data(const QByteArray &arr)
__int64 qint64
Definition: qglobal.h:942
static bool invokeMethod(QObject *obj, const char *member, Qt::ConnectionType, QGenericReturnArgument ret, QGenericArgument val0=QGenericArgument(0), QGenericArgument val1=QGenericArgument(), QGenericArgument val2=QGenericArgument(), QGenericArgument val3=QGenericArgument(), QGenericArgument val4=QGenericArgument(), QGenericArgument val5=QGenericArgument(), QGenericArgument val6=QGenericArgument(), QGenericArgument val7=QGenericArgument(), QGenericArgument val8=QGenericArgument(), QGenericArgument val9=QGenericArgument())
Invokes the member (a signal or a slot name) on the object obj.

◆ sessionCipher()

QSslCipher QSslSocket::sessionCipher ( ) const

Returns the socket's cryptographic QSslCipher {cipher}, or a null cipher if the connection isn't 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.

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

Definition at line 1088 of file qsslsocket.cpp.

1089 {
1090  Q_D(const QSslSocket);
1091  return d->sessionCipher();
1092 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ setCaCertificates()

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

Sets this socket's CA certificate database to be certificates.

The certificate database must be set prior to the SSL handshake. The CA certificate database is used by the socket during the handshake phase to validate the peer's certificate.

The CA certificate database can be reset to the current default CA certificate database by calling this function with the list of CA certificates returned by defaultCaCertificates().

See also
defaultCaCertificates()

Definition at line 1349 of file qsslsocket.cpp.

1350 {
1351  Q_D(QSslSocket);
1352  d->configuration.caCertificates = certificates;
1353  d->allowRootCertOnDemandLoading = false;
1354 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ setCiphers() [1/2]

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

Sets the cryptographic cipher suite for this socket to ciphers, which must contain a subset of the ciphers in the list returned by supportedCiphers().

Restricting the cipher suite must be done before the handshake phase, where the session cipher is chosen.

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

Definition at line 1199 of file qsslsocket.cpp.

1200 {
1201  Q_D(QSslSocket);
1202  d->configuration.ciphers = ciphers;
1203 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
QList< QSslCipher > ciphers() const
Returns this socket&#39;s current cryptographic cipher suite.
#define d

◆ setCiphers() [2/2]

void QSslSocket::setCiphers ( const QString ciphers)

Sets the cryptographic cipher suite for this socket to ciphers, which is a colon-separated list of cipher suite names.

The ciphers are listed in order of preference, starting with the most preferred cipher. For example:

QSslSocket socket;
socket.setCiphers("DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-SHA");

Each cipher name in ciphers must be the name of a cipher in the list returned by supportedCiphers(). Restricting the cipher suite must be done before the handshake phase, where the session cipher is chosen.

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

Definition at line 1219 of file qsslsocket.cpp.

1220 {
1221  Q_D(QSslSocket);
1222  d->configuration.ciphers.clear();
1223  foreach (const QString &cipherName, ciphers.split(QLatin1String(":"),QString::SkipEmptyParts)) {
1224  for (int i = 0; i < 3; ++i) {
1225  // ### Crude
1226  QSslCipher cipher(cipherName, QSsl::SslProtocol(i));
1227  if (!cipher.isNull())
1228  d->configuration.ciphers << cipher;
1229  }
1230  }
1231 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482
The QSslCipher class represents an SSL cryptographic cipher.
Definition: qsslcipher.h:59
SslProtocol
Describes the protocol of the cipher.
Definition: qssl.h:76
#define d
The QLatin1String class provides a thin wrapper around an US-ASCII/Latin-1 encoded string literal...
Definition: qstring.h:654
QStringList split(const QString &sep, SplitBehavior behavior=KeepEmptyParts, Qt::CaseSensitivity cs=Qt::CaseSensitive) const Q_REQUIRED_RESULT
Splits the string into substrings wherever sep occurs, and returns the list of those strings...
Definition: qstring.cpp:6526

◆ setDefaultCaCertificates()

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

Sets the default CA certificate database to certificates.

The default CA certificate database is originally set to your system's default CA certificate database. You can override the default CA certificate database with your own CA certificate database using this function.

Each SSL socket's CA certificate database is initialized to the default CA certificate database.

See also
addDefaultCaCertificate()

Definition at line 1428 of file qsslsocket.cpp.

1429 {
1431 }
static void setDefaultCaCertificates(const QList< QSslCertificate > &certs)

◆ setDefaultCiphers()

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

Sets the default cryptographic cipher suite for all sockets in this application to ciphers, which must contain a subset of the ciphers in the list returned by supportedCiphers().

Restricting the default cipher suite only affects SSL sockets that perform their handshake phase after the default cipher suite has been changed.

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

Definition at line 1244 of file qsslsocket.cpp.

1245 {
1247 }
static void setDefaultCiphers(const QList< QSslCipher > &ciphers)

◆ setLocalCertificate() [1/2]

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(), setPrivateKey()

Definition at line 977 of file qsslsocket.cpp.

978 {
979  Q_D(QSslSocket);
980  d->configuration.localCertificate = certificate;
981 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ setLocalCertificate() [2/2]

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

Sets the socket's local QSslCertificate {certificate} to the first one found in file path, which is parsed according to the specified format.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 993 of file qsslsocket.cpp.

995 {
996  Q_D(QSslSocket);
997  QFile file(path);
998  if (file.open(QIODevice::ReadOnly | QIODevice::Text))
999  d->configuration.localCertificate = QSslCertificate(file.readAll(), format);
1000 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
The QSslCertificate class provides a convenient API for an X509 certificate.

◆ setPeerVerifyDepth()

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.

Since
4.4

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.

See also
peerVerifyDepth(), setPeerVerifyMode()

Definition at line 678 of file qsslsocket.cpp.

679 {
680  Q_D(QSslSocket);
681  if (depth < 0) {
682  qWarning("QSslSocket::setPeerVerifyDepth: cannot set negative depth of %d", depth);
683  return;
684  }
685  d->configuration.peerVerifyDepth = depth;
686 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d
Q_CORE_EXPORT void qWarning(const char *,...)

◆ setPeerVerifyMode()

void QSslSocket::setPeerVerifyMode ( QSslSocket::PeerVerifyMode  mode)

Sets the socket's verify mode to mode.

Since
4.4

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.

See also
peerVerifyMode(), setPeerVerifyDepth(), mode()

Definition at line 634 of file qsslsocket.cpp.

635 {
636  Q_D(QSslSocket);
637  d->configuration.peerVerifyMode = mode;
638 }
SslMode mode() const
Returns the current mode for the socket; either UnencryptedMode, where QSslSocket behaves identially ...
Definition: qsslsocket.cpp:542
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ setPeerVerifyName()

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.

Since
4.8
See also
connectToHostEncrypted()

Definition at line 716 of file qsslsocket.cpp.

717 {
718  Q_D(QSslSocket);
719  d->verificationPeerName = hostName;
720 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ setPrivateKey() [1/2]

void QSslSocket::setPrivateKey ( const QSslKey key)

Sets the socket's private QSslKey {key} to key.

The private key and the local QSslCertificate {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(), setLocalCertificate()

Definition at line 1107 of file qsslsocket.cpp.

1108 {
1109  Q_D(QSslSocket);
1110  d->configuration.privateKey = key;
1111 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d
int key

◆ setPrivateKey() [2/2]

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 QSslKey {SSL key}.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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 QSslCertificate {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(), setLocalCertificate()

Definition at line 1136 of file qsslsocket.cpp.

1138 {
1139  Q_D(QSslSocket);
1140  QFile file(fileName);
1141  if (file.open(QIODevice::ReadOnly)) {
1142  d->configuration.privateKey = QSslKey(file.readAll(), algorithm,
1143  format, QSsl::PrivateKey, passPhrase);
1144  }
1145 }
The QSslKey class provides an interface for private and public keys.
Definition: qsslkey.h:64
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65

◆ setProtocol()

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.

Definition at line 585 of file qsslsocket.cpp.

586 {
587  Q_D(QSslSocket);
588  d->configuration.protocol = protocol;
589 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
QSsl::SslProtocol protocol() const
Returns the socket&#39;s SSL protocol.
Definition: qsslsocket.cpp:574
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ setReadBufferSize()

void QSslSocket::setReadBufferSize ( qint64  size)

Sets the size of QSslSocket's internal read buffer to be size bytes.

Since
4.4

Definition at line 877 of file qsslsocket.cpp.

878 {
879  Q_D(QSslSocket);
880  d->readBufferMaxSize = size;
881 
882  if (d->plainSocket)
883  d->plainSocket->setReadBufferSize(size);
884 }
virtual qint64 size() const
For open random-access devices, this function returns the size of the device.
Definition: qiodevice.cpp:642
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ setSocketDescriptor()

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

Definition at line 476 of file qsslsocket.cpp.

477 {
478  Q_D(QSslSocket);
479 #ifdef QSSLSOCKET_DEBUG
480  qDebug() << "QSslSocket::setSocketDescriptor(" << socketDescriptor << ','
481  << state << ',' << openMode << ')';
482 #endif
483  if (!d->plainSocket)
484  d->createPlainSocket(openMode);
485  bool retVal = d->plainSocket->setSocketDescriptor(socketDescriptor, state, openMode);
486  d->cachedSocketDescriptor = d->plainSocket->socketDescriptor();
487  setSocketError(d->plainSocket->error());
489  setOpenMode(openMode);
490  setLocalPort(d->plainSocket->localPort());
491  setLocalAddress(d->plainSocket->localAddress());
492  setPeerPort(d->plainSocket->peerPort());
493  setPeerAddress(d->plainSocket->peerAddress());
494  setPeerName(d->plainSocket->peerName());
495  return retVal;
496 }
int socketDescriptor() const
Returns the native socket descriptor of the QAbstractSocket object if this is available; otherwise re...
void setSocketError(SocketError socketError)
Sets the type of error that last occurred to socketError.
void setOpenMode(OpenMode openMode)
Sets the OpenMode of the device to openMode.
Definition: qiodevice.cpp:477
void setPeerName(const QString &name)
Sets the host name of the remote peer to name.
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
void setSocketState(SocketState state)
Sets the state of the socket to state.
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define d
void setLocalAddress(const QHostAddress &address)
Sets the address on the local side of a connection to address.
OpenMode openMode() const
Returns the mode in which the device has been opened; i.e.
Definition: qiodevice.cpp:465
void setLocalPort(quint16 port)
Sets the port on the local side of a connection to port.
void setPeerAddress(const QHostAddress &address)
Sets the address of the remote side of the connection to address.
void setPeerPort(quint16 port)
Sets the port of the remote side of the connection to port.
SocketState state() const
Returns the state of the socket.

◆ setSocketOption()

void QSslSocket::setSocketOption ( QAbstractSocket::SocketOption  option,
const QVariant value 
)

Sets the given option to the value described by value.

Since
4.6
See also
socketOption()

Definition at line 507 of file qsslsocket.cpp.

508 {
509  Q_D(QSslSocket);
510  if (d->plainSocket)
511  d->plainSocket->setSocketOption(option, value);
512 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ setSslConfiguration()

void QSslSocket::setSslConfiguration ( const QSslConfiguration configuration)

Sets the socket's SSL configuration to be the contents of configuration.

Since
4.4

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

See also
setLocalCertificate(), setPrivateKey(), setCaCertificates(), setCiphers()

Definition at line 946 of file qsslsocket.cpp.

947 {
948  Q_D(QSslSocket);
949  d->configuration.localCertificate = configuration.localCertificate();
950  d->configuration.privateKey = configuration.privateKey();
951  d->configuration.ciphers = configuration.ciphers();
952  d->configuration.caCertificates = configuration.caCertificates();
953  d->configuration.peerVerifyDepth = configuration.peerVerifyDepth();
954  d->configuration.peerVerifyMode = configuration.peerVerifyMode();
955  d->configuration.protocol = configuration.protocol();
956  d->configuration.sslOptions = configuration.d->sslOptions;
957 
958  // if the CA certificates were set explicitly (either via
959  // QSslConfiguration::setCaCertificates() or QSslSocket::setCaCertificates(),
960  // we cannot load the certificates on demand
961  if (!configuration.d->allowRootCertOnDemandLoading)
962  d->allowRootCertOnDemandLoading = false;
963 }
QSharedDataPointer< QSslConfigurationPrivate > d
QList< QSslCipher > ciphers() const
Returns this connection&#39;s current cryptographic cipher suite.
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
QSsl::SslProtocol protocol() const
Returns the protocol setting for this SSL configuration.
#define d
QSslKey privateKey() const
Returns the QSslKey {SSL key} assigned to this connection or a null key if none has been assigned yet...
int peerVerifyDepth() const
Returns the maximum number of certificates in the peer&#39;s certificate chain to be checked during the S...
QSslCertificate localCertificate() const
Returns the certificate to be presented to the peer during the SSL handshake process.
QSslSocket::PeerVerifyMode peerVerifyMode() const
Returns the verify mode.
QList< QSslCertificate > caCertificates() const
Returns this connection&#39;s CA certificate database.

◆ socketOption()

QVariant QSslSocket::socketOption ( QAbstractSocket::SocketOption  option)

Returns the value of the option option.

Since
4.6
See also
setSocketOption()

Definition at line 523 of file qsslsocket.cpp.

524 {
525  Q_D(QSslSocket);
526  if (d->plainSocket)
527  return d->plainSocket->socketOption(option);
528  else
529  return QVariant();
530 }
The QVariant class acts like a union for the most common Qt data types.
Definition: qvariant.h:92
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ sslConfiguration()

QSslConfiguration QSslSocket::sslConfiguration ( ) const

Returns the socket's SSL configuration state.

Since
4.4

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.

See also
localCertificate(), peerCertificate(), peerCertificateChain(), sessionCipher(), privateKey(), ciphers(), caCertificates()

Definition at line 920 of file qsslsocket.cpp.

Referenced by QHttpNetworkReply::sslConfiguration().

921 {
922  Q_D(const QSslSocket);
923 
924  // create a deep copy of our configuration
925  QSslConfigurationPrivate *copy = new QSslConfigurationPrivate(d->configuration);
926  copy->ref = 0; // the QSslConfiguration constructor refs up
927  copy->sessionCipher = d->sessionCipher();
928 
929  return QSslConfiguration(copy);
930 }
QAtomicInt ref
Definition: qshareddata.h:59
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d
The QSslConfiguration class holds the configuration and state of an SSL connection.

◆ sslErrors() [1/2]

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

Definition at line 1653 of file qsslsocket.cpp.

1654 {
1655  Q_D(const QSslSocket);
1656  return d->sslErrors;
1657 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
#define d

◆ sslErrors [2/2]

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

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

See also
peerVerifyError()

◆ startClientEncryption

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

See also
connectToHostEncrypted(), startServerEncryption()

Definition at line 1682 of file qsslsocket.cpp.

1683 {
1684  Q_D(QSslSocket);
1685  if (d->mode != UnencryptedMode) {
1686  qWarning("QSslSocket::startClientEncryption: cannot start handshake on non-plain connection");
1687  return;
1688  }
1689 #ifdef QSSLSOCKET_DEBUG
1690  qDebug() << "QSslSocket::startClientEncryption()";
1691 #endif
1692  d->mode = SslClientMode;
1693  emit modeChanged(d->mode);
1694  d->startClientEncryption();
1695 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define emit
Definition: qobjectdefs.h:76
#define d
Q_CORE_EXPORT void qWarning(const char *,...)
void modeChanged(QSslSocket::SslMode newMode)
This signal is emitted when QSslSocket changes from QSslSocket::UnencryptedMode to either QSslSocket:...

◆ startServerEncryption

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

See also
connectToHostEncrypted(), startClientEncryption()

Definition at line 1717 of file qsslsocket.cpp.

1718 {
1719  Q_D(QSslSocket);
1720  if (d->mode != UnencryptedMode) {
1721  qWarning("QSslSocket::startServerEncryption: cannot start handshake on non-plain connection");
1722  return;
1723  }
1724 #ifdef QSSLSOCKET_DEBUG
1725  qDebug() << "QSslSocket::startServerEncryption()";
1726 #endif
1727  d->mode = SslServerMode;
1728  emit modeChanged(d->mode);
1729  d->startServerEncryption();
1730 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define emit
Definition: qobjectdefs.h:76
#define d
Q_CORE_EXPORT void qWarning(const char *,...)
void modeChanged(QSslSocket::SslMode newMode)
This signal is emitted when QSslSocket changes from QSslSocket::UnencryptedMode to either QSslSocket:...

◆ supportedCiphers()

QList< QSslCipher > QSslSocket::supportedCiphers ( )
static

Returns the list of cryptographic ciphers supported by this system.

This list is set by the system's SSL libraries and may vary from system to system.

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

Definition at line 1275 of file qsslsocket.cpp.

Referenced by QSslCipher::QSslCipher().

1276 {
1278 }
static QList< QSslCipher > supportedCiphers()

◆ supportsSsl()

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.

Definition at line 1664 of file qsslsocket.cpp.

Referenced by QSslKeyPrivate::clear(), QSslKeyPrivate::decodePem(), QSslCertificatePrivate::QSslCertificate_from_X509(), QHttpPrivate::setSock(), and QSslKey::toPem().

1665 {
1667 }
static bool supportsSsl()
Does the minimum amount of initialization to determine whether SSL is supported or not...

◆ systemCaCertificates()

QList< QSslCertificate > QSslSocket::systemCaCertificates ( )
static

This function provides the CA certificate database provided by the operating system.

The CA certificate database returned by this function is used to initialize the database returned by defaultCaCertificates(). You can replace that database with your own with setDefaultCaCertificates().

See also
caCertificates(), defaultCaCertificates(), setDefaultCaCertificates()

Definition at line 1462 of file qsslsocket.cpp.

1463 {
1464  // we are calling ensureInitialized() in the method below
1466 }
static QList< QSslCertificate > systemCaCertificates()

◆ waitForBytesWritten()

bool QSslSocket::waitForBytesWritten ( int  msecs = 30000)
virtual

Reimplemented Function

Reimplemented from QAbstractSocket.

Definition at line 1582 of file qsslsocket.cpp.

1583 {
1584  Q_D(QSslSocket);
1585  if (!d->plainSocket)
1586  return false;
1587  if (d->mode == UnencryptedMode)
1588  return d->plainSocket->waitForBytesWritten(msecs);
1589 
1590  QElapsedTimer stopWatch;
1591  stopWatch.start();
1592 
1593  if (!d->connectionEncrypted) {
1594  // Wait until we've entered encrypted mode, or until a failure occurs.
1595  if (!waitForEncrypted(msecs))
1596  return false;
1597  }
1598  if (!d->writeBuffer.isEmpty()) {
1599  // empty our cleartext write buffer first
1600  d->transmit();
1601  }
1602 
1603  return d->plainSocket->waitForBytesWritten(qt_timeout_value(msecs, stopWatch.elapsed()));
1604 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
The QElapsedTimer class provides a fast way to calculate elapsed times.
Definition: qelapsedtimer.h:53
qint64 elapsed() const
Returns the number of milliseconds since this QElapsedTimer was last started.
#define d
static int qt_timeout_value(int msecs, int elapsed)
Definition: qsslsocket.cpp:325
bool waitForEncrypted(int msecs=30000)
Waits until the socket has completed the SSL handshake and has emitted encrypted(), or msecs milliseconds, whichever comes first.
void start()
Starts this timer.

◆ waitForConnected()

bool QSslSocket::waitForConnected ( int  msecs = 30000)

Waits until the socket is connected, or msecs milliseconds, whichever happens first.

If the connection has been established, this function returns true; otherwise it returns false.

See also
QAbstractSocket::waitForConnected()

Definition at line 1475 of file qsslsocket.cpp.

1476 {
1477  Q_D(QSslSocket);
1478  if (!d->plainSocket)
1479  return false;
1480  bool retVal = d->plainSocket->waitForConnected(msecs);
1481  if (!retVal) {
1482  setSocketState(d->plainSocket->state());
1483  setSocketError(d->plainSocket->error());
1484  setErrorString(d->plainSocket->errorString());
1485  }
1486  return retVal;
1487 }
void setSocketError(SocketError socketError)
Sets the type of error that last occurred to socketError.
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
void setSocketState(SocketState state)
Sets the state of the socket to state.
#define Q_D(Class)
Definition: qglobal.h:2482
#define d
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660

◆ waitForDisconnected()

bool QSslSocket::waitForDisconnected ( int  msecs = 30000)

Waits until the socket has disconnected or msecs milliseconds, whichever comes first.

If the connection has been disconnected, this function returns true; otherwise it returns false.

See also
QAbstractSocket::waitForDisconnected()

Definition at line 1613 of file qsslsocket.cpp.

1614 {
1615  Q_D(QSslSocket);
1616 
1617  // require calling connectToHost() before waitForDisconnected()
1618  if (state() == UnconnectedState) {
1619  qWarning("QSslSocket::waitForDisconnected() is not allowed in UnconnectedState");
1620  return false;
1621  }
1622 
1623  if (!d->plainSocket)
1624  return false;
1625  if (d->mode == UnencryptedMode)
1626  return d->plainSocket->waitForDisconnected(msecs);
1627 
1628  QElapsedTimer stopWatch;
1629  stopWatch.start();
1630 
1631  if (!d->connectionEncrypted) {
1632  // Wait until we've entered encrypted mode, or until a failure occurs.
1633  if (!waitForEncrypted(msecs))
1634  return false;
1635  }
1636  bool retVal = d->plainSocket->waitForDisconnected(qt_timeout_value(msecs, stopWatch.elapsed()));
1637  if (!retVal) {
1638  setSocketState(d->plainSocket->state());
1639  setSocketError(d->plainSocket->error());
1640  setErrorString(d->plainSocket->errorString());
1641  }
1642  return retVal;
1643 }
void setSocketError(SocketError socketError)
Sets the type of error that last occurred to socketError.
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
void setSocketState(SocketState state)
Sets the state of the socket to state.
#define Q_D(Class)
Definition: qglobal.h:2482
The QElapsedTimer class provides a fast way to calculate elapsed times.
Definition: qelapsedtimer.h:53
qint64 elapsed() const
Returns the number of milliseconds since this QElapsedTimer was last started.
#define d
Q_CORE_EXPORT void qWarning(const char *,...)
static int qt_timeout_value(int msecs, int elapsed)
Definition: qsslsocket.cpp:325
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
bool waitForEncrypted(int msecs=30000)
Waits until the socket has completed the SSL handshake and has emitted encrypted(), or msecs milliseconds, whichever comes first.
void start()
Starts this timer.
SocketState state() const
Returns the state of the socket.

◆ waitForEncrypted()

bool QSslSocket::waitForEncrypted ( int  msecs = 30000)

Waits until the socket has completed the SSL handshake and has emitted encrypted(), or msecs milliseconds, whichever comes first.

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(), isEncrypted()

Definition at line 1505 of file qsslsocket.cpp.

1506 {
1507  Q_D(QSslSocket);
1508  if (!d->plainSocket || d->connectionEncrypted)
1509  return false;
1510  if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1511  return false;
1512 
1513  QElapsedTimer stopWatch;
1514  stopWatch.start();
1515 
1516  if (d->plainSocket->state() != QAbstractSocket::ConnectedState) {
1517  // Wait until we've entered connected state.
1518  if (!d->plainSocket->waitForConnected(msecs))
1519  return false;
1520  }
1521 
1522  while (!d->connectionEncrypted) {
1523  // Start the handshake, if this hasn't been started yet.
1524  if (d->mode == UnencryptedMode)
1526  // Loop, waiting until the connection has been encrypted or an error
1527  // occurs.
1528  if (!d->plainSocket->waitForReadyRead(qt_timeout_value(msecs, stopWatch.elapsed())))
1529  return false;
1530  }
1531  return d->connectionEncrypted;
1532 }
void startClientEncryption()
Starts a delayed SSL handshake for a client connection.
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
The QElapsedTimer class provides a fast way to calculate elapsed times.
Definition: qelapsedtimer.h:53
qint64 elapsed() const
Returns the number of milliseconds since this QElapsedTimer was last started.
#define d
static int qt_timeout_value(int msecs, int elapsed)
Definition: qsslsocket.cpp:325
void start()
Starts this timer.

◆ waitForReadyRead()

bool QSslSocket::waitForReadyRead ( int  msecs = 30000)
virtual

Reimplemented Function

Reimplemented from QAbstractSocket.

Definition at line 1537 of file qsslsocket.cpp.

1538 {
1539  Q_D(QSslSocket);
1540  if (!d->plainSocket)
1541  return false;
1542  if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1543  return d->plainSocket->waitForReadyRead(msecs);
1544 
1545  // This function must return true if and only if readyRead() *was* emitted.
1546  // So we initialize "readyReadEmitted" to false and check if it was set to true.
1547  // waitForReadyRead() could be called recursively, so we can't use the same variable
1548  // (the inner waitForReadyRead() may fail, but the outer one still succeeded)
1549  bool readyReadEmitted = false;
1550  bool *previousReadyReadEmittedPointer = d->readyReadEmittedPointer;
1551  d->readyReadEmittedPointer = &readyReadEmitted;
1552 
1553  QElapsedTimer stopWatch;
1554  stopWatch.start();
1555 
1556  if (!d->connectionEncrypted) {
1557  // Wait until we've entered encrypted mode, or until a failure occurs.
1558  if (!waitForEncrypted(msecs)) {
1559  d->readyReadEmittedPointer = previousReadyReadEmittedPointer;
1560  return false;
1561  }
1562  }
1563 
1564  if (!d->writeBuffer.isEmpty()) {
1565  // empty our cleartext write buffer first
1566  d->transmit();
1567  }
1568 
1569  // test readyReadEmitted first because either operation above
1570  // (waitForEncrypted or transmit) may have set it
1571  while (!readyReadEmitted &&
1572  d->plainSocket->waitForReadyRead(qt_timeout_value(msecs, stopWatch.elapsed()))) {
1573  }
1574 
1575  d->readyReadEmittedPointer = previousReadyReadEmittedPointer;
1576  return readyReadEmitted;
1577 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
The QElapsedTimer class provides a fast way to calculate elapsed times.
Definition: qelapsedtimer.h:53
qint64 elapsed() const
Returns the number of milliseconds since this QElapsedTimer was last started.
#define d
static int qt_timeout_value(int msecs, int elapsed)
Definition: qsslsocket.cpp:325
bool waitForEncrypted(int msecs=30000)
Waits until the socket has completed the SSL handshake and has emitted encrypted(), or msecs milliseconds, whichever comes first.
void start()
Starts this timer.

◆ writeData()

qint64 QSslSocket::writeData ( const char *  data,
qint64  len 
)
protectedvirtual

Reimplemented Function

Reimplemented from QAbstractSocket.

Definition at line 1894 of file qsslsocket.cpp.

1895 {
1896  Q_D(QSslSocket);
1897 #ifdef QSSLSOCKET_DEBUG
1898  qDebug() << "QSslSocket::writeData(" << (void *)data << ',' << len << ')';
1899 #endif
1900  if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1901  return d->plainSocket->write(data, len);
1902 
1903  char *writePtr = d->writeBuffer.reserve(len);
1904  ::memcpy(writePtr, data, len);
1905 
1906  // make sure we flush to the plain socket's buffer
1907  QMetaObject::invokeMethod(this, "_q_flushWriteBuffer", Qt::QueuedConnection);
1908 
1909  return len;
1910 }
The QSslSocket class provides an SSL encrypted socket for both clients and servers.
Definition: qsslsocket.h:67
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define d
static const char * data(const QByteArray &arr)
static bool invokeMethod(QObject *obj, const char *member, Qt::ConnectionType, QGenericReturnArgument ret, QGenericArgument val0=QGenericArgument(0), QGenericArgument val1=QGenericArgument(), QGenericArgument val2=QGenericArgument(), QGenericArgument val3=QGenericArgument(), QGenericArgument val4=QGenericArgument(), QGenericArgument val5=QGenericArgument(), QGenericArgument val6=QGenericArgument(), QGenericArgument val7=QGenericArgument(), QGenericArgument val8=QGenericArgument(), QGenericArgument val9=QGenericArgument())
Invokes the member (a signal or a slot name) on the object obj.

Friends and Related Functions

◆ QSslSocketBackendPrivate

Definition at line 214 of file qsslsocket.h.


The documentation for this class was generated from the following files: