-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracker.cpp
1439 lines (1281 loc) · 34.3 KB
/
tracker.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 <bits/stdc++.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <thread>
#include <signal.h>
#include <mutex>
#define MAX_LEN 4096
#define SOCKET_SIZE sizeof(struct sockaddr_in)
const int chunk_size = 1024 * 512; //512 KB
using namespace std;
char ip_port_delimiter[] = ":"; //for ip and port diffentiation
char afile_data_delimiter[] = "::"; // delimiter for AFile
char peer_data_delimiter[] = "||"; // delimiter for Peer
char glbl_data_delimiter[] = " "; //global delimiter
char peer_list_delimiter[] = "&&"; //to differentiate b/w many Peer data
string secret_prefix = "$$"; //denotes the string is not to be printed since it contains data
char server_prefix[] = "----"; //just for decoration
vector<string> stringSplit(string input, char delim[]);
// vector<string> deserializationCommand(string input, char delim[]);
// typedef pair<string, long> pairs;
class AFile
{
private:
string fileName;
long fileSize;
string fileHash;
public:
AFile() {}
// AFile(string &fileName_, long &fileSize_) : fileName(fileName_), fileSize(fileSize_)
// {
// }
AFile(string &fileName_, long &fileSize_, string &fileHash_) : fileName(fileName_),
fileSize(fileSize_), fileHash(fileHash_)
{
}
void setAFile(string &fileName_, long &fileSize_, string &fileHash_)
{
fileName = fileName_;
fileSize = fileSize_;
fileHash = fileHash_;
}
string getFileName()
{
return fileName;
}
string getFileHash()
{
return fileHash;
}
string serializeData()
{
return fileName + afile_data_delimiter + to_string(fileSize) + afile_data_delimiter + fileHash;
}
bool deserialize(string data)
{
auto parts = stringSplit(data, afile_data_delimiter);
if (parts.size() != 3)
return false;
long size = stol(parts[1]);
setAFile(parts[0], size, parts[2]);
return true;
}
};
class Peer
{
private:
string name;
string pword;
string ipAddress;
string port_no;
unordered_map<string, pair<AFile, int>> sharedFiles; //key = filename and value = pair of file object and no. of groups the file is shared
unordered_map<string, unordered_set<string>> sharedFilesInGroup; //key = group name and value = set of filenames
bool isOnline;
public:
void setIsOnline(bool status)
{
isOnline = status;
}
Peer() {}
Peer(string &name_, string &pword_) : name(name_), pword(pword_), isOnline(false)
{
}
Peer(string &name_, string &ipAddress_, string &port_no_) : name(name_),
isOnline(false), ipAddress(ipAddress_), port_no(port_no_)
{
}
Peer(string &name_, string &pword_, string &ipAddress_, string &port_no_) : name(name_), pword(pword_),
isOnline(false), ipAddress(ipAddress_), port_no(port_no_)
{
}
void operator=(const Peer &p1)
{
name = p1.name;
pword = p1.pword;
ipAddress = p1.ipAddress;
port_no = p1.port_no;
sharedFilesInGroup = p1.sharedFilesInGroup;
isOnline = p1.isOnline;
}
void addGroup(string &gname)
{
if (!isPresentInGroup(gname))
{
unordered_set<string> e;
sharedFilesInGroup[gname] = e;
}
}
unordered_set<string> getFileListByGroup(string &groupName)
{
return sharedFilesInGroup[groupName];
}
// void resetAllSharedFiles()
// {
// sharedFilesInGroup.clear();
// }
bool isPresentInGroup(string &gname)
{
if (sharedFilesInGroup.count(gname))
return true;
return false;
}
void deleteGroup(string &gname)
{
if (isPresentInGroup(gname))
{
for (auto file : sharedFilesInGroup[gname])
{
if (sharedFiles[file].second < 2)
sharedFiles.erase(file);
else
sharedFiles[file].second--;
}
sharedFilesInGroup.erase(gname);
}
}
void deleteAllSharedFilesByGroup(string &groupname)
{
for (auto filelist : sharedFilesInGroup[groupname])
deleteSharedFile(groupname, filelist);
}
void deleteSharedFile(string &groupname, string &filename)
{
sharedFiles[filename].second--;
if (sharedFiles[filename].second == 0)
sharedFiles.erase(filename);
sharedFilesInGroup[groupname].erase(filename);
}
void logout()
{
setIsOnline(false);
}
bool getIsOnline()
{
return isOnline;
}
string getName()
{
return name;
}
AFile getFileObject(string &groupname, string &filename)
{
//cerr << "here in getFileObject" << endl;
for (auto de : sharedFilesInGroup[groupname])
//cerr << de << ", ";
//cerr << endl;
if (sharedFilesInGroup[groupname].count(filename))
return sharedFiles[filename].first;
//cerr << "failed to find file obj for - " << groupname << ", " << filename << endl;
return AFile();
}
void addFile(AFile &afile, string &group_name)
{
//cerr << "here in addfile" << endl;
// for(auto de: sharedFilesInGroup[group_name])
// //cerr << de << ", ";
// //cerr << endl;
if (sharedFilesInGroup[group_name].count(afile.getFileName()))
return;
// //cerr << "now adding.." << endl;
sharedFilesInGroup[group_name].insert(afile.getFileName());
if (sharedFiles.count(afile.getFileName()))
sharedFiles[afile.getFileName()].second++;
else
sharedFiles[afile.getFileName()] = make_pair(afile, 1);
// for (auto de : sharedFilesInGroup[group_name])
//cerr << de << ", ";
//cerr << endl;
//cerr << "now other" << endl;
// for (auto de : sharedFiles)
//cerr << de.first << " " << de.second.first.serializeData() << " " << de.second.second << " => ";
//cerr << endl;
}
bool loginCondition(string &input_string)
{
auto parts = stringSplit(input_string, peer_data_delimiter);
//cerr << "logincondition: " << parts.size() << " " << this->isOnline << endl;
if (parts.size() == 2 and name == parts[0] and pword == parts[1] and !isOnline)
{
setIsOnline(true);
return true;
}
return false;
}
string serializeData1()
{
return name + peer_data_delimiter + pword + peer_data_delimiter + ipAddress + peer_data_delimiter + port_no;
}
string serializeData2()
{
return name + peer_data_delimiter + ipAddress + peer_data_delimiter + port_no;
}
void setPeer(string &name_, string &pword_)
{
name = name_;
pword = pword_;
}
void setPeer(string &name_, string &ipAddress_, string &port_no_)
{
name = name_;
ipAddress = ipAddress_;
port_no = port_no_;
}
void setPeer(string &name_, string &pword_, string &ipAddress_, string &port_no_)
{
setPeer(name_, pword_);
setPeer(name_, ipAddress_, port_no_);
}
bool deserializeData1(string data)
{
auto parts = stringSplit(data, peer_data_delimiter);
if (parts.size() == 4)
{
setPeer(parts[0], parts[1], parts[2], parts[3]);
return true;
}
return false;
}
bool deserializeData2(string data)
{
auto parts = stringSplit(data, peer_data_delimiter);
if (parts.size() == 3)
{
setPeer(parts[0], parts[1], parts[2]);
return true;
}
return false;
}
string serializeData3()
{
return name + peer_data_delimiter + pword;
}
bool deserializeData3(string data)
{
auto parts = stringSplit(data, peer_data_delimiter);
if (parts.size() == 2)
{
setPeer(parts[0], parts[1]);
return true;
}
return false;
}
string dumps()
{
string msg = serializeData3() + "==>\n";
bool flag = true;
for (auto file_ : sharedFiles)
{
msg += file_.second.first.serializeData() + "--" + to_string(file_.second.second) + ", ";
flag = false;
}
if (flag)
msg += "no file";
msg += "\n";
flag = true;
for (auto fl : sharedFilesInGroup)
{
msg += fl.first + ", ";
flag = false;
}
if (flag)
msg += "No Group\n";
return msg;
}
};
class Group
{
private:
string groupName;
string groupAdmin;
unordered_map<string, Peer> groupMembers; //key == peer name and value = peer object
unordered_map<string, unordered_set<string>> sharedFiles; //key = file name and value = set of strings peer name
void deleteAllSharedFilesByPeer(Peer &peer)
{
for (auto filename : peer.getFileListByGroup(groupName))
{
if (sharedFiles.count(filename) and sharedFiles[filename].count(peer.getName()))
{
if (sharedFiles[filename].size() < 2)
{
sharedFiles.erase(filename);
}
else
sharedFiles[filename].erase(peer.getName());
}
}
}
public:
Group() {}
Group(string &groupName_, string &groupAdmin_) : groupName(groupName_), groupAdmin(groupAdmin_)
{
}
bool isAdmin(string &name)
{
return groupAdmin == name;
}
string serialize()
{
string res = groupName + "=" + groupAdmin + " -> \n";
res += "members: ";
for (auto gm : groupMembers)
res += gm.second.serializeData3() + " ";
res += "\nfiles: ";
for (auto sf : sharedFiles)
res += sf.first + ", ";
return res;
}
unordered_set<string> getSetOfPeerNamesByFile(string &filename)
{
return sharedFiles[filename];
}
int getNoOfPeersWithFile(string &filename)
{
if (sharedFiles.count(filename))
return sharedFiles[filename].size();
return -1;
}
bool addGroupMember(Peer &peer)
{
// for (auto member = groupMembers.begin(); member != groupMembers.end(); ++member)
// {
// if (member->getName() == peer.getName())
// {
// return false;
// }
// }
if (groupAdmin == "")
groupAdmin = peer.getName();
// groupMembers.push_back(peer);
if (groupMembers.count(peer.getName()))
return false;
groupMembers[peer.getName()] = peer;
return true;
}
bool addSharedFile(string &filename, string &owner)
{
if (sharedFiles[filename].count(owner))
return false;
sharedFiles[filename].insert(owner);
return true;
}
bool isMember(string &peer_name)
{
// for (auto peer_ : groupMembers)
// if (peer_.getName() == peer_name)
// return true;
if (groupMembers.count(peer_name))
return true;
return false;
}
bool deleteSharedFile(string &filename, Peer &peer)
{
if (filePresent(filename))
{
//cerr << "in delete shared file : file found" << endl;
if (sharedFiles[filename].count(peer.getName()))
{
sharedFiles[filename].erase(peer.getName());
if (sharedFiles[filename].empty())
sharedFiles.erase(filename);
return true;
}
}
return false;
}
string getShareableFilesNames()
{
string msg = "";
for (auto file : sharedFiles)
msg += file.first + '\n';
return msg;
}
bool filePresent(string &file_name)
{
return sharedFiles.count(file_name);
}
string getAllPeersForFileSerialized(string &filename)
{
string firstPart = groupName;
string secondPart = "";
int i = 0;
string thirdPart = "";
int n = sharedFiles[filename].size();
//cerr << "inside all peers for file : " << endl;
for (auto peer : sharedFiles[filename])
{
//cerr << "peer - " << peer << endl;
if (i == 0)
secondPart = groupMembers[peer].getFileObject(groupName, filename).serializeData();
thirdPart += groupMembers[peer].serializeData1();
if (i + 1 < n)
thirdPart += peer_list_delimiter;
i++;
}
return firstPart + glbl_data_delimiter + secondPart + glbl_data_delimiter + thirdPart;
}
int getNoOfMembers()
{
return groupMembers.size();
}
bool deleteGroupMember(Peer &peer)
{
// for (auto member = groupMembers.begin(); member != groupMembers.end(); ++member)
// {
// if (member->getName() == peer.getName())
// {
if (groupMembers.count(peer.getName()))
{
if (peer.getName() == groupAdmin)
{
if (groupMembers.size() == 1)
{
groupAdmin = "";
}
else
{
for (auto peer_ : groupMembers)
{
if (peer_.first != peer.getName())
{
groupAdmin = peer_.first;
break;
}
}
}
}
deleteAllSharedFilesByPeer(peer);
groupMembers.erase(peer.getName());
return true;
}
return false;
}
};
struct terminal
{
int id;
string peer_name;
int socket;
thread th;
};
unordered_map<string, Peer> all_peers;
unordered_map<string, Group> all_groups;
unordered_map<string, unordered_set<string>> all_requests; //key = group name and value = set of peer names
vector<terminal> all_peers_terminals;
int seed = 0;
mutex cout_mtx, all_peers_mtx, all_peers_terminals_mtx, all_requests_mtx, all_groups_mtx, peer_thread_mtx;
// void set_name(int id, char name[]);
// void broadcast_message(string message, int sender_id);
// void broadcast_message(int num, int sender_id);
void end_connection(int id);
void handle_client(int client_socket, int id);
bool userPresent(string &uname);
int tracker_socket_descriptor;
class Socket
{
public:
int socketDescriptor;
struct sockaddr_in socketAddr;
Socket() {}
Socket(string &ip_address, string &port)
{
if ((socketDescriptor = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket error: ");
exit(-1);
}
socketAddr.sin_family = AF_INET;
socketAddr.sin_port = htons(stoi(port));
socketAddr.sin_addr.s_addr = INADDR_ANY;
socketAddr.sin_addr.s_addr = inet_addr(ip_address.c_str());
bzero(&socketAddr.sin_zero, 0);
}
~Socket()
{
close(socketDescriptor);
}
void bindConnection()
{
if ((bind(socketDescriptor, (struct sockaddr *)&socketAddr, SOCKET_SIZE)) == -1)
{
perror("bind error: ");
exit(-1);
}
}
void startServerConnection()
{
bindConnection();
if ((listen(socketDescriptor, 8)) == -1)
{
perror("listen error: ");
exit(-1);
}
}
void acceptConnectionAtServer(Socket *clientSocket)
{
unsigned long adr_size = SOCKET_SIZE;
if ((clientSocket->socketDescriptor = accept(socketDescriptor, (struct sockaddr *)&clientSocket->socketAddr, (socklen_t *)&adr_size)) == -1)
{
perror("accept error: ");
}
else
{
cout << "*|*|* "
<< " " << clientSocket->socketAddr.sin_port << endl;
char ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(clientSocket->socketAddr.sin_addr), ip, INET_ADDRSTRLEN);
// "ntohs(peer_addr.sin_port)" function is
// for finding port number of client
printf("connection established with IP : %s and PORT : %d\n", ip, ntohs(clientSocket->socketAddr.sin_port));
}
}
int connectAtClient(int clientSocketDescriptor)
{
if ((connect(clientSocketDescriptor, (struct sockaddr *)&socketAddr, SOCKET_SIZE)) == -1)
{
perror("connect: ");
return -1;
}
return 0;
}
void closeConnection()
{
// close(server_socket);
}
};
vector<string> stringSplit(string input, char delim[])
{
vector<string> arr;
char *inp = &input[0];
char *token = strtok(inp, delim);
while (token)
{
string s(token);
arr.push_back(s);
token = strtok(NULL, delim);
}
return arr;
}
void get_tracker_ip_and_port(string file_name, string &ip_address, string &port)
{
fstream newfile;
newfile.open(file_name, ios::in);
if (newfile.is_open())
{
string tp;
if (getline(newfile, tp))
{
auto entries = stringSplit(tp, ip_port_delimiter);
ip_address = entries[0];
port = entries[1];
}
newfile.close();
}
}
void catch_ctrl_c(int signal)
{
close(tracker_socket_descriptor);
exit(signal);
}
int main(int argc, char **argv)
{
string ip_address, port;
if (argc > 1)
get_tracker_ip_and_port(argv[1], ip_address, port);
else
get_tracker_ip_and_port("tracker.txt", ip_address, port);
Socket tracker(ip_address, port);
tracker.startServerConnection();
tracker_socket_descriptor = tracker.socketDescriptor;
signal(SIGINT, catch_ctrl_c);
cout << "Now starting tracker. Accepting peers..." << endl;
Socket client;
while (true)
{
tracker.acceptConnectionAtServer(&client);
if (client.socketDescriptor < 0)
{
cout << "failure in connection" << endl;
continue;
}
seed++;
thread t(handle_client, client.socketDescriptor, seed);
lock_guard<mutex> guard(all_peers_terminals_mtx);
all_peers_terminals.push_back({seed, string("Anonymous"), client.socketDescriptor, (move(t))});
// cout << "done with here" << endl;
}
for (int i = 0; i < all_peers_terminals.size(); i++)
{
if (all_peers_terminals[i].th.joinable())
all_peers_terminals[i].th.join();
}
// tracker.closeConnection();
return 0;
}
// For synchronisation of cout statements
void shared_print(string str, bool endLine = true)
{
lock_guard<mutex> guard(cout_mtx);
cout << str;
if (endLine)
cout << endl;
}
void send_message(string message, const terminal *const peerThreadObj)
{
char temp[MAX_LEN];
strcpy(temp, message.c_str());
send(peerThreadObj->socket, temp, sizeof(temp), 0);
}
void send_message(int num, const terminal *const peerThreadObj)
{
send(peerThreadObj->socket, &num, sizeof(num), 0);
}
void end_connection(int id)
{
for (int i = 0; i < all_peers_terminals.size(); i++)
{
if (all_peers_terminals[i].id == id)
{
if (userPresent(all_peers_terminals[i].peer_name))
{
string uname = all_peers_terminals[i].peer_name;
lock_guard<mutex> lck(all_peers_mtx);
all_peers[uname].setIsOnline(false);
}
lock_guard<mutex> guard(all_peers_terminals_mtx);
all_peers_terminals[i].th.detach();
all_peers_terminals.erase(all_peers_terminals.begin() + i);
close(all_peers_terminals[i].socket);
break;
}
}
}
void failure_case(const terminal *const peerThreadObject)
{
send_message("Operation Unsucessful. Try again with correct input, Also ensure you are logged in.", peerThreadObject);
}
void failure_case(const terminal *const peerThreadObject, vector<string> &input_in_parts)
{
send_message("Operation Unsucessful. Try again with correct input, Also ensure you are logged in.", peerThreadObject);
//cerr << "failure case :- ";
// for (auto inp : input_in_parts)
//cerr << inp << " ";
//cerr << endl;
}
bool groupPresent(string &gname)
{
return all_groups.count(gname);
}
bool isMember(string &group_name, string &peer_name)
{
return all_groups[group_name].isMember(peer_name);
}
bool userPresent(string &uname)
{
return all_peers.count(uname);
}
bool test_condition(const terminal *const peerThreadObj, vector<string> &input_in_parts, int n)
{
if (input_in_parts.size() == n)
return true;
failure_case(peerThreadObj, input_in_parts);
return false;
}
void create_user(terminal *const peerThreadObj, vector<string> &input_in_parts)
{
if (test_condition(peerThreadObj, input_in_parts, 2))
{
Peer newPear;
if (newPear.deserializeData1(input_in_parts[1]))
{
string uname = newPear.getName();
if (userPresent(uname))
{
send_message("User already exists", peerThreadObj);
return;
}
unique_lock<mutex> lck(all_peers_mtx);
all_peers[uname] = newPear;
lck.unlock();
// unique_lock<mutex> ulck(peer_thread_mtx);
peerThreadObj->peer_name = uname;
// ulck.unlock();
send_message("User successfully created.", peerThreadObj);
}
else
{
send_message("Incorrect input.", peerThreadObj);
//cerr << "*** " << input_in_parts[1] << endl;
}
}
}
void login(terminal *const peerThreadObj, vector<string> &input_in_parts, bool &is_login_success)
{
if (input_in_parts.size() == 1)
{
failure_case(peerThreadObj, input_in_parts);
return;
}
Peer peer_;
if (!peer_.deserializeData3(input_in_parts[1]))
{
send_message("Incorrect Input - try again", peerThreadObj);
return;
}
string pname = peer_.getName();
if (!userPresent(pname))
{
send_message("You aren\'t signed up", peerThreadObj);
}
else
{
unique_lock<mutex> ulck(all_peers_mtx);
if (all_peers[pname].loginCondition(input_in_parts[1]))
{
ulck.unlock();
send_message("## You are successfully Logged In in the network.", peerThreadObj);
is_login_success = true;
peerThreadObj->peer_name = peer_.getName();
send_message(input_in_parts[0] + glbl_data_delimiter + "1", peerThreadObj);
}
else
{
send_message("Incorrect credentials or already logged in.", peerThreadObj);
//cerr << "Failed to log in " << input_in_parts[1] << endl;
}
}
}
void join_group(const terminal *const peerThreadObj, vector<string> &input_in_parts)
{
if (test_condition(peerThreadObj, input_in_parts, 2))
{
string pname = peerThreadObj->peer_name;
string gname = input_in_parts[1];
string msg;
if (groupPresent(gname))
{
lock_guard<mutex> lck(all_groups_mtx);
all_requests[gname].insert(pname);
msg = "Request Recieved. Wait for approval.";
}
else
msg = "No such group";
send_message(msg, peerThreadObj);
}
}
void create_group(const terminal *const peerThreadObj, vector<string> &input_in_parts)
{
if (test_condition(peerThreadObj, input_in_parts, 2))
{
string pname = peerThreadObj->peer_name;
string gname = input_in_parts[1];
string msg;
bool responseFlag = false;
if (!groupPresent(gname))
{
Group newGroup(gname, pname);
if (newGroup.addGroupMember(all_peers[pname]))
{
unique_lock<mutex> lck(all_groups_mtx);
all_groups[gname] = newGroup;
lck.unlock();
lock_guard<mutex> grd(all_peers_mtx);
all_peers[pname].addGroup(gname);
msg = "## Group successfully created with you as admin.";
responseFlag = true;
}
else
msg = "You are already a member. Cannot join again";
}
else
msg = "Group with this name already present";
send_message(msg, peerThreadObj);
if (responseFlag)
send_message(input_in_parts[0] + glbl_data_delimiter + "1", peerThreadObj);
}
}
void leave_group(const terminal *const peerThreadObj, vector<string> &input_in_parts)
{
if (test_condition(peerThreadObj, input_in_parts, 2))
{
string pname = peerThreadObj->peer_name;
string gname = input_in_parts[1];
string msg;
bool flag = true, responseFlag = false;
if (groupPresent(gname))
{
//cerr << "here in leave_group" << endl;
if (all_groups[gname].getNoOfMembers() == 1)
{
unique_lock<mutex> ulck(all_groups_mtx);
all_groups.erase(gname);
ulck.unlock();
lock_guard<mutex> lck(all_peers_mtx);
all_peers[pname].deleteGroup(gname);
//cerr << "inside first condition in leave_group: after deletion" << endl;
}
else if (all_groups[gname].getNoOfMembers() > 1)
{
unique_lock<mutex> lck(all_groups_mtx);
if (!all_groups[gname].deleteGroupMember(all_peers[pname]))
{
msg = "You are not part of the group.";
flag = false;
//cerr << "here in 2.a in leave_group" << endl;
}
else
{
lck.unlock();
lock_guard<mutex> lgd(all_peers_mtx);
all_peers[pname].deleteGroup(gname);
//cerr << "2.b : deleted successfully group member" << endl;
}
}
else
//cerr << "third condition in leave_group" << endl;
if (flag)
{
msg = "## You are no longer in the group. All files shared by you have been removed.";
responseFlag = true;
}
}
else
msg = "No Such Group";
send_message(msg, peerThreadObj);
if (responseFlag)
send_message(input_in_parts[0] + glbl_data_delimiter + "1", peerThreadObj);
}
}
void requests_list_requests(const terminal *const peerThreadObj, vector<string> &input_in_parts)
{
if (test_condition(peerThreadObj, input_in_parts, 3))
{
string pname = peerThreadObj->peer_name;
string query = input_in_parts[1];
string gname = input_in_parts[2];
string msg;
if (query == "list_requests" and groupPresent(gname))
{
// lock_guard<mutex> lck(all_requests_mtx);
if (all_requests.count(gname) and !all_requests[gname].empty())
{
msg = "All peers requesting to join are:\n";
for (auto member : all_requests[gname])
{
msg += member + "\n";
}
}
else
msg = "No new Request for this group";
}
else
msg = "Invalid Group Id";
send_message(msg, peerThreadObj);
}
}