-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathdiscovery.cpp
258 lines (232 loc) · 7.63 KB
/
discovery.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#include <QtCore/qdatastream.h>
#include <QtCore/qloggingcategory.h>
#include "discovery.h"
#include "peer.h"
static Q_LOGGING_CATEGORY(logger, "lafdup.discovery") using namespace qtng;
const quint16 DefaultPort = 7951;
const quint16 MagicNumber = DefaultPort;
const quint8 CurrentVersion = 1;
LafdupKcpSocket::LafdupKcpSocket(LafdupDiscovery *parent)
: KcpSocket(HostAddress::IPv4Protocol)
, parent(parent)
{
}
bool LafdupKcpSocket::filter(char *data, qint32 *len, HostAddress *addr, quint16 *port)
{
const QByteArray &packet = QByteArray::fromRawData(data, *len);
if (packet.startsWith("\x1f\x0f")) { // MagicCode
parent->handleDiscoveryRequest(packet, *addr, *port);
return true;
}
if (packet.startsWith("\xcd\x1f\x0f")) { // packet previous version sent.
return true;
}
return false;
}
LafdupDiscovery::LafdupDiscovery(const QByteArray &uuid, quint16 port, LafdupPeer *parent)
: operations(new CoroutineGroup())
, uuid(uuid)
, parent(parent)
, port(port)
{
kcpSocket.reset(new LafdupKcpSocket(this));
kcpSocket->setOption(Socket::BroadcastSocketOption, true);
}
LafdupDiscovery::~LafdupDiscovery()
{
delete operations;
}
bool LafdupDiscovery::start()
{
if (operations->has("serve")) {
if (Q_UNLIKELY(kcpSocket->state() != Socket::ListeningState)) {
qCWarning(logger) << "invalid peer state, kcp socket is dead.";
}
if (Q_UNLIKELY(!operations->has("discovery"))) {
qCWarning(logger) << "invalid peer state, discovery coroutine is dead.";
}
return true;
}
if (!kcpSocket->bind(port)) {
return false;
}
kcpSocket->listen(50);
operations->spawnWithName("serve", [this] { serve(); });
operations->spawnWithName("discovery", [this] { discovery(); });
return true;
}
void LafdupDiscovery::stop()
{
operations->killall();
kcpSocket.reset(new LafdupKcpSocket(this));
}
void LafdupDiscovery::setExtraKnownPeers(const QSet<QPair<HostAddress, quint16>> &extraKnownPeers)
{
this->extraKnownPeers = extraKnownPeers;
}
QSet<QPair<HostAddress, quint16>> LafdupDiscovery::getExtraKnownPeers()
{
return extraKnownPeers;
}
QSet<HostAddress> getMyIPs()
{
QSet<HostAddress> addresses;
for (const HostAddress &addr : NetworkInterface::allAddresses()) {
addresses.insert(addr);
}
return addresses;
}
QStringList LafdupDiscovery::getAllBoundAddresses()
{
QStringList addresses;
for (const HostAddress &addr : NetworkInterface::allAddresses()) {
if (!addr.isLoopback() && !addr.isMulticast() && addr.protocol() == HostAddress::IPv4Protocol) {
addresses.append(addr.toString());
}
}
return addresses;
}
quint16 LafdupDiscovery::getPort()
{
if (port == 0) {
return kcpSocket->localPort();
} else {
return port;
}
}
quint16 LafdupDiscovery::getDefaultPort()
{
return DefaultPort;
}
QByteArray LafdupDiscovery::getUuid()
{
return uuid;
}
void LafdupDiscovery::serve()
{
while (true) {
QSharedPointer<KcpSocket> request(kcpSocket->accept());
if (request.isNull()) {
return;
}
parent->tryToConnectPeer(request);
}
}
void LafdupDiscovery::handleDiscoveryRequest(const QByteArray &packet, HostAddress addr, quint16 port)
{
quint16 magicNumber;
quint8 version;
quint32 len;
QByteArray uuid;
QDataStream ds(packet);
ds >> magicNumber >> version >> len;
if (ds.status() != QDataStream::Ok) {
qCInfo(logger) << "got invalid discovery packet.";
return;
}
if (magicNumber != MagicNumber) {
qCInfo(logger) << "got datagram with bad magic number: " << magicNumber;
return;
}
if (version != CurrentVersion) {
qCInfo(logger) << "version" << version << "is unknown.";
return;
}
if (len > 64) {
qCInfo(logger) << "got datagram with bad uuid length: " << len;
return;
}
uuid.resize(static_cast<int>(len));
ds.readRawData(uuid.data(), static_cast<int>(len));
if (ds.status() != QDataStream::Ok) {
qCInfo(logger) << "got invalid discovery packet.";
return;
}
if (uuid.isEmpty()) {
qCInfo(logger) << "got datagram with empty uuid.";
return;
}
if (uuid == this->uuid) {
return;
}
const QString &peerName = QString::fromUtf8(uuid);
knownPeers.insert(peerName, qMakePair(addr, port));
if (parent->hasPeer(peerName)) {
return;
}
if (parent->hasPeer(addr, port)) {
return;
}
parent->tryToConnectPeer(peerName, addr, port);
}
static QSet<HostAddress> allBroadcastAddresses()
{
QSet<HostAddress> addresses;
addresses.insert(HostAddress::Broadcast);
for (const NetworkInterface &interface : NetworkInterface::allInterfaces()) {
for (const NetworkAddressEntry &entry : interface.addressEntries()) {
const HostAddress &addr = entry.broadcast();
if (!addr.isNull()) {
addresses.insert(addr);
}
}
}
return addresses;
}
void LafdupDiscovery::discovery()
{
QByteArray packet;
QDataStream ds(&packet, QIODevice::WriteOnly);
ds << DefaultPort << CurrentVersion << uuid;
if (ds.status() != QDataStream::Ok) {
qCCritical(logger) << "can not make discovery packet.";
return;
}
while (true) {
const QSet<HostAddress> &broadcastList = allBroadcastAddresses();
for (const HostAddress &addr : broadcastList) {
qint32 bs = kcpSocket->udpSend(packet, addr, DefaultPort);
if (bs != packet.size()) {
qCDebug(logger) << "can not send packet to" << addr << kcpSocket->errorString();
} else {
qCDebug(logger) << "send to broadcast address: " << addr.toString();
}
}
// prevent undefined behavior if addresses changed while broadcasting.
QHash<QString, QPair<HostAddress, quint16>> addresses = this->knownPeers;
for (const QString &peerName : addresses.keys()) {
const QPair<HostAddress, quint16> &addr = addresses.value(peerName);
if (parent->hasPeer(peerName)) {
continue;
}
if (parent->hasPeer(addr.first, addr.second)) {
continue;
}
qint32 bs = kcpSocket->udpSend(packet, addr.first, addr.second);
if (bs != packet.size()) {
qCDebug(logger) << "can not send packet to" << addr << kcpSocket->errorString();
} else {
qCDebug(logger) << "send to known peer: " << addr.first.toString() << ":" << addr.second;
}
}
// prevent undefined behavior if addresses changed while broadcasting.
QSet<QPair<HostAddress, quint16>> extraKnownPeers = this->extraKnownPeers;
for (const QPair<HostAddress, quint16> &extraKnownPeer : extraKnownPeers) {
if (knownPeers.values().contains(extraKnownPeer)) {
continue;
}
if (parent->hasPeer(extraKnownPeer.first, extraKnownPeer.second)) {
continue;
}
qint32 bs = kcpSocket->udpSend(packet, extraKnownPeer.first, extraKnownPeer.second);
if (bs != packet.size()) {
qCDebug(logger) << "can not send packet to" << extraKnownPeer.first.toString() << ":"
<< extraKnownPeer.second;
} else {
qCDebug(logger) << "send to extra known peer: " << extraKnownPeer.first.toString() << ":"
<< extraKnownPeer.second;
}
}
Coroutine::sleep(5.0);
}
}