forked from kslotay/p2p-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cc
583 lines (442 loc) · 14.7 KB
/
main.cc
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
#include <unistd.h>
#include <QVBoxLayout>
#include <QApplication>
#include <QDebug>
#include <QDateTime>
#include "main.hh"
state currentState;
ChatDialog::ChatDialog()
{
// Read-only text box where we display messages from everyone.
// This widget expands both horizontally and vertically.
textview = new QTextEdit(this);
textview->setReadOnly(true);
// Small text-entry box the user can enter messages.
// This widget normally expands only horizontally,
// leaving extra vertical space for the textview widget.
//
// You might change this into a read/write QTextEdit,
// so that the user can easily enter multi-line messages.
textline = new QLineEdit(this);
// Lay out the widgets to appear in the main window.
// For Qt widget and layout concepts see:
// http://doc.qt.nokia.com/4.7-snapshot/widgets-and-layouts.html
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(textview);
layout->addWidget(textline);
setLayout(layout);
// Create a UDP network socket
sock = new NetSocket();
if (!sock->bind())
exit(1);
qsrand((uint) QDateTime::currentMSecsSinceEpoch());
QString myOrigin;
myOrigin = QString::number(qrand());
local_origin = myOrigin;
setWindowTitle(local_origin);
// // Initialize timer for message timeout
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(timeoutHandler()));
QTimer *antiEntropyTimer = new QTimer(this);
connect(antiEntropyTimer, SIGNAL(timeout()), this, SLOT(antiEntropyHandler()));
qDebug() << "Starting ANTIENTROPY timer";
antiEntropyTimer->start(5000);
// Initialize user-defined variables
currentSeqNum = 1;
pingList = sock->PeerList();
qDebug() << "LOCAL ORIGIN: " << local_origin;
// set waiting for a status to 0 (false) since instance just launched
currentState.waitingForStatus = 0;
// Register a callback on the textline's returnPressed signal
// so that we can send the message entered by the user.
connect(textline, SIGNAL(returnPressed()),
this, SLOT(gotReturnPressed()));
// Callback fired when message is received
connect(sock, SIGNAL(readyRead()), this, SLOT(readPendingMessages()));
Ping();
}
void ChatDialog::readPendingMessages()
{
while (sock->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(sock->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
sock->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
qDebug() << "\nRECEIVING MESSAGE";
processIncomingData(datagram, sender, senderPort);
}
}
void ChatDialog::processReceivedMessage(QMap<QString, QVariant> messageReceived, QHostAddress sender, quint16 senderPort)
{
QString msg_origin = messageReceived.value("Origin").toString();
quint32 msg_seqnum = messageReceived.value("SeqNo").toUInt();
// If localStatusMap[msg_origin] = 0, this is a new peer not on list
// Set expected msg_num to 1 for comparison
if (localStatusMap.value(msg_origin) == 0) {
localStatusMap[msg_origin] = 1;
}
// Modify localStatusMap before executing sendStatusMessage
// If origin already in localStatusMap, seqno+1
if (localStatusMap.value(msg_origin) == msg_seqnum) {
messageList[msg_origin][msg_seqnum] = messageReceived;
localStatusMap[msg_origin] = msg_seqnum+1;
// Show in chatdialog textview
textview->append(msg_origin + ": " + messageReceived.value("ChatText").toString());
// TODO: Forward message to random peer (not including one received from)
sendRandomMessage(serializeMessage(messageReceived));
}
else if (localStatusMap.value(msg_origin) > msg_seqnum) {
// If expected message number greater than one being received
// Message has already been seen, ignore
qDebug() << "message already seen: " << msg_seqnum;
}
else {
qDebug() << "waiting for msg with msgnum: " << localStatusMap.value(msg_origin);
}
sendStatusMessage(sender, senderPort);
}
void ChatDialog::processStatusMessage(QMap<QString, QMap<QString, quint32>> peerWantMap, QHostAddress sender, quint16 senderPort) {
QMap<QString, QVariant> messageToSend;
// Unwrap peerWant
QMap<QString, quint32> peerStatusMap = peerWantMap.value("Want");
// Create enum for differences in status
enum Status {INSYNC, AHEAD, BEHIND};
qDebug() << "\nmessage contains want:" << peerStatusMap;
// check if the want matches the one we are waiting an ACK for
if (currentState.waitingForStatus == 1) {
if (last_message_sent.contains(senderPort)) {
QString lms_origin = last_message_sent[senderPort].value("Origin").toString();
quint32 lms_seqno = last_message_sent[senderPort].value("SeqNo").toUInt();
if ((peerStatusMap.contains(lms_origin)) && (peerStatusMap[lms_origin] == lms_seqno+1)) {
last_message_sent.remove(senderPort);
currentState.waitingForStatus = 0;
qDebug() << "in processstatusmessage about to stop timer";
timer->stop();
}
}
}
// Set initial status
Status status = INSYNC;
// Compare statusMaps using localStatus keys
for (auto originKey : localStatusMap.keys()) {
if (!peerStatusMap.contains(originKey)){
status = AHEAD;
// Add message to message buffer from messageList
messageToSend = messageList[originKey][1];
break;
}
else if (peerStatusMap.value(originKey) < localStatusMap.value(originKey)) {
status = AHEAD;
// Add message to message buffer from messageList
messageToSend = messageList[originKey][peerStatusMap.value(originKey)];
break;
}
else if (peerStatusMap.value(originKey) > localStatusMap.value(originKey)) {
// Send status message
status = BEHIND;
break;
}
}
// Check for keys in peerStatusMap that are not in localStatusMap
for (auto originKey : peerStatusMap.keys()) {
if (!localStatusMap.contains(originKey)){
status = BEHIND;
break;
}
}
switch (status) {
case INSYNC:
// Coin flip and randomly send, or stop
srand(time(0));
int coin_flip;
coin_flip = (qrand() % 2);
qDebug() << "[INSYNC]";
if(coin_flip) {
pickNeighboring();
int index = qrand() % neighborList.size();
qDebug() << "COIN FLIP ABOUT TO SEND";
sendStatusMessage(QHostAddress::LocalHost, neighborList[index]);
}
break;
case AHEAD:
qDebug() << "[AHEAD] about to send MESSAGE";
sendMessage(serializeMessage(messageToSend), senderPort);
break;
case BEHIND:
qDebug() << "[BEHIND] about to send STATUS";
sendStatusMessage(sender, senderPort);
break;
}
}
void ChatDialog::processPingMessage(QHostAddress sender, quint16 senderPort) {
// Send ping reply
sendPingReply(sender, senderPort);
}
void ChatDialog::processPingReply(quint16 senderPort) {
// Check timer, add to pingTimes, and remove port from pingList
quint16 pingTime = pingTimer.elapsed();
pingTimes[senderPort] = pingTime;
pingList.removeOne(senderPort);
QList<quint16> peerList;
int index;
if (neighborList.size() == 2) {
switch (pingTimes.size()) {
case 1:
for (quint16 port : pingTimes.keys()) {
neighborList.append(port);
}
peerList = sock->PeerList();
peerList.removeOne(neighborList[0]);
index = (rand() % peerList.size());
neighborList.append(peerList[index]);
break;
case 2:
for (quint16 port : pingTimes.keys()) {
neighborList.append(port);
}
break;
default:
QList<int> ping_rtt;
QList<quint16> ports;
ping_rtt = pingTimes.values();
ports = pingTimes.keys();
qSort(ping_rtt);
pingTimes.clear();
QList<int>::iterator i;
QList<short unsigned int>::iterator j;
i = ping_rtt.begin();
j = ports.begin();
// insert back the sorted values and map them to keys in QMap container
while(i != ping_rtt.end() && j != ports.end()){
pingTimes.insert(*j, *i);
i++;
j++;
}
for (quint16 port : pingTimes.keys()) {
if (neighborList.size() < 2) {
neighborList.append(port);
}
}
break;
}
}
}
// Process the message read from pending messages from sock
void ChatDialog::processIncomingData(QByteArray datagramReceived, QHostAddress sender, quint16 senderPort)
{
// Stream for both msg and want, as stream is emptied on read
QMap<QString, QVariant> messageReceived;
QDataStream stream_msg(&datagramReceived, QIODevice::ReadOnly);
stream_msg >> messageReceived;
QMap<QString, QMap<QString, quint32>> peerWantMap;
QDataStream stream_want(&datagramReceived, QIODevice::ReadOnly);
stream_want >> peerWantMap;
QMap<QString, QString> pingMap;
QDataStream stream_ping(&datagramReceived, QIODevice::ReadOnly);
stream_ping >> pingMap;
// if we are still waiting for an ACK ignore everything else
// currentState.waitingForStatus == 0
if (messageReceived.contains("ChatText")) {
qDebug() << "messageReceived: " << messageReceived["ChatText"];
processReceivedMessage(messageReceived, sender, senderPort);
}
else if (peerWantMap.contains("Want")) {
qDebug() << "wantMap: " << peerWantMap["Want"];
processStatusMessage(peerWantMap, sender, senderPort);
}
else if (pingMap.contains("Ping")) {
processPingMessage(sender, senderPort);
}
else if (pingMap.contains("PingReply")) {
processPingReply(senderPort);
}
}
QByteArray ChatDialog::serializeLocalMessage(QString messageText)
{
QVariantMap messageMap;
messageMap.insert("ChatText", messageText);
messageMap.insert("Origin", local_origin);
messageMap.insert("SeqNo", currentSeqNum);
messageList[local_origin][currentSeqNum] = messageMap;
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::ReadWrite);
stream << messageMap;
return buffer;
}
QByteArray ChatDialog::serializeMessage(QMap<QString, QVariant> messageToSend)
{
QVariantMap messageMap;
messageMap.insert("ChatText", messageToSend.value("ChatText"));
messageMap.insert("Origin", messageToSend.value("Origin"));
messageMap.insert("SeqNo", messageToSend.value("SeqNo"));
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::ReadWrite);
stream << messageMap;
return buffer;
}
void ChatDialog::timeoutHandler()
{
qDebug() << "TIMEOUT OCCURED!!!";
for (auto portNumber : last_message_sent.keys()) {
sendMessage(serializeMessage(last_message_sent[portNumber]), portNumber);
currentState.waitingForStatus = 0;
}
timer->stop();
}
void ChatDialog::antiEntropyHandler()
{
qDebug() << "ANTIENTROPY kicked in";
QList<quint16> peerList = sock->PeerList();
int index = rand() % peerList.size();
sendStatusMessage(QHostAddress::LocalHost, peerList[index]);
}
void ChatDialog::gotReturnPressed()
{
QString text = textline->text();
textview->append(local_origin + ": " + textline->text());
// Append to localStatusMap
localStatusMap[local_origin] = currentSeqNum+1;
// about to send message so set current waitingForStatus to true
currentState.waitingForStatus = 1;
// about to send a message from chat diaglog, start a timer
timer->start(1000);
sendRandomMessage(serializeLocalMessage(text));
// If local message being forwarded, increment, else don't
currentSeqNum++;
// Clear the textline to get ready for the next input message.
textline->clear();
}
void ChatDialog::pickNeighboring() {
QList<quint16> peerList;
int index;
peerList = sock->PeerList();
if (neighborList.size() == 0) {
index = rand() % peerList.size();
neighborList.append(peerList[index]);
peerList.removeOne(peerList[index]);
index = rand() % peerList.size();
neighborList.append(peerList[index]);
}
}
void ChatDialog::sendMessage(QByteArray buffer, quint16 senderPort)
{
qDebug() << "Sending to port: " << senderPort;
sock->writeDatagram(buffer, buffer.size(), QHostAddress::LocalHost, senderPort);
// save last message sent to be resend on timeout
cacheLastSentMessage(senderPort, buffer);
}
void ChatDialog::sendRandomMessage(QByteArray buffer)
{
int index;
pickNeighboring();
qDebug() << "Neighbor List: " << neighborList;
index = rand() % neighborList.size();
sendMessage(buffer, neighborList[index]);
}
void ChatDialog::cacheLastSentMessage(quint16 peerPort, QByteArray buffer)
{
QMap<QString, QVariant> lastMessageSentMap;
QDataStream stream(&buffer, QIODevice::ReadOnly);
stream >> lastMessageSentMap;
last_message_sent[peerPort] = lastMessageSentMap;
}
void ChatDialog::sendPingMessage(QHostAddress sendto, quint16 port)
{
QByteArray ping;
QDataStream stream(&ping, QIODevice::ReadWrite);
QMap<QString, QString> pingMsg;
pingMsg["Ping"] = "Ping";
stream << pingMsg;
sock->writeDatagram(ping, ping.size(), sendto, port);
}
void ChatDialog::sendPingReply(QHostAddress sendto, quint16 port)
{
QByteArray pingreply;
QDataStream stream(&pingreply, QIODevice::ReadWrite);
QMap<QString, QString> pingReply;
pingReply["PingReply"] = "PingReply";
stream << pingReply;
sock->writeDatagram(pingreply, pingreply.size(), sendto, port);
}
void ChatDialog::Ping() {
int attempts = 3;
while (attempts > 0) {
if(neighborList.size() == 2) {
break;
}
int timeout = 1000;
if(pingTimer.elapsed() > 0) {
pingTimer.restart();
}
else {
pingTimer.start();
}
for (int i = 0; i < pingList.size(); i++) {
sendPingMessage(QHostAddress::LocalHost, pingList[i]);
}
int remainingTime = timeout - pingTimer.elapsed();
while (remainingTime > 0) {
remainingTime = timeout - pingTimer.elapsed();
}
attempts--;
}
}
void ChatDialog::sendStatusMessage(QHostAddress sendto, quint16 port)
{
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::ReadWrite);
QMap<QString, QMap<QString, quint32>> statusMessage;
// Define message QMap
statusMessage["Want"] = localStatusMap;
qDebug() << "\nSending statusMessage: " << statusMessage;
qDebug() << "sending status to peer: " << port;
stream << statusMessage;
sock->writeDatagram(buffer, buffer.size(), sendto, port);
}
NetSocket::NetSocket()
{
// Pick a range of four UDP ports to try to allocate by default,
// computed based on my Unix user ID.
// This makes it trivial for up to four P2Papp instances per user
// to find each other on the same host,
// barring UDP port conflicts with other applications
// (which are quite possible).
// We use the range from 32768 to 49151 for this purpose.
myPortMin = 32768 + (getuid() % 4096)*4;
myPortMax = myPortMin + 3;
}
QList<quint16> NetSocket::PeerList()
{
QList<quint16> peerList;
for (int p = myPortMin; p <= myPortMax; p++) {
if (this->localPort() != p) {
peerList.append(p);
}
}
return peerList;
}
bool NetSocket::bind()
{
// Try to bind to each of the range myPortMin..myPortMax in turn.
for (int p = myPortMin; p <= myPortMax; p++) {
if (QUdpSocket::bind(p)) {
qDebug() << "bound to UDP port " << p;
return true;
}
}
qDebug() << "Oops, no ports in my default range " << myPortMin
<< "-" << myPortMax << " available";
return false;
}
int main(int argc, char **argv)
{
// Initialize Qt toolkit
QApplication app(argc,argv);
// Create an initial chat dialog window
ChatDialog dialog;
dialog.show();
// Enter the Qt main loop; everything else is event driven
return app.exec();
}