-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy_frontend.cpp
1308 lines (1134 loc) · 46.8 KB
/
proxy_frontend.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
// Bernie Birnbaum and Shawyoun Saidon
// Comp 112 Final Project
// Tufts University
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
#include <iostream>
#include <math.h>
#include <iomanip>
#include "player.h"
#include <openssl/sha.h>
using namespace std;
#define HEADERSIZE 50
#define MAXDATASIZE 150000
#define MAXCLIENTS 200
#define IDLENGTH 20 // Includes null character
#define TEAMSIZE 12
#define HELLO 1
#define HELLO_ACK 2
#define LIST_REQUEST 3
#define CLIENT_LIST 4
#define CHAT 5
#define EXIT 6
#define ERROR 7
#define CANNOT_DELIVER 8
#define PLAYER_REQUEST 9
#define PLAYER_RESPONSE 10
#define DRAFT_REQUEST 11
#define PING 12
#define PING_RESPONSE 13
#define START_DRAFT 14
#define DRAFT_STATUS 15
#define DRAFT_STARTING 16
#define DRAFT_ROUND_START 17
#define DRAFT_ROUND_RESULT 18
#define BAD_EXIT 19 /* Shawyoun */
struct header {
unsigned short type;
char sourceID[IDLENGTH];
char destID[IDLENGTH];
unsigned int dataLength;
unsigned int msgID;
}__attribute__((packed, aligned(1)));
struct clientInfo {
int sock;
char ID[IDLENGTH];
bool active;
int mode; /* TODO Shawyoun: will there need to be a mode for backend? */
int modeForWrite;
int headerToRead;
int headerToWrite; /* Shawyoun */
char partialHeader[HEADERSIZE];
char partialHeaderForWrite[HEADERSIZE]; /* Shawyoun */
int dataToRead;
int dataToWrite; /* Shawyoun */
int totalDataExpected;
int totalDataExpectedToWrite; /* Shawyoun */
char partialData[MAXDATASIZE];
char partialDataForWrite[MAXDATASIZE]; /* Shawyoun */
char destID[IDLENGTH];
char destIDForWrite[IDLENGTH]; /* Shawyoun */
int msgID;
int msgIDForWrite; /* Shawyoun */
int pwordToRead;
int pwordToWrite; /* Shawyoun: don't expect to use this */
int totalPwordExpected;
int totalPwordExpectedtoWrite; /* Shawyoun: don't expect to use this */
char pword[65];
bool validated;
int pingID;
int pings;
struct timeval lastPingSent;
float estRTT;
float devRTT;
float timeout;
bool readyToDraft;
/* Shawyoun */
char fullHeaderToRead[HEADERSIZE];
char fullPwordToRead[65];
char fullDataToRead[MAXDATASIZE]; /* TODO: this needs to be used too. for now we've only incorporated fullPwordToRead because that's the equivalent of "data" for HELLO */
char fullHeaderToWrite[HEADERSIZE];
char fullPwordToWrite[65]; /* Shawyoun: don't think this will be used */
char fullDataToWrite[MAXDATASIZE];
/* End Shawyoun */
}__attribute__((packed, aligned(1)));
struct team
{
char owner[20];
int playersDrafted;
timeval adjustedTimeReceived;
playerInfo players[TEAMSIZE];
};
struct draftInfo {
int index;
int currentRound;
timeval roundEndTime;
vector<team> teams;
};
struct clientInfo clients[MAXCLIENTS];
int clientCounter = 0;
int numClients = 0;
int maxDelay = 0;
bool pingNow = false;
bool draftStarted;
struct draftInfo theDraft;
timeval roundEndTime;
//struct timeval selectTimeout = {1,0};
vector<playerInfo> playerData;
const float minTimeout = 50.0;
const float alpha = 0.875;
const float beta = 0.25;
char currentClientIDFromBackEndServer[IDLENGTH]; /* Shawyoun */
/*TODO Shawyoun: you'll have to reset currentClientIDFromBackEndServer just like on backend */
int backEndServerSock; /* Shawyoun */
void error(const char *msg)
{
perror(msg);
exit(1);
}
void readFromClient(int sockfd);
void readHeader(struct clientInfo *curClient, int sockfd);
void readData(struct clientInfo *curClient);
void readPword(struct clientInfo *curClient);
/* TODO Shawyoun: either write different methods or branch the logic within the method, so that it behaves differently if it's the backend "client" */
void handleHello(struct clientInfo *curClient);
void handleListRequest(struct clientInfo *curClient);
void handleChat(struct clientInfo *curClient);
void handleExit(struct clientInfo *curClient);
void handleClientPresent(struct clientInfo *curClient, char *ID);
void handleCannotDeliver(struct clientInfo *curClient);
void handleError(struct clientInfo *curClient);
void handlePlayerRequest(struct clientInfo *curClient);
void handleDraftRequest(struct clientInfo *curClient);
void handleStartDraft(struct clientInfo *curClient);
void handlePingResponse(struct clientInfo *curClient);
void sendPing(struct clientInfo *curClient);
void sendStartDraft();
void draftNewRound();
void endDraftRound();
void readFromClientForBackEnd(); /* Shawyoun */
void readHeaderForBackEnd(struct clientInfo *curClient); /* Shawyoun */
void readDataForBackEnd(struct clientInfo *curClient); /* Shawyoun */
void handleHelloACK(struct clientInfo* curClient); /* Shawyoun */
void handleClientList(struct clientInfo* curClient); /* Shawyoun */
void handlePlayerResponse(struct clientInfo* curClient); /* Shawyoun */
void handleChatForWrite(struct clientInfo * curClient); /* Shawyoun */
void handleCannotDeliver(struct clientInfo * curClient); /* Shawyoun */
void handleErrorForWrite(struct clientInfo * curClient); /* Shawyoun */
void handleBadExit(struct clientInfo *curClient); /* Shawyoun */
string sha256(const string str);
fd_set active_fd_set, read_fd_set; // Declared here so all functions can use
int main(int argc, char *argv[])
{
// TODO: Give more options than this hard coded file
playerData = readCSV("nba1516.csv");
//for(int i = 0; i < playerData.size(); i++) {
//cout << playerToString(playerData[i]) << '\n';
//}
memset(&clients, 0, sizeof(clients));
int sockfd, newsockfd, portno, pid, i;
//int clientCounter = 0;
socklen_t clilen;
struct sockaddr_in frontend_addr, cli_addr; /* Shawyoun */
/* Shawyoun: add more arguments to specify the backend server */
if (argc < 4) {
fprintf(stderr,"Usage: ./proxy_frontend <frontendport> backendhostname <backendport>");
exit(1);
}
/* Shawyoun */
char * backEndHost = argv[2];
int backEndPort = atoi(argv[3]);
struct hostent * backEndServer;
struct sockaddr_in backend_addr;
/* End Shawyoun */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
backEndServerSock = socket(AF_INET, SOCK_STREAM, 0); /* Shawyoun */
if (sockfd < 0 || backEndServerSock < 0) /* Shawyoun */
error("ERROR opening socket");
/* Shawyoun */
backEndServer = gethostbyname(backEndHost);
if(backEndServer == NULL) error("ERROR, no such host");
memset(&backend_addr,0,sizeof(backend_addr));
backend_addr.sin_family = AF_INET;
backend_addr.sin_port = htons(backEndPort);
memcpy(&backend_addr.sin_addr.s_addr,backEndServer->h_addr,backEndServer->h_length);
if(connect(backEndServerSock,(struct sockaddr *)&backend_addr,sizeof(backend_addr)) < 0) error("ERROR connecting");
/* connected = true; Shawyoun */
fprintf(stdout, "Connected to the backend server!\n");
/* end Shawyoun */
bzero((char *) &frontend_addr, sizeof(frontend_addr));
portno = atoi(argv[1]); // Get port number from args
frontend_addr.sin_family = AF_INET;
frontend_addr.sin_addr.s_addr = INADDR_ANY;
frontend_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &frontend_addr,
sizeof(frontend_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
FD_ZERO(&active_fd_set);
FD_SET(sockfd, &active_fd_set);
FD_SET(backEndServerSock, &active_fd_set); /* Shawyoun */
clilen = sizeof(cli_addr);
/* TODO Shawyoun: Connect to backend server before doing anything else. Make sure to add this file descriptor to the set */
while(1) {
/* if(draftStarted) {
timeval curTime;
gettimeofday(&curTime,NULL);
fprintf(stderr, "curTime - roundEndTime: %d\n", curTime.tv_sec - theDraft.roundEndTime.tv_sec);
if(curTime.tv_sec > theDraft.roundEndTime.tv_sec) {
endDraftRound();
//break;
}
}
if(pingNow) {
for(int i = 0; i < MAXCLIENTS; i++) {
if(clients[i].active) {
sendPing(&clients[i]);
}
}
}
//fprintf(stderr, "While again\n");
pingNow = true; */
struct timeval selectTimeout = {5,0};
read_fd_set = active_fd_set;
/* Block until input arrives on one or more active sockets */
if(select(FD_SETSIZE, &read_fd_set, NULL, NULL, &selectTimeout) < 0) {
error("ERROR on select");
}
/* Service all the sockets with input pending */
for(i = 0; i < FD_SETSIZE; i++) { //FD_SETSIZE == 1024
if(FD_ISSET(i, &read_fd_set)) {
/* pingNow = false; */
if(i == sockfd) {
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if(newsockfd < 0)
error("ERROR on accept");
/* make and insert new clientInfo record */
struct clientInfo newClient;
memset(&newClient, 0, sizeof(newClient));
newClient.sock = newsockfd;
newClient.headerToRead = HEADERSIZE;
newClient.active = true;
newClient.validated = false;
newClient.timeout = 5000;
newClient.readyToDraft = false;
bool inserted = false;
while(!inserted) {
if(clients[clientCounter].sock == NULL) {
clients[clientCounter] = newClient;
inserted = 1;
}
clientCounter++;
numClients++;
clientCounter = clientCounter % MAXCLIENTS;
}
fprintf(stderr, "New connection with newsockfd: %d\n", newsockfd);
// fprintf(stderr, "Server: connect from host %s, port %hu. \n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
FD_SET(newsockfd, &active_fd_set);
} else if(i == backEndServerSock){ /* Shawyoun */
fprintf(stderr, "Data came in from backend\n");
/* TODO Shawyoun: fill this out */
readFromClientForBackEnd();
}
else {
/* Data arriving on an already-connected socket */
readFromClient(i);
}
}
}
}
close(sockfd);
return 0;
}
void readFromClient (int sockfd) {
int i;
struct clientInfo *curClient;
//fprintf(stderr, "sockfd: %d\n", sockfd);
/* get client address based on sockfd */
for(i = 0; i < MAXCLIENTS; i++) {
if(clients[i].sock == sockfd) {
if(clients[i].active) {
curClient = &clients[i];
break;
} else {
struct clientInfo newClient;
memset(&newClient, 0, sizeof(newClient));
newClient.sock = sockfd;
newClient.headerToRead = HEADERSIZE;
newClient.active = true;
newClient.validated = false;
int inserted = 0;
while(inserted == 0) {
if(clients[clientCounter].sock == NULL) {
clients[clientCounter] = newClient;
inserted = 1;
}
clientCounter++;
clientCounter = clientCounter % MAXCLIENTS;
}
//fprintf(stderr, "New client made with previously existing sockfd: %d\n", sockfd);
}
}
}
/* data takes precedence over headers since headerToRead should always
be > 0 */
if(curClient->pwordToRead > 0) {
readPword(curClient);
} else if(curClient->dataToRead > 0) {
readData(curClient);
} else if(curClient->headerToRead > 0) {
readHeader(curClient, sockfd);
} else {
error("ERROR: headerToRead and dataToRead not > 0");
}
}
void readHeader(struct clientInfo *curClient, int sockfd) {
char header_buffer[HEADERSIZE];
int nbytes;
/* Shawyoun */
fprintf(stderr, "Partial header: ");
fprintf(stderr, (char*)&curClient->partialHeader);
/*End Shawyoun */
/* retrieve what has already been read of the header */
memcpy(header_buffer, curClient->partialHeader, HEADERSIZE);
/* try to read the rest of the header */
nbytes = read (curClient->sock, &header_buffer[HEADERSIZE-curClient->headerToRead],curClient->headerToRead);
//fprintf(stderr, "readHeader client: %s, nbytes: %d, expected readsize: %d\n",curClient->ID, nbytes,curClient->headerToRead);
if (nbytes <= 0) {
/* Read error or EOF: Socket closed */
// TODO: Pause mode
handleBadExit(curClient); /* Shawyoun */
} else if (nbytes < curClient->headerToRead) {
/* Shawyoun */
fprintf(stderr, "Partial header: ");
fprintf(stderr, curClient->partialHeader);
/*End Shawyoun */
/* still more to read */
curClient->headerToRead = curClient->headerToRead - nbytes;
memcpy(curClient->partialHeader, header_buffer, HEADERSIZE);
} else {
/* Parse header. */
/* Shawyoun */
fprintf(stderr, "Partial header: ");
fprintf(stderr, (char*)&curClient->partialHeader);
/*End Shawyoun */
struct header newHeader;
memcpy((char *)&newHeader, &header_buffer[0], HEADERSIZE);
memcpy(&curClient->fullHeaderToRead, &header_buffer[0], HEADERSIZE); /* Shawyoun */
newHeader.type = ntohs(newHeader.type);
newHeader.dataLength = ntohl(newHeader.dataLength);
newHeader.msgID = ntohl(newHeader.msgID);
curClient->headerToRead = HEADERSIZE;
fprintf (stderr, "Read-in header: type: %hu, sourceID: %s, destID: %s, dataLength: %u, msgID: %u\n", newHeader.type, newHeader.sourceID, newHeader.destID, newHeader.dataLength, newHeader.msgID);
/* next step depends on header type */
if(newHeader.type == HELLO) {
curClient->totalPwordExpected = newHeader.dataLength;
curClient->pwordToRead = newHeader.dataLength;
memcpy(curClient->ID, newHeader.sourceID, IDLENGTH);
} else if(newHeader.type == LIST_REQUEST) {
handleListRequest(curClient);
} else if(newHeader.type == CHAT) {
/* store information about CHAT in clientInfo struct */
curClient->msgID = newHeader.msgID;
memcpy(curClient->destID, newHeader.destID, 20);
curClient->mode = CHAT;
curClient->dataToRead = newHeader.dataLength;
curClient->totalDataExpected = newHeader.dataLength;
} else if(newHeader.type == EXIT) {
/* No need to check for errors,
we're kicking the client out anyway! */
curClient->active = false;
curClient->validated = false;
handleExit(curClient);
} else if(newHeader.type == PLAYER_REQUEST) {
//string augCSV = vectorToAugmentedCSV(playerData);
handlePlayerRequest(curClient);
} else if(newHeader.type == DRAFT_REQUEST) {
memset(curClient->partialData, 0, MAXDATASIZE);
curClient->mode = DRAFT_REQUEST;
curClient->dataToRead = newHeader.dataLength;
curClient->totalDataExpected = newHeader.dataLength;
}/*else if(newHeader.type == PING_RESPONSE) {
memset(curClient->partialData,0,MAXDATASIZE);
curClient->mode = PING_RESPONSE;
curClient->msgID = newHeader.msgID;
curClient->dataToRead = newHeader.dataLength;
curClient->totalDataExpected = newHeader.dataLength;
} else if(newHeader.type == START_DRAFT) {
handleStartDraft(curClient);
}*/else {
fprintf(stderr, "ERROR: bad header type\n");
/* Shawyoun handleError(curClient); */
return;
}
}
}
void readData(struct clientInfo *curClient) {
/* same logic for reading as in readHeader */
char data_buffer[curClient->totalDataExpected];
int nbytes;
memcpy(data_buffer, curClient->partialData, curClient->totalDataExpected);
nbytes = read (curClient->sock, &data_buffer[curClient->totalDataExpected-curClient->dataToRead],curClient->dataToRead);
//fprintf(stderr, "nbytes: %d, expected readsize: %d\n",nbytes,curClient->dataToRead);
if (nbytes <= 0) {
/* Read error or EOF */
handleBadExit(curClient); /* Shawyoun */
} else if (nbytes < curClient->dataToRead) {
/* still more data to read */
curClient->dataToRead = curClient->dataToRead - nbytes;
memcpy(curClient->partialData, data_buffer, curClient->totalDataExpected);
} else {
/* All data has been read */
memcpy(curClient->partialData, data_buffer, curClient->totalDataExpected);
memcpy(curClient->fullDataToRead, data_buffer, curClient->totalDataExpected); /* Shawyoun */
fprintf(stderr,"Message read in: curClient->partialData: %s\n",curClient->partialData);
curClient->dataToRead = 0;
if(curClient->mode == CHAT) {
handleChat(curClient);
} else if(curClient->mode == DRAFT_REQUEST) {
handleDraftRequest(curClient);
} else if(curClient->mode == PING_RESPONSE) {
handlePingResponse(curClient);
} else {
fprintf(stderr, "ERROR: Done reading data but client in invalid mode\n");
/* Shawyoun handleError(curClient); */
}
}
}
void readPword(struct clientInfo *curClient) {
char data_buffer[curClient->totalPwordExpected];
int nbytes;
memcpy(data_buffer, curClient->pword, curClient->totalPwordExpected);
nbytes = read (curClient->sock, &data_buffer[curClient->totalPwordExpected - curClient->pwordToRead], curClient->pwordToRead);
//fprintf(stderr, "nbytes: %d, expected readsize of pword: %d\n", nbytes, curClient->pwordToRead);
if (nbytes <= 0) {
/* Read error or EOF */
handleBadExit(curClient); /* Shawyoun */
} else if (nbytes < curClient->pwordToRead) {
/* still more pword to read */
curClient->pwordToRead = curClient->pwordToRead - nbytes;
memcpy(curClient->pword, data_buffer, curClient->totalPwordExpected);
} else {
/* TODO Shawyoun: remove hashing from frontend */
/* entire password read */
memcpy(curClient->pword, data_buffer, curClient->totalPwordExpected); /* Shawyoun */
memcpy(curClient->fullPwordToRead, data_buffer, curClient->totalPwordExpected); /* Shawyoun */
fprintf(stderr, "Password read in: curClient->password: %s\n", curClient->pword);
curClient->pwordToRead = 0;
handleHello(curClient);
}
}
void handleHello(struct clientInfo *curClient) {
/* Shawyoun */
fprintf(stderr, "reached handleHello. Header: %s\n Password: %s\n PasswordLength: %i\n", curClient->fullHeaderToRead, curClient->fullPwordToRead, curClient->totalPwordExpected);
write(backEndServerSock, (char*)&curClient->fullHeaderToRead, HEADERSIZE);
bzero(curClient->fullHeaderToRead, HEADERSIZE);
write(backEndServerSock, (char*)&curClient->fullPwordToRead, curClient->totalPwordExpected);
bzero(curClient->fullPwordToRead, 65);
/* End Shawyoun*/
fprintf(stderr, "end of handleHello");
}
void handleListRequest(struct clientInfo *curClient) {
/* Shawyoun */
fprintf(stderr, "reached handleListRequest. Header: %s\n Data: %s\n PasswordLength: %i\n", curClient->fullHeaderToRead, curClient->fullDataToRead, curClient->totalPwordExpected);
write(backEndServerSock, (char*)&curClient->fullHeaderToRead, HEADERSIZE);
bzero(curClient->fullHeaderToRead, HEADERSIZE);
write(backEndServerSock, (char*)&curClient->fullDataToRead, curClient->totalDataExpected);
bzero(curClient->fullDataToRead, MAXDATASIZE);
/* End Shawyoun*/
fprintf(stderr, "end of handleListRequest");
}
void handleChat(struct clientInfo *curClient) {
/* Shawyoun */
fprintf(stderr, "reached handleChat. Header: %s\n Data %s\n PasswordLength: %i\n", curClient->fullHeaderToRead, curClient->fullDataToRead, curClient->totalDataExpected);
write(backEndServerSock, (char*)&curClient->fullHeaderToRead, HEADERSIZE);
bzero(curClient->fullHeaderToRead, HEADERSIZE);
write(backEndServerSock, (char*)&curClient->fullDataToRead, curClient->totalDataExpected);
bzero(curClient->fullDataToRead, MAXDATASIZE);
/* End Shawyoun*/
fprintf(stderr, "end of handleChat");
}
void handleExit(struct clientInfo *curClient) {
/* Shawyoun */
fprintf(stderr, "reached handleExit. Header: %s\n Data %s\n PasswordLength: %i\n", curClient->fullHeaderToRead, curClient->fullDataToRead, curClient->totalDataExpected);
write(backEndServerSock, (char*)&curClient->fullHeaderToRead, HEADERSIZE);
bzero(curClient->fullHeaderToRead, HEADERSIZE);
write(backEndServerSock, (char*)&curClient->fullDataToRead, curClient->totalPwordExpected);
bzero(curClient->fullDataToRead, MAXDATASIZE);
/* End Shawyoun*/
fprintf(stderr, "end of handleExitRequest");
/* Shawyoun if(curClient->active && curClient->validated) {
fprintf(stderr, "exit: active and validated\n");
int sock = curClient->sock;
close(sock);
FD_CLR(sock, &read_fd_set);
FD_CLR(sock, &active_fd_set);
curClient->active = false;
curClient->sock = -1;
} else { *
if(!curClient->active) fprintf(stderr, "exit: not active\n");
if(!curClient->validated) fprintf(stderr, "exit: not validated\n"); */
int sock = curClient->sock;
close(sock);
FD_CLR(sock, &read_fd_set);
FD_CLR(sock, &active_fd_set);
for(int i = 0; i < MAXCLIENTS; i++) {
if(curClient->sock == 0) break;
if((strcmp(curClient->ID,clients[i].ID) == 0) && (!(clients[i].active)) || !(clients[i].validated)) {
if(!curClient->validated) {
for(int i = 0; i < playerData.size(); i++) {
if(strcmp(curClient->ID,playerData[i].owner) == 0) {
memset(playerData[i].owner,0,IDLENGTH);
strcpy(playerData[i].owner,"Server");
}
}
}
fprintf(stderr,"permanently removing client %s with sockfd %d\n",curClient->ID,curClient->sock);
memset(curClient, 0, sizeof(curClient));
}
}
numClients--;
/* } Shawyoun */
}
void handleBadExit(struct clientInfo *curClient) {
fprintf(stderr, "Entered handleBadExit\n");
struct header exitHeader;
memset(&exitHeader, 0, sizeof(exitHeader));
exitHeader.type = htons(BAD_EXIT);
memcpy(exitHeader.sourceID,curClient->ID,IDLENGTH);
memcpy(exitHeader.destID,"Server",IDLENGTH);
exitHeader.dataLength = htonl(0);
exitHeader.msgID = htonl(0);
int total = sizeof(exitHeader);
int sent = 0;
int bytes;
do {
bytes = write(backEndServerSock,(char *)&exitHeader+sent,total-sent);
if(bytes < 0) error("ERROR writing message to socket");
if(bytes == 0) break;
sent+=bytes;
//fprintf(stdout,"Sent %d bytes of the exit header\n",sent);
} while (sent < total);
/* Shawyoun if(curClient->active && curClient->validated) {
fprintf(stderr, "exit: active and validated\n");
int sock = curClient->sock;
close(sock);
FD_CLR(sock, &read_fd_set);
FD_CLR(sock, &active_fd_set);
curClient->active = false;
curClient->sock = -1;
} else { *
if(!curClient->active) fprintf(stderr, "exit: not active\n");
if(!curClient->validated) fprintf(stderr, "exit: not validated\n"); */
int sock = curClient->sock;
close(sock);
FD_CLR(sock, &read_fd_set);
FD_CLR(sock, &active_fd_set);
for(int i = 0; i < MAXCLIENTS; i++) {
if(curClient->sock == 0) break;
if((strcmp(curClient->ID,clients[i].ID) == 0) && (!(clients[i].active)) || !(clients[i].validated)) {
if(!curClient->validated) {
for(int i = 0; i < playerData.size(); i++) {
if(strcmp(curClient->ID,playerData[i].owner) == 0) {
memset(playerData[i].owner,0,IDLENGTH);
strcpy(playerData[i].owner,"Server");
}
}
}
fprintf(stderr,"permanently removing client %s with sockfd %d\n",curClient->ID,curClient->sock);
memset(curClient, 0, sizeof(curClient));
}
}
numClients--;
/* } Shawyoun */
}
void handleClientPresent(struct clientInfo *curClient, char *ID) {
/* build CLIENT_ALREADY_PRESENT header */
/*
struct header responseHeader;
responseHeader.type = htons(ERROR);
strcpy(responseHeader.sourceID, "Server");
memcpy(responseHeader.destID, ID, IDLENGTH);
responseHeader.dataLength = htonl(0);
responseHeader.msgID = htonl(0);
*/
//fprintf (stderr, "CLIENT_ALREADY_PRESENT responseHeader: type: %hu, sourceID: %s, destID: %s, dataLength: %u, msgID: %u\n", responseHeader.type, responseHeader.sourceID, responseHeader.destID, responseHeader.dataLength, responseHeader.msgID);
/* send CLIENT_ALREADY_PRESENT */
/*
int bytes, sent, total;
total = HEADERSIZE; sent = 0;
do {
bytes = write(curClient->sock, (char *)&responseHeader+sent, total-sent);
if(bytes < 0) error("ERROR writing to socket");
if(bytes == 0) break;
sent+=bytes;
} while (sent < total);
*/
handleExit(curClient);
}
void handleCannotDeliver(struct clientInfo *curClient) {
/* TODO Shawyoun: implement this */
}
/* Shawyoun: we may not need this anymore */
void handleError(struct clientInfo *curClient) {
if(curClient->sock != -1) {
struct header responseHeader;
responseHeader.type = htons(ERROR);
strcpy(responseHeader.sourceID, "Server");
memcpy(responseHeader.destID, curClient->ID, IDLENGTH);
responseHeader.dataLength = htonl(0);
responseHeader.msgID = htonl(curClient->msgID);
fprintf (stderr, "ERROR responseHeader: type: %hu, sourceID: %s, destID: %s, dataLength: %u, msgID: %u\n", responseHeader.type, responseHeader.sourceID, responseHeader.destID, responseHeader.dataLength, responseHeader.msgID);
/* send ERROR */
int bytes, sent, total;
total = HEADERSIZE; sent = 0;
do {
bytes = write(curClient->sock, (char *)&responseHeader+sent, total-sent);
if(bytes < 0) error("ERROR writing to socket");
if(bytes == 0) break;
sent+=bytes;
} while (sent < total);
fprintf(stderr, "ERROR: booting client '%s' with sockfd %d\n",curClient->ID, curClient->sock);
}
handleExit(curClient);
}
void handlePlayerRequest(struct clientInfo *curClient) {
/* Shawyoun */
fprintf(stderr, "reached handlePlayerRequest. Header: %s\n Data %s\n PasswordLength: %i\n", curClient->fullHeaderToRead, curClient->fullDataToRead, curClient->totalDataExpected);
write(backEndServerSock, (char*)&curClient->fullHeaderToRead, HEADERSIZE);
bzero(curClient->fullHeaderToRead, HEADERSIZE);
write(backEndServerSock, (char*)&curClient->fullDataToRead, curClient->totalPwordExpected);
bzero(curClient->fullDataToRead, MAXDATASIZE);
/* End Shawyoun*/
fprintf(stderr, "end of handlePlayerRequest");
}
void handleDraftRequest(clientInfo *curClient) {
/* Shawyoun */
fprintf(stderr, "reached handleDraftRequest. Header: %s\n Data: %s\n PasswordLength: %i\n", curClient->fullHeaderToRead, curClient->fullDataToRead, curClient->totalPwordExpected);
write(backEndServerSock, (char*)&curClient->fullHeaderToRead, HEADERSIZE);
bzero(curClient->fullHeaderToRead, HEADERSIZE);
write(backEndServerSock, (char*)&curClient->fullDataToRead, curClient->totalDataExpected);
bzero(curClient->fullDataToRead, MAXDATASIZE);
/* End Shawyoun*/
fprintf(stderr, "end of handleDraftRequest");
}
void sendPing(clientInfo *curClient) {
//struct timeval startTime;
//char timeBuffer[sizeof(startTime)];
struct header responseHeader;
memset(&responseHeader,0,sizeof(responseHeader));
responseHeader.type = htons(PING);
strcpy(responseHeader.sourceID, "Server");
strcpy(responseHeader.destID, curClient->ID);
responseHeader.dataLength = htonl(0);
responseHeader.msgID = htonl(++curClient->pingID);
int bytes, sent, total;
total = HEADERSIZE; sent = 0;
do {
gettimeofday(&curClient->lastPingSent, NULL);
bytes = write(curClient->sock, (char *)&responseHeader+sent, total-sent);
if(bytes < 0) error("ERROR writing to socket");
if(bytes == 0) break;
sent+=bytes;
} while (sent < total);
//readHeader(curClient, curClient->sock);
//readData(curClient);
//memcpy(timeBuffer,&startTime,sizeof(startTime));
}
void handleStartDraft(clientInfo *curClient) {
curClient->readyToDraft = !curClient->readyToDraft;
string s;
int readyClients = 0;
int totalClients = 0;
for(int i = 0; i < MAXCLIENTS; i++) {
if(clients[i].active) {
totalClients++;
if(clients[i].readyToDraft) {
readyClients++;
}
}
}
if(!draftStarted) {
if(curClient->readyToDraft) {
s = "You, "; s += curClient->ID; s += ", are ready to draft! ";
} else {
s = "You, "; s += curClient->ID; s += ", are not ready to draft. ";
}
s += "There are "; s += to_string(readyClients); s += " clients ready and ";
s += to_string(totalClients - readyClients); s += " that are not ready.\n";
} else {
s = "The draft is already underway!\n";
}
char stringBuffer[s.length() + 1];
strcpy(stringBuffer, s.c_str());
stringBuffer[s.length()] = '\0';
struct header responseHeader;
memset(&responseHeader,0,sizeof(responseHeader));
responseHeader.type = htons(DRAFT_STATUS);
strcpy(responseHeader.sourceID, "Server");
strcpy(responseHeader.destID, curClient->ID);
responseHeader.dataLength = htonl(s.length() + 1);
responseHeader.msgID = htonl(0);
int bytes, sent, total;
total = HEADERSIZE; sent = 0;
do {
bytes = write(curClient->sock, (char *)&responseHeader+sent, total-sent);
if(bytes < 0) error("ERROR writing to socket");
if(bytes == 0) break;
sent+=bytes;
} while (sent < total);
total = strlen(stringBuffer) + 1;
sent = 0;
while(sent < total) {
bytes = write(curClient->sock, stringBuffer+sent, total-sent);
if(bytes < 0) error("ERROR writing to socket");
if(bytes == 0) break;
sent+= bytes;
}
if(totalClients == readyClients) {
sendStartDraft();
draftStarted = true;
}
}
void sendStartDraft() {
memset(&theDraft,0,sizeof(theDraft));
fprintf(stderr, "In sendStartDraft\n");
struct header responseHeader;
memset(&responseHeader,0,sizeof(responseHeader));
responseHeader.type = htons(DRAFT_STARTING);
strcpy(responseHeader.sourceID, "Server");
responseHeader.msgID = htonl(0);
string s;
s = "The draft is now starting with "; s += to_string(clientCounter); s += " clients!";
char stringBuffer[s.length() + 1];
strcpy(stringBuffer, s.c_str());
stringBuffer[s.length()] = '\0';
responseHeader.dataLength = htonl(s.length() + 1);
for(int i = 0; i < MAXCLIENTS; i++) {
fprintf(stderr, "In for with i=%d\n", i);
if(clients[i].active) {
//fprintf(stderr, "In for with active client: %s\n", clients[i].ID);
strcpy(responseHeader.destID, clients[i].ID);
int bytes, sent, total;
total = HEADERSIZE; sent = 0;
do {
bytes = write(clients[i].sock, (char *)&responseHeader+sent, total-sent);
if(bytes < 0) error("ERROR writing to socket");
if(bytes == 0) break;
sent+=bytes;
} while (sent < total);
total = strlen(stringBuffer) + 1;
sent = 0;
while(sent < total) {
bytes = write(clients[i].sock, stringBuffer+sent, total-sent);
if(bytes < 0) error("ERROR writing to socket");
if(bytes == 0) break;
sent+= bytes;
}
struct team newTeam;
memset(&newTeam,0,sizeof(newTeam));
strcpy(newTeam.owner, clients[i].ID);
theDraft.teams.push_back(newTeam);
}
}
draftNewRound();
}
void handlePingResponse(clientInfo *curClient) {
struct timeval sentTime, curTime;
gettimeofday(&curTime, NULL);
memcpy((char *)&sentTime,curClient->partialData,sizeof(sentTime));
int delayms = ((curTime.tv_sec * 1000) + (curTime.tv_usec / 1000)) - ((curClient->lastPingSent.tv_sec * 1000) + (curClient->lastPingSent.tv_usec / 1000));
//fprintf(stderr, "Delay between ping response sent and ping response recieved: %d\n", delayms);
//fprintf(stderr, "Ping recieved: %d, curClient->pingID: %d\n", curClient->msgID, curClient->pingID);
if(curClient->msgID != curClient->pingID) return;
if(delayms < curClient->timeout) {
if(curClient->estRTT == 0) {
curClient->estRTT = delayms;
} else {
curClient->estRTT = (alpha * curClient->estRTT) + (delayms * (1.0 - alpha));
}
curClient->devRTT = (beta * fabs(delayms - curClient->estRTT)) + ((1.0 - beta) * curClient->devRTT);
curClient->timeout = max((curClient->estRTT + (4 * curClient->devRTT)), minTimeout);
fprintf(stderr, "Client %s has estRTT of %f, devRTT of %f, and timeout of %f\n", curClient->ID,curClient->estRTT,curClient->devRTT,curClient->timeout);
if(curClient->timeout > maxDelay) {
maxDelay = curClient->timeout;
}
}
if(curClient->pings-- > 0) {
sendPing(curClient);
}
}
string sha256(const string str) {
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, str.c_str(), str.size());
SHA256_Final(hash, &sha256);
stringstream ss;
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
ss << hex << setw(2) << setfill('0') << (int)hash[i];
}
return ss.str();
}
void draftNewRound() {
theDraft.currentRound++;
char curPlayer[50];
memset(curPlayer,0,50);
memcpy(curPlayer,playerData[theDraft.index].PLAYER_NAME,50);
fprintf(stderr, "curPlayer in draftNewRound: %s\n", curPlayer);
struct header responseHeader;
memset(&responseHeader,0,sizeof(responseHeader));
responseHeader.type = htons(DRAFT_ROUND_START);
strcpy(responseHeader.sourceID, "Server");
responseHeader.dataLength = htonl(strlen(curPlayer) + 1);
responseHeader.msgID = htonl(theDraft.currentRound);
for(int i = 0; i < MAXCLIENTS; i++) {
if(clients[i].active) {
strcpy(responseHeader.destID, clients[i].ID);
int bytes, sent, total;
total = HEADERSIZE; sent = 0;
do {
bytes = write(clients[i].sock, (char *)&responseHeader+sent, total-sent);
if(bytes < 0) error("ERROR writing to socket");
if(bytes == 0) break;
sent+=bytes;
} while (sent < total);
total = strlen(curPlayer) + 1;
sent = 0;
while(sent < total) {
bytes = write(clients[i].sock, curPlayer+sent, total-sent);
if(bytes < 0) error("ERROR writing to socket");
if(bytes == 0) break;
sent+= bytes;
}
}
}
for(int i = 0; i < theDraft.teams.size(); i++) {
theDraft.teams[i].adjustedTimeReceived.tv_sec = 0;
theDraft.teams[i].adjustedTimeReceived.tv_usec = 0;
}
theDraft.index++;
//timeval fiveSecs; fiveSecs.tv_sec = 5; fiveSecs.tv_usec = 0;
timeval roundTotalTime; roundTotalTime.tv_sec = (maxDelay / 1000) + 10; roundTotalTime.tv_usec = (maxDelay % 1000) * 1000;
fprintf(stderr, "roundTotalTime.tv_sec: %d\n", roundTotalTime.tv_sec);
timeval curTime;
gettimeofday(&curTime, NULL);
timeval roundEndTime;
timeradd(&roundTotalTime,&curTime,&roundEndTime);