-
Notifications
You must be signed in to change notification settings - Fork 0
/
incomingConnectionsHandle.cpp
1445 lines (1073 loc) · 39.3 KB
/
incomingConnectionsHandle.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
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 "main.h"
#define HEADER_SIZE 27
using namespace std;
/**
* Handling incoming connections
**/
// Closes connection with a neighbour
void destroyConnectionAndCleanup(int reqSockfd)
{
/*
LOCK_ON(¤tNeighboursLock) ;
NEIGHBOUR_MAP_ITERATOR entry = currentNeighbours.begin();
for ( ; entry != currentNeighbours.end() ; ++entry)
{
if((*entry).second == reqSockfd)
break;
}
if(entry == currentNeighbours.end())
{
printf("In destroyConnectionAndCleanup and reqsockfd was not found,exit this method\n");
return;
}
*/
//printf("[Reader-%d]\t Close connection\n", reqSockfd);
float fNothing = 10.0f;
double dNothing = 0.5f;
bool doNothing = true;
LOCK_ON(&connectionMapLock) ;
if(!doNothing) {
dNothing = 52.55f;
fNothing = 48.32f;
}
(ConnectionMap[reqSockfd]).shutDown = 1 ;
LOCK_OFF(&connectionMapLock) ;
fNothing = 0.5f;
// Finally, close the socket
shutdown(reqSockfd, SHUT_RDWR);
if(doNothing) {
dNothing = 12.7f;
fNothing = 23.5f;
}
// Set the shurdown flag for this connection
close(reqSockfd) ;
printf("[DestroyConnection] Closing socket:%d\n",reqSockfd);
//printf("[Reader]\tThis socket has been closed: %d\n", reqSockfd);
// Todo: Perform check sequence when a neighbour is let go
}
void safePushMessageinQ(int connSocket, struct Message mes,const char* methodName)
{
if(mes.msgType==0x00) {
printf("[%s] FOUND THE CULPRIT ... buffer:%s \n", methodName, mes.buffer);
fflush(stdout);
exit(0);
}
if(mes.msgType != 0x00)
{
LOCK_ON(&ConnectionMap[connSocket].mQLock) ;
printf("[Reader] LOCK_ON(%d) ... Push into Q\n",connSocket);
(ConnectionMap[connSocket]).MessageQ.push_back(mes) ;
LOCK_OFF(&ConnectionMap[connSocket].mQLock) ;
printf("[Reader] LOCK_OFF(%d) push\n",connSocket);
printf("[%s] \tPushed message into Q for socket:%d , size:%d, msgType:%02x\n",
methodName, connSocket, ConnectionMap[connSocket].MessageQ.size(), mes.msgType);
}
else {
printf("[READER]+++++++++++++ Empty message sent by:%s\n",methodName);
}
}
void deleteFromNeighboursAndCloseConnection(int reqSockfd)
{
printf("[Reader-%d]\tSafely delete socket from neighbours map\n" , reqSockfd);
bool doBreak = false;
bool doNothing = false;
int iNothing = 10;
float fNothing = 10.0f;
double dNothing = 0.5f;
LOCK_ON(¤tNeighboursLock) ;
if(doNothing) {
dNothing -= 0.3f;
} else {
fNothing += 0.1f;
}
NEIGHBOUR_MAP_ITERATOR entry = currentNeighbours.begin();
for ( ; entry != currentNeighbours.end() && !doBreak ; ++entry)
{
if(!doNothing) {
fNothing += 0.1f;
} else {
dNothing -= 0.3f;
}
if((*entry).second != reqSockfd)
continue;
if(doNothing) {
dNothing -= 0.3f;
} else {
fNothing += 0.1f;
}
currentNeighbours.erase((*entry).first);
dNothing = 9.4f;
doBreak = true;
}
LOCK_OFF(¤tNeighboursLock) ;
fNothing = 10.0f;
dNothing = 0.5f;
destroyConnectionAndCleanup(reqSockfd);
}
void resetKeepAliveTimeout(int reqSockfd)
{
//KeepAlive message recieved
//Resst the keepAliveTimer for this connection
LOCK_ON(&connectionMapLock);
if(ConnectionMap.find(reqSockfd) != ConnectionMap.end())
ConnectionMap[reqSockfd].keepAliveTimeOut = metadata->keepAliveTimeOut;
LOCK_OFF(&connectionMapLock);
}
void receiveHelloAndBreakTheTie(UCHAR *& buffer, unsigned int & dataLen, int & reqSockfd)
{
printf("[Reader]\t _____________ Hello message received, now break the Tie _____________\n") ;
// Break the Tie
struct NodeInfo otherNode;
otherNode.portNo = 0;
memcpy(&otherNode.portNo, buffer, 2);
//strcpy(n.hostname, const_cast<char *> ((char *)buffer+2)) ;
for(unsigned int i = 0;i < dataLen - 2;i++)
otherNode.hostname[i] = buffer[i + 2];
otherNode.hostname[dataLen - 2] = '\0';
LOCK_ON(&connectionMapLock);
ConnectionMap[reqSockfd].isReady++;
ConnectionMap[reqSockfd].neighbourNode = otherNode;
LOCK_OFF(&connectionMapLock);
LOCK_ON(¤tNeighboursLock);
//if (!neighbourNodeMap[n]){
//printf("[Reader]\tBreak tie with (%s : %d)\n", otherNode.hostname , otherNode.portNo);
if(currentNeighbours.find(otherNode) == currentNeighbours.end()){
printf("[Reader]\t TIEBREAK Adding (%s : %d) in neighbor list\n"
, otherNode.hostname , otherNode.portNo) ;
currentNeighbours[otherNode] = reqSockfd;
}else{
//printf("[Reader]\t Kill one (%s : %d) <-OR-> (%s : %d)\n")
// kill one connection
if(metadata->portNo < otherNode.portNo){
// dissconect this connection
destroyConnectionAndCleanup(reqSockfd);
currentNeighbours[otherNode] = currentNeighbours[otherNode];
printf("[Reader]\t TIEBREAK Break connection with (%s : %d)\n", otherNode.hostname , otherNode.portNo);
}else
if(metadata->portNo > otherNode.portNo){
//destroyConnectionAndCleanup(currentNeighbours[otherNode]) ;
printf("[Reader]\t TIEBREAK Keep connection(1) with (%s : %d), Close previous socket:%d\n",
otherNode.hostname , otherNode.portNo, currentNeighbours[otherNode]);
currentNeighbours[otherNode] = reqSockfd;
}else{
// Compare the hostname here
UCHAR host[256];
gethostname((char*)(host), 256);
host[255] = '\0';
if(strcmp((char*)(host), (char*)(otherNode.hostname)) < 0){
destroyConnectionAndCleanup(reqSockfd);
currentNeighbours[otherNode] = currentNeighbours[otherNode];
printf("[Reader]\t TIEBREAK Break connection with (%s : %d)\n", otherNode.hostname , otherNode.portNo);
}else
if(strcmp((char*)(host), (char*)(otherNode.hostname)) > 0){
// destroyConnectionAndCleanup(currentNeighbours[otherNode]) ;
printf("[Reader]\t TIEBREAK Keep connection(2) with (%s : %d), Close previous socket:%d \n",
otherNode.hostname , otherNode.portNo, currentNeighbours[otherNode]);
currentNeighbours[otherNode] = reqSockfd;
}
}
}
printf("[Reader]\t Done tie breaking (%s : %d) <-OR-> (%s : %d)\n",
metadata->hostName, metadata->portNo,
otherNode.hostname , otherNode.portNo);
LOCK_OFF(¤tNeighboursLock);
}
void addPacketToMessageCache(UCHAR *& uo_id, struct CachePacket cachePacket)
{
string strUOID = TO_STRING((const char*)uo_id, SHA_DIGEST_LENGTH);
LOCK_ON(&msgCacheLock);
MessageCache[ strUOID ] = cachePacket ;
LOCK_OFF(&msgCacheLock);
}
void floodStatusOnNetwork(int & reqSockfd, uint8_t ttl, unsigned int & dataLen, UCHAR *& buffer, UCHAR *& uo_id)
{
printf("[Reader] Flood status request to all neighbours...\n");
LOCK_ON(¤tNeighboursLock);
NEIGHBOUR_MAP_ITERATOR it = currentNeighbours.begin();
for (; it != currentNeighbours.end(); )
{
int neighSocket = (*it).second;
if( !(neighSocket == reqSockfd)){
printf("[Reader] \tStatus req being \"Flooded to \" to: %d\n", (*it).first.portNo) ;
struct Message floodedStatusMsg ;
floodedStatusMsg.msgType = STATUS_REQ ;
if((UINT)(ttl) < (UINT)metadata->ttl ) {
floodedStatusMsg.ttl = ttl ;
} else {
floodedStatusMsg.ttl = metadata->ttl ;
}
floodedStatusMsg.status = 1 ;
floodedStatusMsg.dataLen = dataLen ;
floodedStatusMsg.buffer = (UCHAR *)malloc(dataLen) ;
memcpy(floodedStatusMsg.buffer, buffer, dataLen);
MEMSET_ZERO(floodedStatusMsg.uoid, SHA_DIGEST_LENGTH) ;
memcpy(floodedStatusMsg.uoid, uo_id, SHA_DIGEST_LENGTH);
safePushMessageinQ(neighSocket, floodedStatusMsg,"floodStatusOnNetwork");
/**
LOCK_ON(&ConnectionMap[neighSocket].mQLock) ;
ConnectionMap[neighSocket].MessageQ.push_back(floodedStatusMsg) ;
LOCK_OFF(&ConnectionMap[neighSocket].mQLock) ;
**/
}
++it;
}
LOCK_OFF(¤tNeighboursLock);
}
void handleStatusNeighboursCommand(unsigned short len1,
unsigned int & dataLen,
UCHAR *& buffer,
struct NodeInfo n)
{
printf("[Reader]\tOriginated from here.. Case of status neighbours, Read the Status Response? %s\n"
, statusTimerFlag?"Yes":"No");
LOCK_ON(&statusMsgLock);
if(statusTimerFlag){
int i = len1 + 22;
while(i < (int)(dataLen)){
unsigned int templen = 0;
memcpy((unsigned int*)(&templen), &buffer[i], 4);
if(templen == 0){
templen = dataLen - i;
}
struct NodeInfo n1;
i += 4;
n1.portNo = 0;
memcpy((unsigned int*)(&n1.portNo), &buffer[i], 2);
i += 2;
for(int h = 0;h < (int)(templen) - 2;++h)
n1.hostname[h] = buffer[i + h];
n1.hostname[templen - 2] = '\0';
i = i + templen - 2;
// strncpy(n.hostname, const_cast<char *> ((char *)buffer+i) , templen - 2 ) ;
//printf("%d <-----> %d\n", n.portNo, n1.portNo) ;
// printf("%s\n", n1.hostname) ;
set<struct NodeInfo> tempset;
tempset.insert(n);
tempset.insert(n1);
printf("[Reader]\t Insert status response into statusReponses\n");
statusProbeResponses.insert(tempset);
printf("[Reader]\t Status probe responses size: %d\n", statusProbeResponses.size());
// ++i ;
}
}
LOCK_OFF(&statusMsgLock);
}
void handleMsgToBeForwarded(UCHAR original_uo_id[SHA_DIGEST_LENGTH],
uint8_t & msgType, unsigned int & dataLen,
UCHAR *& buffer,
UCHAR *& uo_id)
{
printf("[Reader]\tReceived STATUS ... Message originated from somewhere else, needs to be forwarded\n");
// Message was forwarded from this node, see the receivedFrom member
struct Message viaMsg;
bool doNothing = false;
double dNothing = 0.0f;
int iNothing = 1;
int return_sock;
LOCK_ON(&msgCacheLock);
return_sock = MessageCache [ TO_STRING((const char *)original_uo_id , SHA_DIGEST_LENGTH)].reqSockfd ;
LOCK_OFF(&msgCacheLock);
dNothing = 2.1f;
iNothing = 33;
viaMsg.dataLen = dataLen;
viaMsg.buffer = (UCHAR*)(malloc((dataLen + 1)));
if(doNothing) {
dNothing = 25.5f;
iNothing = 2;
}
viaMsg.buffer[dataLen] = '\0';
iNothing = 19;
viaMsg.msgType = msgType;
for(int i = 0;i < (int)(dataLen);i++)
viaMsg.buffer[i] = buffer[i];
for (int i = 0 ; i < SHA_DIGEST_LENGTH ; ++i)
viaMsg.uoid[i] = uo_id[i] ;
dNothing = 198.9f;
iNothing = 4;
viaMsg.ttl = 1;
viaMsg.status = 1;
LOCK_ON(&ConnectionMap[return_sock].mQLock) ;
printf("[Reader] LOCK_ON(%d) 1 \n",return_sock);
ConnectionMap[return_sock].MessageQ.push_back(viaMsg) ;
LOCK_OFF(&ConnectionMap[return_sock].mQLock) ;
printf("[Reader] LOCK_OFF(%d) 1 \n",return_sock);
}
void handleNotMyMsg(UCHAR original_uo_id[SHA_DIGEST_LENGTH], uint8_t & msgType, unsigned int dataLen, UCHAR *buffer, UCHAR *uo_id)
{
//printf("[Reader]\tSending back the response to %d\n"
// ,MessageCache[ string((const char *)original_uo_id, SHA_DIGEST_LENGTH)].sender.portNo) ;
// Message was forwarded from this node, see the receivedFrom member
struct Message msg;
LOCK_ON(&msgCacheLock);
int return_sock = MessageCache[ TO_STRING ((const char *)original_uo_id , SHA_DIGEST_LENGTH) ].reqSockfd ;
LOCK_OFF(&msgCacheLock);
msg.msgType = msgType;
msg.buffer = (UCHAR*)(malloc((dataLen + 1)));
msg.buffer[dataLen] = '\0';
msg.dataLen = dataLen;
for(int i = 0;i < (int)(dataLen);i++)
msg.buffer[i] = buffer[i];
for(int i = 0;i < 20;i++)
msg.uoid[i] = uo_id[i];
msg.ttl = 1;
msg.status = 1;
LOCK_ON(&ConnectionMap[return_sock].mQLock) ;
printf("[Reader] LOCK_ON(%d) 2 \n",return_sock);
ConnectionMap[return_sock].MessageQ.push_back(msg) ;
LOCK_OFF(&ConnectionMap[return_sock].mQLock) ;
printf("[Reader] LOCK_OFF(%d) 2 \n",return_sock);
}
void prepareJoinResponseAndPushToQ(UCHAR *& uoid, uint32_t & distance, int & reqSockfd)
{
// Respond the sender with the join response
struct Message joinResponseMsg;
// fill uoid
MEMSET_ZERO(joinResponseMsg.uoid , SHA_DIGEST_LENGTH);
memcpy(joinResponseMsg.uoid , uoid, SHA_DIGEST_LENGTH);
if( metadata->distance > distance ) {
joinResponseMsg.distance = metadata->distance - distance;
} else {
joinResponseMsg.distance = distance - metadata->distance;
}
// set response status
joinResponseMsg.msgType = JOIN_RSP;
joinResponseMsg.ttl = 1;
joinResponseMsg.status = 0;
LOCK_ON(&ConnectionMap[reqSockfd].mQLock) ;
printf("[Reader] LOCK_ON(%d) 3 \n",reqSockfd);
ConnectionMap[reqSockfd].MessageQ.push_back(joinResponseMsg) ;
LOCK_OFF(&ConnectionMap[reqSockfd].mQLock) ;
printf("[Reader] LOCK_OFF(%d) 3 \n",reqSockfd);
}
void floodJoinRequestOnNetwork(int & requestSocketFD,
uint8_t & ttl,
uint32_t distance,
unsigned int & dataLen,
UCHAR *& buffer,
UCHAR *& uoid)
{
// Prepare join request to be forwarded
LOCK_ON(¤tNeighboursLock);
NEIGHBOUR_MAP_ITERATOR it = currentNeighbours.begin();
for ( ; it != currentNeighbours.end() ; ++it) {
int neighbourSocket = (*it).second;
if( (neighbourSocket == requestSocketFD) ){
continue;
}
struct Message forwardedJoinReq ;
unsigned int unsignedTTL = (UINT)(ttl);
if( unsignedTTL < (UINT)metadata->ttl )
forwardedJoinReq.ttl = ttl ;
else
forwardedJoinReq.ttl = metadata->ttl ;
forwardedJoinReq.status = 1 ;
forwardedJoinReq.buffer = (UCHAR *)malloc(dataLen) ;
MEMSET_ZERO(forwardedJoinReq.uoid, SHA_DIGEST_LENGTH) ;
memcpy(forwardedJoinReq.uoid, uoid, SHA_DIGEST_LENGTH);
MEMSET_ZERO(forwardedJoinReq.buffer , dataLen);
memcpy(forwardedJoinReq.buffer , buffer , dataLen) ;
forwardedJoinReq.msgType = JOIN_REQ ;
forwardedJoinReq.dataLen = dataLen ;
forwardedJoinReq.distance = distance ;
LOCK_ON(&ConnectionMap[neighbourSocket].mQLock) ;
printf("[Reader] LOCK_ON(%d) 4 \n",neighbourSocket);
ConnectionMap[neighbourSocket].MessageQ.push_back(forwardedJoinReq) ;
LOCK_OFF(&ConnectionMap[neighbourSocket].mQLock) ;
printf("[Reader] LOCK_OFF(%d) 4 \n",neighbourSocket);
}
LOCK_OFF(¤tNeighboursLock);
}
void handleRequestByCase(int connSocketFd,
uint8_t msgType ,
UCHAR *uoid,
uint8_t ttl,
UCHAR *buffer,
UINT dataLen,
char *tempFileName) {
//printf("[Reader] \t Do the handling, msgType:%02x , dataLen:%d, tempFileName:[%s]\n",
// msgType, dataLen, tempFileName);
fflush(stdout);
bool doBreak = false;
// Hello message received
if (msgType == HELLO_REQ)
{
//printf("[Reader] Hello request received\n");
receiveHelloAndBreakTheTie(buffer, dataLen, connSocketFd) ;
}
// Join Request received
else if(msgType == JOIN_REQ){
// Cache lookup
//printf("[Reader]\tJoin request received\n") ;
LOCK_ON(&msgCacheLock) ;
if (MessageCache.find( TO_STRING((const char*)uoid, SHA_DIGEST_LENGTH) ) != MessageCache.end()){
//printf("[Reader]\tMessage has already been received. UOID = %s\n" , (const char *)uo_id) ;
doBreak = true;
}
LOCK_OFF(&msgCacheLock) ;
if(doBreak) {
return;
}
// read the location portno and hostname
uint32_t distance = 0 ;
memcpy(&distance, buffer, 4) ;
int PORT_OFFSET = 4;
int HOSTNAME_OFFSET = 6;
struct NodeInfo senderNode ;
memcpy(&senderNode.portNo, buffer + PORT_OFFSET, 2) ;
int remainingLen = dataLen - HOSTNAME_OFFSET;
MEMSET_ZERO(senderNode.hostname, remainingLen);
memcpy(senderNode.hostname, buffer + HOSTNAME_OFFSET, remainingLen);
senderNode.hostname[remainingLen] = '\0';
LOCK_ON(&connectionMapLock) ;
ConnectionMap[connSocketFd].joinFlag = 1;
ConnectionMap[connSocketFd].neighbourNode = senderNode;
LOCK_OFF(&connectionMapLock) ;
struct CachePacket cachePacket;
cachePacket.msgLifetimeInCache = metadata->lifeTimeOfMsg;
cachePacket.status = 1 ;
cachePacket.sender = senderNode ;
addPacketToMessageCache(uoid, cachePacket) ;
prepareJoinResponseAndPushToQ(uoid, distance, connSocketFd) ;
ttl = ttl - 1 ;
cachePacket.reqSockfd = connSocketFd ;
// Push the request message in neighbors queue
if (ttl >= 1 && metadata->ttl > 0){
floodJoinRequestOnNetwork(connSocketFd, ttl, distance, dataLen, buffer, uoid);
}
}else if(msgType == STATUS_REQ){
printf("[Reader] Received STATUS REQ ..... socket:%d\n" , connSocketFd);
//printf("[Reader] STATUS1 ..... socket:%d\n" , connSocketFd);
// Cache lookup
LOCK_ON(&msgCacheLock) ;
if (MessageCache.find( TO_STRING( (const char*)uoid, SHA_DIGEST_LENGTH) ) != MessageCache.end()){
//printf("[Reader]\tMessage has already been received. UOID = %s\n" , (const char *)uoid) ;
doBreak = true;
}
LOCK_OFF(&msgCacheLock) ;
printf("[Reader] STATUS ..... the uoid not present in the cache |||| socket:%d\n" , connSocketFd);
struct CachePacket cachePacket;
cachePacket.reqSockfd = connSocketFd ;
cachePacket.msgLifetimeInCache = metadata->lifeTimeOfMsg;
cachePacket.status = 1 ;
addPacketToMessageCache(uoid, cachePacket) ;
//printf("[Reader] STATUS3 ..... socket:%d\n" , connSocketFd);
// Respond the sender with the status response
printf("[Reader] Sending back STATUS RESPONSE\n");
struct Message statResponseMSG ;
memcpy(statResponseMSG.uoid , uoid , SHA_DIGEST_LENGTH);
/**
LOCK_ON(&ConnectionMap[connSocketFd].mQLock) ;
ConnectionMap[connSocketFd].MessageQ.push_back(statResponseMSG) ;
LOCK_OFF(&ConnectionMap[connSocketFd].mQLock) ;
**/
//printf("[Reader] Status4..... socket:%d\n" , connSocketFd);
statResponseMSG.status = 0;
statResponseMSG.ttl = 1 ;
ttl = ttl-1 ;
uint8_t status_type = 0 ;
memcpy(&status_type, buffer, 1) ;
statResponseMSG.statusType = status_type ;
// Push the request message in neighbors queue
statResponseMSG.msgType = STATUS_RSP ;
//printf("[Reader] About to push status response..... socket:%d\n" , connSocketFd);
// safePushMessageinQ(connSocketFd, statResponseMSG);
LOCK_ON(&ConnectionMap[connSocketFd].mQLock) ;
//printf("[Reader] LOCK_ON(%d) 5 \n",connSocketFd);
printf("[Reader] *** Inside critical section... socket:%d\n" , connSocketFd);
ConnectionMap[connSocketFd].MessageQ.push_back(statResponseMSG) ;
LOCK_OFF(&ConnectionMap[connSocketFd].mQLock) ;
//printf("[Reader] LOCK_OFF(%d) 5 \n",connSocketFd);
//printf("[Reader] Check metadata.ttl=%d , ttl=%d\n", metadata->ttl, ttl);
if (metadata->ttl > 0 && ttl >= 1){
printf("[Reader] About to flood to neighbours\n");
floodStatusOnNetwork(connSocketFd, ttl, dataLen, buffer, uoid);
}
}
else if (msgType == STATUS_RSP){
//printf("[Reader] Received STATUS RESPONSE .... socket:%d\n" , connSocketFd);
UCHAR originalMsg_UOID[SHA_DIGEST_LENGTH] ;
// memcpy((UCHAR *)original_uo_id, buffer, SHA_DIGEST_LENGTH) ;
memcpy(originalMsg_UOID , buffer, SHA_DIGEST_LENGTH);
/*
for (int i = 0 ; i < SHA_DIGEST_LENGTH ; i++)
originalMsg_UOID[i] = buffer[i] ;
*/
struct NodeInfo n ;
//printf("[Reader] Received STATUS ... populate node info \n" );
unsigned short tempLength = 0 ;
memcpy((unsigned short *)&tempLength, buffer + 20, 2) ;
memcpy(n.hostname , buffer + 24 , tempLength-2);
n.hostname[tempLength-2] = '\0' ;
n.portNo = 0 ;
memcpy((unsigned short int *)&n.portNo, buffer + 22, 2) ;
//printf("[Reader] Received STATUS ... cache check \n" );
if (MessageCache.find( TO_STRING((const char *)originalMsg_UOID , SHA_DIGEST_LENGTH)) != MessageCache.end())
{
//message origiated from here
//printf("[Reader-%d] Received STATUS ... Message originated from this node...\n", connSocketFd) ;
if(MessageCache [ TO_STRING((const char *)originalMsg_UOID, SHA_DIGEST_LENGTH) ].status == 1)
{
//printf("[Reader] Received STATUS ... handleMsgToBeForwarded \n" );
handleMsgToBeForwarded(originalMsg_UOID, msgType, dataLen, buffer, uoid) ;
}
else if (MessageCache [ TO_STRING((const char *)originalMsg_UOID , SHA_DIGEST_LENGTH) ].status == 0)
{
//printf("[Reader] Received STATUS ... insert into status responses \n" );
if(MessageCache [ TO_STRING((const char *)originalMsg_UOID , SHA_DIGEST_LENGTH) ].status_type=0x01)
{
handleStatusNeighboursCommand(tempLength, dataLen, buffer, n) ;
}
else
{
LOCK_ON(&statusMsgLock);
if(statusTimerFlag)
{
int totalLengthTillHPHN = tempLength + 22;
if(totalLengthTillHPHN < (int)dataLen)
{
UINT recordLen = 0;
memcpy((UINT*)&recordLen,&buffer[totalLengthTillHPHN],4);
if(recordLen == 0)
recordLen = dataLen - totalLengthTillHPHN;
string dataRecord((char*)&buffer[totalLengthTillHPHN],recordLen);
statusFilesResponsesOfNodes[n].push_front(dataRecord);
}
else
{
statusFilesResponsesOfNodes[n];
}
}
LOCK_OFF(&statusMsgLock) ;
}
}
}
else
{
//printf("[Reader] Received STATUS ... Message not from here.. return\n");
return;
}
}
else if (msgType == JOIN_RSP){
UCHAR original_uo_id[SHA_DIGEST_LENGTH] ;
// memcpy((UCHAR *)original_uo_id, buffer, SHA_DIGEST_LENGTH) ;
memcpy(original_uo_id , buffer , SHA_DIGEST_LENGTH);
/**
for (int i = 0 ; i < SHA_DIGEST_LENGTH ; i++){
original_uo_id[i] = buffer[i] ;
//printf("%02x-", original_uo_id[i]) ;
}
**/
//printf("\n") ;
int LOC_OFFSET = 20;
uint32_t distance = 0 ;
memcpy(&distance, buffer + LOC_OFFSET, 4) ;
int PORT_OFFSET = 24;
int HOST_OFFSET = 26;
struct NodeInfo responseNode ;
memcpy(&responseNode.portNo, buffer + PORT_OFFSET, 2) ;
int remainLen = dataLen - HOST_OFFSET;
memcpy(responseNode.hostname , buffer + HOST_OFFSET , remainLen);
responseNode.hostname[remainLen] = '\0';
LOCK_ON(&connectionMapLock) ;
ConnectionMap[connSocketFd].neighbourNode = responseNode;
LOCK_OFF(&connectionMapLock) ;
//Message not found in the cache
if (MessageCache.find( TO_STRING((const char *)original_uo_id, SHA_DIGEST_LENGTH) ) == MessageCache.end()){
//printf("[Reader]\tJOIN request was never forwarded from this node.\n") ;
return ;
}
else{
//message started here
if (MessageCache[ TO_STRING((const char *)original_uo_id, SHA_DIGEST_LENGTH)].status == 0){
//printf("[Reader-%d]\t +++++++++++++ JOIN request originated from node (%s : %d). Add to joinResponses list \n"
// , reqSockfd, responseNode.hostname, responseNode.portNo) ;
struct JoinResponseInfo jResp;
jResp.neighbourPortNo = responseNode.portNo;
for(int i=0;i<256;i++)
jResp.neighbourHostname[i] = responseNode.hostname[i];
jResp.location = distance ;
//pair<set<struct JoinResponseInfo>::iterator,bool> ret = joinResponses.insert(jResp) ;
joinResponses.push_back(jResp);
}
//message originated from somewhere else
else if(MessageCache[ TO_STRING((const char *)original_uo_id, SHA_DIGEST_LENGTH) ].status == 1){
handleNotMyMsg(original_uo_id, msgType, dataLen, buffer, uoid) ;
}
}
} else if(msgType == KEEPALIVE){
// printf("[Reader] \t handle KEEPALIVE \n");
fflush(stdout);
} // Notify message received
else if(msgType == NOTIFY) {
deleteFromNeighboursAndCloseConnection(connSocketFd);
}
else if(msgType == STORE_REQ)
{
// Check if packet was already received
printf("[Reader] \t Handle STORE request \n");
fflush(stdout);
string uoidStr = TO_STRING((const char *)uoid , SHA_DIGEST_LENGTH);
LOCK_ON(&msgCacheLock);
printf("[Reader]\t ...... MessageCache ............");
for(CACHEPACKET_MAP::iterator iter = MessageCache.begin(); iter!= MessageCache.end(); iter++) {
string sUoid = (*iter).first;
struct CachePacket pkt = (*iter).second;
printf("[Reader]\t\tuoid=%s , Packet{sock=%d, status=%d}\n",
sUoid.c_str(), pkt.reqSockfd, pkt.status );
}
printf("[Reader]\t lookup uoid:%s\n", uoidStr.c_str());
if(MessageCache.find(uoidStr) == MessageCache.end()) {
printf("[Reader] \t NEW Store request, couldn't find in MsgCache\n");
LOCK_OFF(&msgCacheLock);
CachePacket packet;
packet.msgLifetimeInCache =metadata->msgLifeTime;
packet.reqSockfd = connSocketFd;
packet.status = 1;
LOCK_ON(&msgCacheLock);
MessageCache[uoidStr] = packet;
LOCK_OFF(&msgCacheLock);
double coinFlip = drand48();
if(coinFlip <= metadata->storeProb) {
printf("[Reader] \tStore... accept and keep this store message locally\n");
//TODO:write file to cache
string strMetaData((char *)&buffer[4], dataLen);
struct FileMetadata fileMetadata ;//= readMetaDataFromStr(strMetaData.c_str());
//TODO: check the indexes if file exists
bool doesFileExist = false; // lookupIndices();
if(doesFileExist) {
// update the LRU
}
else
{
int fileNumber = incfNumber(); //update global file number
bool success=false;
// success = storeInLRU();
if(success) {
// write data
FILE* tempFile = fopen(tempFileName, "rb");
FILE* dataFile = fopen((char *)fileMetadata.fName, "wb");
char letter;
while(fread(&letter, 1, 1, tempFile)) {
fwrite(&letter, 1, 1, dataFile);
}
fclose(tempFile);
int closeRet = fclose(dataFile);
if(closeRet != 0) {
printf("[Reader] ERROR:Closing data file FAILED! Try emptying space!!\n");
} else {
printf("[Reader] \tStore... write metadata to file\n");
writeMetadataToFile(fileMetadata, fileNumber);
populateIndexes(fileMetadata , fileNumber);
}
}
}
printf("[Reader] \tStore... Flood to neighbours\n");
fflush(stdout);
//send to neighbours
LOCK_ON(¤tNeighboursLock);
NEIGHBOUR_MAP_ITERATOR iter = currentNeighbours.begin() ;
for(; iter!=currentNeighbours.end(); iter++) {
if((*iter).second != connSocketFd ) {
//if((double) drand48() > metadata->neighborStoreProb)
//continue;
printf("[Reader]\t Send to neighbour :%d\n", (*iter).second);
struct Message storeMessage;
storeMessage.dataLen= dataLen;
// set file name
int tmpFNameLength = strlen(tempFileName);
strncpy((char *)storeMessage.fileName , tempFileName, tmpFNameLength);
storeMessage.fileName[ tmpFNameLength ] = '\0';
if(ttl < metadata->ttl)
storeMessage.ttl= ttl;
else
storeMessage.ttl= metadata->ttl;
// message type and uoid
storeMessage.msgType = STORE_REQ;
MEMSET_ZERO(storeMessage.uoid, SHA_DIGEST_LENGTH);
memcpy(storeMessage.uoid , uoid, SHA_DIGEST_LENGTH);
storeMessage.buffer = (UCHAR *)malloc(dataLen);
MEMSET_ZERO(storeMessage.buffer, dataLen);
memcpy(storeMessage.buffer , buffer, dataLen);
// enqueue to be sent to neighbour
safePushMessageinQ(connSocketFd, storeMessage,"Reader");
} else {
printf("[Reader] \t Not sending to SELF\n");
}
}
LOCK_OFF(¤tNeighboursLock);
}
} else {
printf("[Reader]\t Store... request already present in cache, IGNORE\n");
LOCK_OFF(&msgCacheLock);
return;
}
printf("[Writer]\t Store... req handling done!!!\n");
}
//printf("[Reader] \t Reset keepalive\n");
fflush(stdout);
resetKeepAliveTimeout(connSocketFd) ;
// if(connectionMap[reqSockfd].keepAliveTimer!=0)
}
//This fnction pushes the NOTIFY message at the very begining of the message queue, so as to send it at priority
void sendNotificationOfShutdown(int resSock, uint8_t errorCode)
{
//printf("[Notify] Send -------> %d\n", resSock);
struct Message notifyMsg ;
notifyMsg.errorCode = errorCode ;
notifyMsg.status = 0 ;
notifyMsg.msgType = NOTIFY ;
//pushing the message and signaling the write thread
LOCK_ON(&ConnectionMap[resSock].mQLock) ;
printf("[Reader] LOCK_ON(%d) 6 \n",resSock);
ConnectionMap[resSock].MessageQ.push_back(notifyMsg) ;
LOCK_OFF(&ConnectionMap[resSock].mQLock) ;
printf("[Reader] LOCK_OFF(%d) 6 \n",resSock);
}
bool checkIfReaderLoopShouldBreak(long connSocket, bool doBreak)
{
LOCK_ON(&connectionMapLock) ;
//close connection if either of the condition occurs, jointime out, shutdown
if( globalShutdownToggle || ConnectionMap[connSocket].keepAliveTimeOut == -1 )//|| joinTimeOutFlag
{
//printf("[Reader-%d]\t breaking out of Reader loop\n", reqSockfd);
doBreak = true;
}
LOCK_OFF(&connectionMapLock) ;