Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
|
This class provides encryption for UDP sockets. More...
#include <qdtls.h>
Public Types | |
enum | HandshakeState { HandshakeNotStarted , HandshakeInProgress , PeerVerificationFailed , HandshakeComplete } |
Describes the current state of DTLS handshake. More... | |
using | GeneratorParameters = QDtlsClientVerifier::GeneratorParameters |
Signals | |
void | pskRequired (QSslPreSharedKeyAuthenticator *authenticator) |
QDtls emits this signal when it negotiates a PSK ciphersuite, and therefore a PSK authentication is then required. | |
void | handshakeTimeout () |
Packet loss can result in timeouts during the handshake phase. | |
Signals inherited from QObject | |
void | destroyed (QObject *=nullptr) |
This signal is emitted immediately before the object obj is destroyed, after any instances of QPointer have been notified, and cannot be blocked. | |
void | objectNameChanged (const QString &objectName, QPrivateSignal) |
This signal is emitted after the object's name has been changed. | |
Public Member Functions | |
QDtls (QSslSocket::SslMode mode, QObject *parent=nullptr) | |
Creates a QDtls object, parent is passed to the QObject constructor. | |
~QDtls () | |
Destroys the QDtls object. | |
bool | setPeer (const QHostAddress &address, quint16 port, const QString &verificationName={}) |
Sets the peer's address, port, and host name and returns true if successful. | |
bool | setPeerVerificationName (const QString &name) |
Sets the host name that will be used for the certificate validation and returns true if successful. | |
QHostAddress | peerAddress () const |
Returns the peer's address, set by setPeer(), or QHostAddress::Null. | |
quint16 | peerPort () const |
Returns the peer's port number, set by setPeer(), or 0. | |
QString | peerVerificationName () const |
Returns the host name set by setPeer() or setPeerVerificationName(). | |
QSslSocket::SslMode | sslMode () const |
Returns QSslSocket::SslServerMode for a server-side connection and QSslSocket::SslClientMode for a client. | |
void | setMtuHint (quint16 mtuHint) |
mtuHint is the maximum transmission unit (MTU), either discovered or guessed by the application. | |
quint16 | mtuHint () const |
Returns the value previously set by setMtuHint(). | |
bool | setCookieGeneratorParameters (const GeneratorParameters ¶ms) |
Sets the cryptographic hash algorithm and the secret from params. | |
GeneratorParameters | cookieGeneratorParameters () const |
Returns the current hash algorithm and secret, either default ones or previously set by a call to setCookieGeneratorParameters(). | |
bool | setDtlsConfiguration (const QSslConfiguration &configuration) |
Sets the connection's TLS configuration from configuration and returns true if successful. | |
QSslConfiguration | dtlsConfiguration () const |
Returns either the default DTLS configuration or the configuration set by an earlier call to setDtlsConfiguration(). | |
HandshakeState | handshakeState () const |
Returns the current handshake state for this QDtls. | |
bool | doHandshake (QUdpSocket *socket, const QByteArray &dgram={}) |
Starts or continues a DTLS handshake. | |
bool | handleTimeout (QUdpSocket *socket) |
If a timeout occurs during the handshake, the handshakeTimeout() signal is emitted. | |
bool | resumeHandshake (QUdpSocket *socket) |
If peer verification errors were ignored during the handshake, resumeHandshake() resumes and completes the handshake and returns true . | |
bool | abortHandshake (QUdpSocket *socket) |
Aborts the ongoing handshake. | |
bool | shutdown (QUdpSocket *socket) |
Sends an encrypted shutdown alert message and closes the DTLS connection. | |
bool | isConnectionEncrypted () const |
Returns true if DTLS handshake completed successfully. | |
QSslCipher | sessionCipher () const |
Returns the cryptographic \l {QSslCipher} {cipher} used by this connection, or a null cipher if the connection isn't encrypted. | |
QSsl::SslProtocol | sessionProtocol () const |
Returns the DTLS protocol version used by this connection, or UnknownProtocol if the connection isn't encrypted yet. | |
qint64 | writeDatagramEncrypted (QUdpSocket *socket, const QByteArray &dgram) |
Encrypts dgram and writes the encrypted data into socket. | |
QByteArray | decryptDatagram (QUdpSocket *socket, const QByteArray &dgram) |
Decrypts dgram and returns its contents as plain text. | |
QDtlsError | dtlsError () const |
Returns the last error encountered by the connection or QDtlsError::NoError. | |
QString | dtlsErrorString () const |
Returns a textual description for the last error encountered by the connection or empty string. | |
QList< QSslError > | peerVerificationErrors () const |
Returns errors found while establishing the identity of the peer. | |
void | ignoreVerificationErrors (const QList< QSslError > &errorsToIgnore) |
This method tells QDtls to ignore only the errors given in errorsToIgnore. | |
Public Member Functions inherited from QObject | |
Q_INVOKABLE | QObject (QObject *parent=nullptr) |
Constructs an object with parent object parent. | |
virtual | ~QObject () |
Destroys the object, deleting all its child objects. | |
virtual bool | event (QEvent *event) |
This virtual function receives events to an object and should return true if the event e was recognized and processed. | |
virtual bool | eventFilter (QObject *watched, QEvent *event) |
Filters events if this object has been installed as an event filter for the watched object. | |
QString | objectName () const |
Q_WEAK_OVERLOAD void | setObjectName (const QString &name) |
Sets the object's name to name. | |
void | setObjectName (QAnyStringView name) |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. | |
QBindable< QString > | bindableObjectName () |
bool | isWidgetType () const |
Returns true if the object is a widget; otherwise returns false . | |
bool | isWindowType () const |
Returns true if the object is a window; otherwise returns false . | |
bool | isQuickItemType () const |
Returns true if the object is a QQuickItem; otherwise returns false . | |
bool | signalsBlocked () const noexcept |
Returns true if signals are blocked; otherwise returns false . | |
bool | blockSignals (bool b) noexcept |
If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). | |
QThread * | thread () const |
Returns the thread in which the object lives. | |
bool | moveToThread (QThread *thread QT6_DECL_NEW_OVERLOAD_TAIL) |
Changes the thread affinity for this object and its children and returns true on success. | |
int | startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer) |
This is an overloaded function that will start a timer of type timerType and a timeout of interval milliseconds. | |
int | startTimer (std::chrono::nanoseconds time, Qt::TimerType timerType=Qt::CoarseTimer) |
void | killTimer (int id) |
Kills the timer with timer identifier, id. | |
void | killTimer (Qt::TimerId id) |
template<typename T > | |
T | findChild (QAnyStringView aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const |
Returns the child of this object that can be cast into type T and that is called name, or \nullptr if there is no such object. | |
template<typename T > | |
QList< T > | findChildren (QAnyStringView aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) 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. | |
template<typename T > | |
T | findChild (Qt::FindChildOptions options=Qt::FindChildrenRecursively) const |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. | |
template<typename T > | |
QList< T > | findChildren (Qt::FindChildOptions options=Qt::FindChildrenRecursively) const |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. | |
const QObjectList & | children () const |
Returns a list of child objects. | |
void | setParent (QObject *parent) |
Makes the object a child of parent. | |
void | installEventFilter (QObject *filterObj) |
Installs an event filter filterObj on this object. | |
void | removeEventFilter (QObject *obj) |
Removes an event filter object obj from this object. | |
QMetaObject::Connection | connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const |
bool | disconnect (const char *signal=nullptr, const QObject *receiver=nullptr, const char *member=nullptr) const |
bool | disconnect (const QObject *receiver, const char *member=nullptr) const |
void | dumpObjectTree () const |
Dumps a tree of children to the debug output. | |
void | dumpObjectInfo () const |
Dumps information about signal connections, etc. | |
bool | setProperty (const char *name, const QVariant &value) |
Sets the value of the object's name property to value. | |
bool | setProperty (const char *name, QVariant &&value) |
QVariant | property (const char *name) const |
Returns the value of the object's name property. | |
QList< QByteArray > | dynamicPropertyNames () const |
QBindingStorage * | bindingStorage () |
const QBindingStorage * | bindingStorage () const |
QObject * | parent () const |
Returns a pointer to the parent object. | |
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 . | |
Additional Inherited Members | |
Public Slots inherited from QObject | |
void | deleteLater () |
\threadsafe | |
Static Public Member Functions inherited from QObject | |
static QMetaObject::Connection | connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection) |
\threadsafe | |
static QMetaObject::Connection | connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection) |
template<typename Func1 , typename Func2 > | |
static QMetaObject::Connection | connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::ContextTypeForFunctor< Func2 >::ContextType *context, Func2 &&slot, Qt::ConnectionType type=Qt::AutoConnection) |
template<typename Func1 , typename Func2 > | |
static QMetaObject::Connection | connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, Func2 &&slot) |
static bool | disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member) |
\threadsafe | |
static bool | disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member) |
static bool | disconnect (const QMetaObject::Connection &) |
Disconnect a connection. | |
template<typename Func1 , typename Func2 > | |
static bool | disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::FunctionPointer< Func2 >::Object *receiver, Func2 slot) |
template<typename Func1 > | |
static bool | disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const QObject *receiver, void **zero) |
Protected Member Functions inherited from QObject | |
QObject * | sender () const |
Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns \nullptr. | |
int | senderSignalIndex () const |
int | receivers (const char *signal) const |
Returns the number of receivers connected to the signal. | |
bool | isSignalConnected (const QMetaMethod &signal) const |
virtual void | timerEvent (QTimerEvent *event) |
This event handler can be reimplemented in a subclass to receive timer events for the object. | |
virtual void | childEvent (QChildEvent *event) |
This event handler can be reimplemented in a subclass to receive child events. | |
virtual void | customEvent (QEvent *event) |
This event handler can be reimplemented in a subclass to receive custom events. | |
virtual void | connectNotify (const QMetaMethod &signal) |
virtual void | disconnectNotify (const QMetaMethod &signal) |
QObject (QObjectPrivate &dd, QObject *parent=nullptr) | |
Protected Attributes inherited from QObject | |
QScopedPointer< QObjectData > | d_ptr |
Properties inherited from QObject | |
QString | objectName |
the name of this object | |
Related Symbols inherited from QObject | |
template< class T > T | qobject_cast (const QObject *object) |
Returns the given object cast to type T if the object is of type T (or of a subclass); otherwise returns \nullptr. | |
template< typename T > T | qFindChildqFindChildren (const QObject *obj, const QString &name)() |
template< typename T > QList< T > | qFindChildrenqFindChildren (const QObject *obj, const QString &name)() |
QObjectList | |
\macro Q_CLASSINFO(Name, Value) | |
This class provides encryption for UDP sockets.
\inmodule QtNetwork
The QDtls class can be used to establish a secure connection with a network peer using User Datagram Protocol (UDP). DTLS connection over essentially connectionless UDP means that two peers first have to successfully complete a TLS handshake by calling doHandshake(). After the handshake has completed, encrypted datagrams can be sent to the peer using writeDatagramEncrypted(). Encrypted datagrams coming from the peer can be decrypted by decryptDatagram().
QDtls is designed to work with QUdpSocket. Since QUdpSocket can receive datagrams coming from different peers, an application must implement demultiplexing, forwarding datagrams coming from different peers to their corresponding instances of QDtls. An association between a network peer and its QDtls object can be established using the peer's address and port number. Before starting a handshake, the application must set the peer's address and port number using setPeer().
QDtls does not read datagrams from QUdpSocket, this is expected to be done by the application, for example, in a slot attached to the QUdpSocket::readyRead() signal. Then, these datagrams must be processed by QDtls.
Normally, several datagrams are to be received and sent by both peers during the handshake phase. Upon reading datagrams, server and client must pass these datagrams to doHandshake() until some error is found or handshakeState() returns HandshakeComplete:
For a server, the first call to doHandshake() requires a non-empty datagram containing a ClientHello message. If the server also deploys QDtlsClientVerifier, the first ClientHello message is expected to be the one verified by QDtlsClientVerifier.
In case the peer's identity cannot be validated during the handshake, the application must inspect errors returned by peerVerificationErrors() and then either ignore errors by calling ignoreVerificationErrors() or abort the handshake by calling abortHandshake(). If errors were ignored, the handshake can be resumed by calling resumeHandshake().
After the handshake has been completed, datagrams can be sent to and received from the network peer securely:
A DTLS connection may be closed using shutdown().
If the server does not use QDtlsClientVerifier, it must configure its QDtls objects to disable the cookie verification procedure:
A server that uses cookie verification with non-default generator parameters must set the same parameters for its QDtls object before starting the handshake.
The \l{secureudpserver}{DTLS server} and \l{secureudpclient}{DTLS client} examples illustrate how to use QDtls in applications.
Describes the current state of DTLS handshake.
\inmodule QtNetwork
This enum describes the current state of DTLS handshake for a QDtls connection.
\value HandshakeNotStarted Nothing done yet. \value HandshakeInProgress Handshake was initiated and no errors were found so far. \value PeerVerificationFailed The identity of the peer can't be established. \value HandshakeComplete Handshake completed successfully and encrypted connection was established.
Enumerator | |
---|---|
HandshakeNotStarted | |
HandshakeInProgress | |
PeerVerificationFailed | |
HandshakeComplete |
|
explicit |
Creates a QDtls object, parent is passed to the QObject constructor.
mode is QSslSocket::SslServerMode for a server-side DTLS connection or QSslSocket::SslClientMode for a client.
bool QDtls::abortHandshake | ( | QUdpSocket * | socket | ) |
Aborts the ongoing handshake.
Returns true if one was on-going on socket; otherwise, sets a suitable error and returns false.
QDtls::GeneratorParameters QDtls::cookieGeneratorParameters | ( | ) | const |
Returns the current hash algorithm and secret, either default ones or previously set by a call to setCookieGeneratorParameters().
The default hash algorithm is QCryptographicHash::Sha256 if Qt was configured to support it, QCryptographicHash::Sha1 otherwise. The default secret is obtained from the backend-specific cryptographically strong pseudorandom number generator.
QByteArray QDtls::decryptDatagram | ( | QUdpSocket * | socket, |
const QByteArray & | dgram ) |
bool QDtls::doHandshake | ( | QUdpSocket * | socket, |
const QByteArray & | dgram = {} ) |
Starts or continues a DTLS handshake.
socket must be a valid pointer. When starting a server-side DTLS handshake, dgram must contain the initial ClientHello message read from QUdpSocket. This function returns true
if no error was found. Handshake state can be tested using handshakeState(). false
return means some error occurred, use dtlsError() for more detailed information.
QSslConfiguration QDtls::dtlsConfiguration | ( | ) | const |
Returns either the default DTLS configuration or the configuration set by an earlier call to setDtlsConfiguration().
QDtlsError QDtls::dtlsError | ( | ) | const |
Returns the last error encountered by the connection or QDtlsError::NoError.
QString QDtls::dtlsErrorString | ( | ) | const |
Returns a textual description for the last error encountered by the connection or empty string.
bool QDtls::handleTimeout | ( | QUdpSocket * | socket | ) |
If a timeout occurs during the handshake, the handshakeTimeout() signal is emitted.
The application must call handleTimeout() to retransmit handshake messages; handleTimeout() returns true
if a timeout has occurred, false otherwise. socket must be a valid pointer.
QDtls::HandshakeState QDtls::handshakeState | ( | ) | const |
Returns the current handshake state for this QDtls.
|
signal |
Packet loss can result in timeouts during the handshake phase.
In this case QDtls emits a handshakeTimeout() signal. Call handleTimeout() to retransmit the handshake messages:
This method tells QDtls to ignore only the errors given in errorsToIgnore.
If, for instance, you want to connect to a server that uses a self-signed certificate, consider the following snippet:
You can also call this function after doHandshake() encountered the QDtlsError::PeerVerificationError error, and then resume the handshake by calling resumeHandshake().
Later 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.
bool QDtls::isConnectionEncrypted | ( | ) | const |
Returns true
if DTLS handshake completed successfully.
quint16 QDtls::mtuHint | ( | ) | const |
QHostAddress QDtls::peerAddress | ( | ) | const |
Returns the peer's address, set by setPeer(), or QHostAddress::Null.
quint16 QDtls::peerPort | ( | ) | const |
Returns errors found while establishing the identity of the peer.
If you want to continue connecting despite the errors that have occurred, you must call ignoreVerificationErrors().
QString QDtls::peerVerificationName | ( | ) | const |
Returns the host name set by setPeer() or setPeerVerificationName().
The default value is an empty string.
|
signal |
QDtls emits this signal when it negotiates a PSK ciphersuite, and therefore a PSK authentication is then required.
When using PSK, the client must send to the server a valid identity and a valid pre shared key, in order for the TLS handshake to continue. Applications can provide this information in a slot connected to this signal, by filling in the passed authenticator object according to their needs.
bool QDtls::resumeHandshake | ( | QUdpSocket * | socket | ) |
If peer verification errors were ignored during the handshake, resumeHandshake() resumes and completes the handshake and returns true
.
socket must be a valid pointer. Returns false
if the handshake could not be resumed.
QSslCipher QDtls::sessionCipher | ( | ) | const |
Returns the cryptographic \l {QSslCipher} {cipher} used by this connection, or a null cipher if the connection isn't encrypted.
The cipher for the session is selected during the handshake phase. The cipher is used to encrypt and decrypt data.
QSslConfiguration provides functions for setting the ordered list of ciphers from which the handshake phase will eventually select the session cipher. This ordered list must be in place before the handshake phase begins.
QSsl::SslProtocol QDtls::sessionProtocol | ( | ) | const |
Returns the DTLS protocol version used by this connection, or UnknownProtocol if the connection isn't encrypted yet.
The protocol for the connection is selected during the handshake phase.
setDtlsConfiguration() can set the preferred version before the handshake starts.
bool QDtls::setCookieGeneratorParameters | ( | const GeneratorParameters & | params | ) |
Sets the cryptographic hash algorithm and the secret from params.
This function is only needed for a server-side QDtls connection. Returns true
if successful.
bool QDtls::setDtlsConfiguration | ( | const QSslConfiguration & | configuration | ) |
Sets the connection's TLS configuration from configuration and returns true
if successful.
mtuHint is the maximum transmission unit (MTU), either discovered or guessed by the application.
The application is not required to set this value.
bool QDtls::setPeer | ( | const QHostAddress & | address, |
quint16 | port, | ||
const QString & | verificationName = {} ) |
Sets the peer's address, port, and host name and returns true
if successful.
address must not be null, multicast, or broadcast. verificationName is the host name used for the certificate validation.
bool QDtls::setPeerVerificationName | ( | const QString & | name | ) |
Sets the host name that will be used for the certificate validation and returns true
if successful.
bool QDtls::shutdown | ( | QUdpSocket * | socket | ) |
Sends an encrypted shutdown alert message and closes the DTLS connection.
Handshake state changes to QDtls::HandshakeNotStarted. socket must be a valid pointer. This function returns true
on success.
QSslSocket::SslMode QDtls::sslMode | ( | ) | const |
Returns QSslSocket::SslServerMode for a server-side connection and QSslSocket::SslClientMode for a client.
qint64 QDtls::writeDatagramEncrypted | ( | QUdpSocket * | socket, |
const QByteArray & | dgram ) |
Encrypts dgram and writes the encrypted data into socket.
Returns the number of bytes written, or -1 in case of error. The handshake must be completed before writing encrypted data. socket must be a valid pointer.