1/****************************************************************************
2**
3** Copyright (C) 2018 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the examples of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:BSD$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** BSD License Usage
18** Alternatively, you may use this file under the terms of the BSD license
19** as follows:
20**
21** "Redistribution and use in source and binary forms, with or without
22** modification, are permitted provided that the following conditions are
23** met:
24** * Redistributions of source code must retain the above copyright
25** notice, this list of conditions and the following disclaimer.
26** * Redistributions in binary form must reproduce the above copyright
27** notice, this list of conditions and the following disclaimer in
28** the documentation and/or other materials provided with the
29** distribution.
30** * Neither the name of The Qt Company Ltd nor the names of its
31** contributors may be used to endorse or promote products derived
32** from this software without specific prior written permission.
33**
34**
35** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46**
47** $QT_END_LICENSE$
48**
49****************************************************************************/
50
51#include "association.h"
52
53QT_BEGIN_NAMESPACE
54
55DtlsAssociation::DtlsAssociation(const QHostAddress &address, quint16 port,
56 const QString &connectionName)
57 : name(connectionName),
58 crypto(QSslSocket::SslClientMode)
59{
60 //! [1]
61 auto configuration = QSslConfiguration::defaultDtlsConfiguration();
62 configuration.setPeerVerifyMode(QSslSocket::VerifyNone);
63 crypto.setPeer(address, port);
64 crypto.setDtlsConfiguration(configuration);
65 //! [1]
66
67 //! [2]
68 connect(sender: &crypto, signal: &QDtls::handshakeTimeout, receiver: this, slot: &DtlsAssociation::handshakeTimeout);
69 //! [2]
70 connect(sender: &crypto, signal: &QDtls::pskRequired, receiver: this, slot: &DtlsAssociation::pskRequired);
71 //! [3]
72 socket.connectToHost(hostName: address.toString(), port);
73 //! [3]
74 //! [13]
75 connect(sender: &socket, signal: &QUdpSocket::readyRead, receiver: this, slot: &DtlsAssociation::readyRead);
76 //! [13]
77 //! [4]
78 pingTimer.setInterval(5000);
79 connect(sender: &pingTimer, signal: &QTimer::timeout, receiver: this, slot: &DtlsAssociation::pingTimeout);
80 //! [4]
81}
82
83//! [12]
84DtlsAssociation::~DtlsAssociation()
85{
86 if (crypto.isConnectionEncrypted())
87 crypto.shutdown(socket: &socket);
88}
89//! [12]
90
91//! [5]
92void DtlsAssociation::startHandshake()
93{
94 if (socket.state() != QAbstractSocket::ConnectedState) {
95 emit infoMessage(message: tr(s: "%1: connecting UDP socket first ...").arg(a: name));
96 connect(sender: &socket, signal: &QAbstractSocket::connected, receiver: this, slot: &DtlsAssociation::udpSocketConnected);
97 return;
98 }
99
100 if (!crypto.doHandshake(socket: &socket))
101 emit errorMessage(message: tr(s: "%1: failed to start a handshake - %2").arg(args&: name, args: crypto.dtlsErrorString()));
102 else
103 emit infoMessage(message: tr(s: "%1: starting a handshake").arg(a: name));
104}
105//! [5]
106
107void DtlsAssociation::udpSocketConnected()
108{
109 emit infoMessage(message: tr(s: "%1: UDP socket is now in ConnectedState, continue with handshake ...").arg(a: name));
110 startHandshake();
111}
112
113void DtlsAssociation::readyRead()
114{
115 if (socket.pendingDatagramSize() <= 0) {
116 emit warningMessage(message: tr(s: "%1: spurious read notification?").arg(a: name));
117 return;
118 }
119
120 //! [6]
121 QByteArray dgram(socket.pendingDatagramSize(), Qt::Uninitialized);
122 const qint64 bytesRead = socket.readDatagram(data: dgram.data(), maxlen: dgram.size());
123 if (bytesRead <= 0) {
124 emit warningMessage(message: tr(s: "%1: spurious read notification?").arg(a: name));
125 return;
126 }
127
128 dgram.resize(size: bytesRead);
129 //! [6]
130 //! [7]
131 if (crypto.isConnectionEncrypted()) {
132 const QByteArray plainText = crypto.decryptDatagram(socket: &socket, dgram);
133 if (plainText.size()) {
134 emit serverResponse(clientInfo: name, datagraam: dgram, plainText);
135 return;
136 }
137
138 if (crypto.dtlsError() == QDtlsError::RemoteClosedConnectionError) {
139 emit errorMessage(message: tr(s: "%1: shutdown alert received").arg(a: name));
140 socket.close();
141 pingTimer.stop();
142 return;
143 }
144
145 emit warningMessage(message: tr(s: "%1: zero-length datagram received?").arg(a: name));
146 } else {
147 //! [7]
148 //! [8]
149 if (!crypto.doHandshake(socket: &socket, dgram)) {
150 emit errorMessage(message: tr(s: "%1: handshake error - %2").arg(args&: name, args: crypto.dtlsErrorString()));
151 return;
152 }
153 //! [8]
154
155 //! [9]
156 if (crypto.isConnectionEncrypted()) {
157 emit infoMessage(message: tr(s: "%1: encrypted connection established!").arg(a: name));
158 pingTimer.start();
159 pingTimeout();
160 } else {
161 //! [9]
162 emit infoMessage(message: tr(s: "%1: continuing with handshake ...").arg(a: name));
163 }
164 }
165}
166
167//! [11]
168void DtlsAssociation::handshakeTimeout()
169{
170 emit warningMessage(message: tr(s: "%1: handshake timeout, trying to re-transmit").arg(a: name));
171 if (!crypto.handleTimeout(socket: &socket))
172 emit errorMessage(message: tr(s: "%1: failed to re-transmit - %2").arg(args&: name, args: crypto.dtlsErrorString()));
173}
174//! [11]
175
176//! [14]
177void DtlsAssociation::pskRequired(QSslPreSharedKeyAuthenticator *auth)
178{
179 Q_ASSERT(auth);
180
181 emit infoMessage(message: tr(s: "%1: providing pre-shared key ...").arg(a: name));
182 auth->setIdentity(name.toLatin1());
183 auth->setPreSharedKey(QByteArrayLiteral("\x1a\x2b\x3c\x4d\x5e\x6f"));
184}
185//! [14]
186
187//! [10]
188void DtlsAssociation::pingTimeout()
189{
190 static const QString message = QStringLiteral("I am %1, please, accept our ping %2");
191 const qint64 written = crypto.writeDatagramEncrypted(socket: &socket, dgram: message.arg(a: name).arg(a: ping).toLatin1());
192 if (written <= 0) {
193 emit errorMessage(message: tr(s: "%1: failed to send a ping - %2").arg(args&: name, args: crypto.dtlsErrorString()));
194 pingTimer.stop();
195 return;
196 }
197
198 ++ping;
199}
200//! [10]
201
202QT_END_NAMESPACE
203

source code of qtbase/examples/network/secureudpclient/association.cpp