-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cc
More file actions
1334 lines (918 loc) · 30.6 KB
/
main.cc
File metadata and controls
1334 lines (918 loc) · 30.6 KB
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <unistd.h>
#include <ctime>
#include <cstdlib>
#include <QApplication>
#include <QDebug>
#include <QKeyEvent>
#include <QTextStream>
#include <QtGlobal>
#include <QTime>
#include <QDateTime>
#include <QUuid>
#include <QListWidget>
#include <QtCrypto>
#include <QLabel>
#include "main.hh"
#include "router.hh"
#include "helper.hh"
#include "dispatcher.hh"
PaxosDialog::PaxosDialog(Router *r, const QList<QString> &participants)
{
paxos = new Paxos(participants);
valueDisplay = new QTextEdit(this);
valueDisplay->setReadOnly(true);
valueAdder = new QLineEdit(this);
QVBoxLayout *layout = new QVBoxLayout();
QLabel *learnedValues = new QLabel("Learned values:");
QLabel *commitValue = new QLabel("Commit a value:");
layout->addWidget(learnedValues);
layout->addWidget(valueDisplay);
layout->addWidget(commitValue);
layout->addWidget(valueAdder);
setLayout(layout);
valueAdder->setFocus();
// Connect our client to paxos.
connect(this, SIGNAL(newRequest(const QString&)),
paxos, SLOT(clientRequest(const QString&)));
connect(paxos, SIGNAL(newValue(quint32, const QString&)),
this, SLOT(newValue(quint32, const QString&)));
// Connect the router to paxos.
connect(paxos, SIGNAL(sendP2P(const QMap<QString, QVariant>&, const QString&)),
r, SLOT(sendMap(const QMap<QString, QVariant>&, const QString&)));
connect(r, SIGNAL(toPaxos(const QMap<QString, QVariant>&)),
paxos, SLOT(newMessage(const QMap<QString, QVariant>&)));
connect(valueAdder, SIGNAL(returnPressed()),
this, SLOT(gotReturnPressed()));
}
void
PaxosDialog::gotReturnPressed()
{
emit newRequest (valueAdder->text());
valueAdder->clear();
}
void
PaxosDialog::newValue(quint32 round,const QString& value)
{
QString toDisplay = QString::number(round, 10);
toDisplay += " :> ";
toDisplay += value;
valueDisplay->append(toDisplay);
}
FileDialog::FileDialog(FileRequests *fr)
{
m_fr = fr;
QLabel *entryLabel = new QLabel("Search here:");
QVBoxLayout *layout = new QVBoxLayout();
QHBoxLayout *innerLayout = new QHBoxLayout();
text = new QLineEdit(this);
innerLayout->addWidget(entryLabel);
innerLayout->addWidget(text);
fileButton = new QPushButton("Share File ...", this);
fileButton->setDown(false);
fileButton->setChecked(false);
layout->addLayout(innerLayout);
layout->addWidget(fileButton);
setLayout(layout);
connect(text, SIGNAL(returnPressed()),
this, SLOT(newSearch()));
connect(this, SIGNAL(newRequest(const QString&)),
fr, SLOT(newSearch(const QString&)));
connect(fr, SIGNAL(newResponse(const QString &, const QMap<QString, QVariant>&)),
this, SLOT(newSearchResult(const QString &, const QMap<QString, QVariant> &)));
connect(this, SIGNAL(destroyRequest(const QString &)),
fr, SLOT(destroyRequest(const QString &)));
connect(fileButton, SIGNAL(pressed()),
this, SLOT(fileButtonClicked()));
}
void
FileDialog::fileButtonClicked()
{
//qDebug() << "file button clicked\n";
// First disable the button from being
// clicked until we're done selecting files.
fileButton->setDown(true);
// Setup a new file menu.
fileMenu = new QFileDialog(this);
fileMenu->setFileMode(QFileDialog::ExistingFiles);
// Connect the signal for file selection to
// the corresponding slot.
connect(fileMenu, SIGNAL(filesSelected(const QStringList &)),
this, SLOT(filesSelected(const QStringList &)));
fileMenu->show();
}
void
FileDialog::filesSelected(const QStringList & files)
{
int len = files.count();
for(int i = 0; i < len; ++i)
qDebug() << files[i] << '\n';
//delete(fileMenu);
fileButton->setDown(false);
emit indexFiles(files);
}
void
FileDialog::newSearch()
{
QString query = text->text();
text->clear();
qDebug() << "New request!";
if (!activeRequests.contains(query)){
DownloadBox * newSearch = new DownloadBox(query);
activeRequests[query] = newSearch;
connect(newSearch, SIGNAL(download(const QString&, const QString&, const QByteArray&)),
m_fr, SLOT(newDownload(const QString&, const QString&, const QByteArray&)));
connect(newSearch, SIGNAL(close(const QString &)),
this, SLOT(closeBox(const QString& )));
newSearch->show();
emit newRequest(query);
}
}
void
FileDialog::newSearchResult(const QString &query, const QMap<QString, QVariant> &response)
{
if (activeRequests.contains(query)){
qDebug() << "FileDialog: got new search result for " << query;
DownloadBox *search = activeRequests[query];
search->newResult(response);
}
}
void
FileDialog::closeBox(const QString &query)
{
if (activeRequests.contains(query)){
qDebug() << "Killed window";
emit destroyRequest(query);
DownloadBox *searchBox = activeRequests[query];
activeRequests.remove(query);
delete(searchBox);
}
}
DownloadBox::DownloadBox(const QString& search)
{
m_search = search;
QString titleString = "Searching for... ";
titleString.append(search);
setWindowTitle(titleString);
results = new QListWidget();
layout = new QVBoxLayout();
layout->addWidget(results);
setLayout(layout);
connect(results, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
this, SLOT(gotDoubleClick(QListWidgetItem*)));
}
DownloadBox::~DownloadBox()
{
results->~QListWidget();
layout->~QVBoxLayout();
}
void
DownloadBox::newResult(const QMap<QString, QVariant> &msg)
{
qDebug() << "DownloadBox: got new search result" << msg["Name"].toString();
QListWidgetItem *item = new QListWidgetItem(msg["Name"].toString());
item->setData(1, msg);
results->addItem(item);
}
void
DownloadBox::gotDoubleClick(QListWidgetItem *item)
{
QMap<QString, QVariant> data = (item->data(1)).toMap();
qDebug() << "Start download!!!";
emit download(data["Name"].toString(),
data["Origin"].toString(),
data["ID"].toByteArray());
}
void
DownloadBox::closeEvent(QCloseEvent *e)
{
emit close(m_search);
}
// BEGIN: PrivateChatDialog
PrivateChatDialog::PrivateChatDialog(const QString& destination)
{
m_destination = destination;
setWindowTitle(destination);
textview = new QTextEdit(this);
textview->setReadOnly(true);
textentry = new QLineEdit(this);
textentry->setFocus();
layout = new QVBoxLayout();
layout->addWidget(textview);
layout->addWidget(textentry);
connect(textentry, SIGNAL(returnPressed()),
this, SLOT(internalMessageReceived()));
setLayout(layout);
}
PrivateChatDialog::~PrivateChatDialog()
{
textview->~QTextEdit();
textentry->~QLineEdit();
layout->~QVBoxLayout();
}
void
PrivateChatDialog::internalMessageReceived()
{
QString msg = textentry->text();
textview->append(msg);
emit sendMessage(msg, m_destination);
textentry->clear();
}
void
PrivateChatDialog::externalMessageReceived(const QString& msg)
{
textview->append(msg);
}
void
PrivateChatDialog::closeEvent(QCloseEvent *e)
{
emit closed(m_destination);
}
// END: PrivateChatDialog
// BEGIN: TextEntryWidget
TextEntryWidget::TextEntryWidget(QWidget * parent) : QTextEdit(parent)
{
}
void TextEntryWidget::keyPressEvent(QKeyEvent *e)
{
if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return){
emit returnPressed();
}
else{
QTextEdit::keyPressEvent(e);
}
}
// END: TextEntryWidget
// Begin: ChatDialog
ChatDialog::ChatDialog(Router *r)
{
router = r;
setWindowTitle("Peerster");
// 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 TextEntryWidget(this);
peerAdder = 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
QHBoxLayout *layout = new QHBoxLayout();
QVBoxLayout *innerLayout = new QVBoxLayout();
QVBoxLayout *innerLayout2 = new QVBoxLayout();
QLabel *addPeer = new QLabel("Add a neighbor:");
QLabel *typeHere = new QLabel("Type here for public chat:");
innerLayout->addWidget(addPeer);
innerLayout->addWidget(peerAdder);
innerLayout->addWidget(textview);
innerLayout->addWidget(typeHere);
innerLayout->addWidget(textline);
QLabel *originLabel = new QLabel("Double-click someone to private chat:");
origins = new QListWidget();
innerLayout2->addWidget(originLabel);
innerLayout2->addWidget(origins);
layout->addLayout(innerLayout);
layout->addLayout(innerLayout2);
setLayout(layout);
textline->setFocus();
// Register a callback on the textline's returnPressed signal
// so that we can send the message entered by the user.
connect(router, SIGNAL(newOrigin(const QString&)),
this, SLOT(addOrigin(const QString&)));
connect(textline, SIGNAL(returnPressed()),
this, SLOT(gotReturnPressed()));
connect(peerAdder, SIGNAL(returnPressed()),
this, SLOT(gotAddPeer()));
connect(origins, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
this, SLOT(openEmptyPrivateChat(QListWidgetItem*)));
}
void
ChatDialog::addOrigin(const QString& origin)
{
origins->addItem(origin);
}
void ChatDialog::gotAddPeer()
{
QString temp = peerAdder->text();
peerAdder->clear();
////qDebug() << "ChatDialog::gotAddPeer -- received request to add " << temp;
emit this->addPeer(temp);
}
void ChatDialog::gotReturnPressed()
{
// Initially, just echo the string locally.
// Insert some networking code here...
////qDebug() << "FIX: send message to other peers: " << textline->toPlainText();
//textview->append(textline->toPlainText());
emit this->sendMessage (textline->toPlainText());
// Clear the textline to get ready for the next input message.
textline->clear();
}
void ChatDialog::gotNewMessage(const QString& s)
{
////qDebug() << "ChatDialog::gotNewMessage -- ok, at least I get called" << '\n';
textview->append(s);
}
void ChatDialog::destroyPrivateWindow(const QString & from)
{
if(privateChats.contains(from)){
PrivateChatDialog *privChat = privateChats[from];
privateChats.remove(from);
delete(privChat);
//qDebug() << "Removed host from hash table!";
}
}
void ChatDialog::newPrivateMessage(const QString& message, const QString& from)
{
PrivateChatDialog *privChat;
if (!privateChats.contains(from)){
privChat = new PrivateChatDialog(from);
privateChats[from] = privChat;
QObject::connect(privChat, SIGNAL(sendMessage(const QString&, const QString&)),
router, SLOT(sendMessage(const QString&, const QString&)));
connect(privChat, SIGNAL(closed(const QString&)),
this, SLOT(destroyPrivateWindow(const QString&)));
privChat->show();
}
else{
privChat = privateChats[from];
}
privChat->externalMessageReceived(message);
}
void
ChatDialog::openEmptyPrivateChat(QListWidgetItem* item)
{
PrivateChatDialog *privChat;
QString destination = item->text();
if (!privateChats.contains(destination)){
privChat= new PrivateChatDialog(destination);
privateChats[destination] = privChat;
connect(privChat, SIGNAL(sendMessage(const QString&, const QString&)),
router, SLOT(sendMessage(const QString&, const QString&)));
connect(privChat, SIGNAL(closed(const QString&)),
this, SLOT(destroyPrivateWindow(const QString&)));
//qDebug() << "Opened empty private chat!";
privChat->show();
}
}
// End: ChatDialog
//Begin: NetSocket
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 Peerster 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;
messageIdCounter = 1;
dispatcher = new Dispatcher(&fs, this);
QObject::connect(this, SIGNAL(toDispatcher(const QMap<QString, QVariant>&)),
dispatcher, SLOT(processRequest(const QMap<QString, QVariant>&)));
QObject::connect(dispatcher, SIGNAL(sendNeighbor(const QMap<QString, QVariant>&, quint32)),
this, SLOT(sendNeighbor(const QMap<QString, QVariant> &, quint32)));
anythingHot = false;
antiEntropyTimer.setSingleShot(false);
antiEntropyTimer.start(10000);
routeRumorTimer.setSingleShot(false);
routeRumorTimer.start(60000);
qsrand((QDateTime::currentDateTime()).toTime_t());
QObject::connect(&routeRumorTimer, SIGNAL(timeout()),
this, SLOT(routeRumorTimeout()));
QObject::connect(this, SIGNAL(startRouteRumorTimer(int)),
&routeRumorTimer, SLOT(start(int)));
QObject::connect(this, SIGNAL(readyRead()),
this, SLOT(readData()));
QObject::connect(this, SIGNAL(startRumorTimer(int)),
&rumorTimer, SLOT(start(int)));
QObject::connect(&rumorTimer, SIGNAL(timeout()),
this, SLOT(newRumor()));
QObject::connect(&antiEntropyTimer, SIGNAL(timeout()),
this, SLOT(processAntiEntropyTimeout()));
}
void
NetSocket::processFiles(const QStringList &files)
{
fs.IndexFiles(files);
}
void NetSocket::routeRumorTimeout()
{
QVariantMap udpBodyAsMap;
routeRumorTimer.stop();
// Put the values in the map.
udpBodyAsMap["SeqNo"] = messageIdCounter++;
udpBodyAsMap["Origin"] = myNameString;
if (updateVector(udpBodyAsMap, false)){
broadcastMessage(udpBodyAsMap);
emit startRouteRumorTimer(60000);
}
else {
qDebug() << "NetSocket::gotSendMessage -- OUT OF ORDER MESSAGE FROM MYSELF: COMMIT SUICIDE";
// *((int *)NULL) = 1;
}
}
void NetSocket::addHost(const QString& s)
{
neighborList.addHost(s);
}
// After receiving a time-out from the antientropy timer, send
// my vector clock to a random neighbor.
void NetSocket::processAntiEntropyTimeout()
{
QPair<QHostAddress, quint16> neighbor = neighborList.randomNeighbor();
sendStatusMessage(neighbor.first, neighbor.second);
}
bool NetSocket::bind(QList<QString> &paxosNodes)
{
// Try to bind to each of the range myPortMin..myPortMax in turn.
quint16 qMyPortMin = (quint16) myPortMin;
quint16 qMyPortMax = (quint16) myPortMax;
// Find and register all the neighbors. For the time being they are just those on the same
// host on different ports.
for (quint16 p = qMyPortMin; p <= qMyPortMax; p++) {
if (QUdpSocket::bind(p)) {
/* ////qDebug() << "bound to UDP port " << p;
if (p == qMyPortMin){
neighborList.addNeighbor(QHostAddress::LocalHost, p + 1);
}
else if (p == qMyPortMin + 1){
neighborList.addNeighbor(QHostAddress::LocalHost, p - 1);
neighborList.addNeighbor(QHostAddress::LocalHost, p + 1);
}
else if (p == qMyPortMin + 2){
neighborList.addNeighbor(QHostAddress::LocalHost, p - 1);
neighborList.addNeighbor(QHostAddress::LocalHost, p + 1);
}
else if (p == qMyPortMin + 3){
neighborList.addNeighbor(QHostAddress::LocalHost, p - 1);
}
*/
qDebug() << "port: " << p;
for (quint16 q = qMyPortMin; q <= qMyPortMax; q++) {
if (p != q){
//neighbors.append(QPair<QHostAddress, quint16>(QHostAddress::LocalHost, q));
neighborList.addNeighbor(QHostAddress::LocalHost, q);
}
}
noForward = false;
QStringList args = QCoreApplication::arguments();
int max = args.count();
bool inPaxos = false;
bool donePaxos = false;
qDebug() << args.count();
for(int i = 1; i < max; ++i){
if (!inPaxos && !donePaxos && (args[i] == "-paxos-nodes"))
inPaxos = true;
else if(inPaxos){
if (args[i][0] == '-'){
inPaxos = false;
donePaxos = true;
}
else{
qDebug() << args[i];
paxosNodes.append(args[i]);
}
}
else if (args[i] == "-noforward"){
//qDebug() << "No Forwarding!!!";
noForward = true;
}
////qDebug() << args[i];
/*
else
addHost(args[i]);*/
}
qDebug() << "Num paxos nodes =" << paxosNodes.count();
if(paxosNodes.count() == 0){
qDebug() << "Node identifiers not specified, exiting...";
exit(0);
}
router = new Router(this, noForward);
myNameString = paxosNodes[0];
/*
QTextStream stream(&myNameString);
stream << QUuid::createUuid();
stream << (QDateTime::currentDateTime()).toTime_t();
*/
myNameVariant = QVariant(myNameString);
//qDebug() << p;
router->me = myNameString;
fileRequests = new FileRequests(myNameString);
connect(fileRequests, SIGNAL(sendDownloadMsg(const QMap<QString, QVariant>&, const QString&)),
router, SLOT(sendMap(const QMap<QString, QVariant>&, const QString&)));
connect(router, SIGNAL(blockRequest(const QMap<QString, QVariant> &)),
dispatcher, SLOT(processRequest(const QMap<QString, QVariant> &)));
connect(router, SIGNAL(toFileRequests(const QMap<QString, QVariant> &)),
fileRequests, SLOT(processReply(const QMap<QString, QVariant> &)));
connect(dispatcher, SIGNAL(reply(const QMap<QString, QVariant>&, const QString &)),
router, SLOT(sendMap(const QMap<QString, QVariant>&, const QString&)));
connect(fileRequests, SIGNAL(broadcastRequest(const QMap<QString, QVariant> &)),
this, SLOT(broadcastMessage(const QMap<QString, QVariant>&)));
////qDebug() << "Finished intialization!!!";
return true;
}
}
////qDebug() << "Oops, no ports in my default range " << myPortMin
//<< "-" << myPortMax << " available";
return false;
}
// Received a message from the dialog.
// Construct the message as a QVariantMap and
// call the function to handle received rumors.
void NetSocket::gotSendMessage(const QString &s)
{
QVariantMap udpBodyAsMap;
// Put the values in the map.
udpBodyAsMap["ChatText"] = s;
udpBodyAsMap["SeqNo"] = messageIdCounter++;
udpBodyAsMap["Origin"] = myNameString;
if (updateVector(udpBodyAsMap, true)){
newRumor();
}
else {
qDebug() << "NetSocket::gotSendMessage -- OUT OF ORDER MESSAGE FROM MYSELF: COMMIT SUICIDE";
// *((int *)NULL) = 1;
}
}
// Send status message to the given address:port combination.
// Reads the current state of the vector clock.
void NetSocket::sendStatusMessage(QHostAddress address, quint16 port)
{
QVariantMap udpBodyAsMap;
udpBodyAsMap["Want"] = vectorClock;
QByteArray arr;
QDataStream s(&arr, QIODevice::Append);
s << udpBodyAsMap;
////qDebug() << "NetSocker::sendStatusMessage " << udpBodyAsMap["Want"];
this->writeDatagram(arr, address, port);
////qDebug() << "NetSocket:sendStatusMessage -- finished sending status to " << address << " " << port;
}
bool
NetSocket::expectedRumor(const QVariantMap& rumor, QString *origin, quint32* expected)
{
*origin = rumor["Origin"].toString();
if (vectorClock.contains(*origin)){
*expected = (vectorClock[*origin]).toUInt();
////qDebug() << "NetSocket::newRumor -- Contain entry for " << *origin << " expect " << *expected;
}
else{
*expected = 1;
////qDebug() << "NetSocket::newRumor -- Don't contain entry for " << *origin << " expect " << 1;
}
////qDebug() << "NetSocket::newRumor -- got " << " " << rumor["SeqNo"].toUInt();
return (*expected) == rumor["SeqNo"].toUInt();
}
bool
NetSocket::updateVector(const QVariantMap& rumor, bool isRumorMessage)
{
QString origin;
quint32 expected;
if (expectedRumor(rumor, &origin, &expected)){
QByteArray arr;
QDataStream stream(&arr, QIODevice::Append);
stream << rumor;
anythingHot = true;
hotMessage = rumor;
////qDebug() << "NetSocket::newRumor -- yay, in-order message!!!";
vectorClock[origin] = expected + 1;
if (expected == 1){
QList<QVariantMap> temp;
messages[origin] = temp;
messages[origin].append(EMPTY_VARIANT_MAP);
}
messages[origin].append(rumor);
if (isRumorMessage){
emit receivedMessage ((rumor["ChatText"]).toString());
}
return true;
}
return false;
}
// We might have received a new rumor.
// a) If it is from the dialog, then it is definitely new.
//
// b) If it is from the network, then it might not be new,
// we have to account for this by checking the expected
// value from the vector clock with the sequence number
// in the message.
//
// c) If we have a new message, start rumor mongering.
//
// d) Only this function manipulates the vector clock and messages.
//
// e) Only this function sets anythingHot to true.
void NetSocket::newRumor()
{
rumorTimer.stop();
if(anythingHot){
if (!noForward || !hotMessage.contains("ChatText")){
QPair<QHostAddress, quint16> neighbor = neighborList.randomNeighbor();
this->writeDatagram(Helper::SerializeMap(hotMessage),
neighbor.first,
neighbor.second);
emit startRumorTimer(2000);
}
}
}
// Some utility methods to keep track of which neighbors we have already sent
// messages to for the same hotmessage. If we change hotmessages, then we have to clean up!!!
// WE ONLY CLEAN UP IN newRumor!!!
/*
void NetSocket::excludeNeighbor(quint32 port)
{
for (int i = 0; i < neighbors.count(); ++i){
if ((neighbors[i]).second == port){
neighborsVisited->insert(i);
return;
}
}
}
*/
// If none of the elements are bigger, the string is empty.
int NetSocket::tryFindFirstBigger(const QVariantMap& map1, const QVariantMap& map2, QString* key)
{
QList<QString> keys = map1.keys();
for(int i = 0; i < keys.count(); ++i){
if (map2.contains(keys[i])){
//////qDebug() << "NetSocket::tryFindFirstBigger -- first if ok";
// both have the key, but map1's is higher: Success!!!
if ((map1[keys[i]].toUInt() > map2[keys[i]].toUInt()) &&
(map1[keys[i]].toUInt() > 1)){
//////qDebug() << "NetSocket::tryFindFirstBigger -- inner if ok";
*key = keys[i];
return map2[keys[i]].toUInt();
}
else
continue;
}
// map2 does not have the key: Success!!!
else if (map1[keys[i]].toUInt() == 1){
continue;
}
else {
*key = keys[i];
return 1;
}
}
return -1;
}
bool NetSocket::checkVector(const QVariantMap& vect)
{
QVariant temp = vect["Want"];
if (temp.type() == QVariant::Map){
QMap<QString, QVariant> other_vector = temp.toMap();
QList<QString> keys = other_vector.keys();
for(int i = 0; i < keys.count(); ++i){
bool isInt;
quint32 value = other_vector[keys[i]].toUInt(&isInt);
if (isInt){
if (value < 1){
return false;
}
}
else{ // if (isInt)
return false;
}
}
return true;
}
else{ // if (temp.type() == QVariant::Map)
return false;
}
}
void NetSocket::addUnknownOrigins(const QVariantMap &message)
{
QList<QString> keys = message.keys();
int len = keys.count();
for (int i = 0; i < len; ++i){