-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.cpp
1808 lines (1541 loc) · 60.7 KB
/
server.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
// This whole section with includes, defines, and struct definitions would
// ideally be in a seperate header file
#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>
#include <time.h>
#include <algorithm>
#include <random>
using namespace std;
// Single points of reference for hard-coded parameters
#define MAXDATASIZE 400 // Only limits messages sent between users
#define MAXCLIENTS 200 // Draft with this many would run out of players however
#define IDLENGTH 20 // Includes null character
#define TEAMSIZE 12
#define ROUNDTIME 10 // Max of 255
#define PARTICIPATING_MASK 256
const float minTimeout = 50.0;
// Message types (in order in which they were incorperated into the code)
// Comments indicat use of msgID field, if any
#define HELLO 1
#define HELLO_ACK 2 // 1 if draft in progress, 0 otherwise
#define LIST_REQUEST 3
#define CLIENT_LIST 4
#define CHAT 5 // # chat sent by client
#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 // # ping sent to specific client by server
#define PING_RESPONSE 13 // # of pint client is responding to
#define START_DRAFT 14
#define DRAFT_STATUS 15
#define DRAFT_STARTING 16 // Roundlength & participation mask
#define DRAFT_ROUND_START 17 // # of round that is starting
#define DRAFT_ROUND_RESULT 18 // # of round that is ending
#define DRAFT_PASS 19
#define DRAFT_END 20 // # of draft that just finished
// Header struct, agreed upon by client and server
struct header {
unsigned short type; // One of the options from above;
char sourceID[IDLENGTH];
char destID[IDLENGTH];
unsigned int dataLength;
unsigned int msgID; // Used to store info for some message types
}__attribute__((packed, aligned(1)));
#define HEADERSIZE sizeof(header)
// struct for storing info about clients
struct clientInfo {
int sock;
char ID[IDLENGTH];
bool active;
int mode;
// In case a header isn't read all at once
int headerToRead;
char partialHeader[HEADERSIZE];
// Storage for data read from client
int dataToRead;
int totalDataExpected;
char partialData[MAXDATASIZE];
char destID[IDLENGTH];
int msgID;
// Storage for client's hashed password
int pwordToRead;
int totalPwordExpected;
char pword[65];
bool validated;
// Info about this client's pings
int pingSent;
int pingRcvd;
int pings;
struct timespec lastPingSent;
float estRTT;
float devRTT;
float timeout;
// Is this client ready for the draft to start?
bool readyToDraft;
}__attribute__((packed, aligned(1)));
// Struct for each team participating in draft
struct team
{
char owner[20];
int playersDrafted;
bool responseRecieved;
timespec adjustedTimeReceived;
playerInfo players[TEAMSIZE];
};
// Info about the draft
struct draftInfo {
int index;
int currentRound;
timespec roundEndTime;
vector<team> teams;
vector<int> order;
};
// Stroring, tracking clients
struct clientInfo clients[MAXCLIENTS];
int clientCounter = 0;
int numClients = 0; int numActiveClients = 0;
// maximum time server should wait for any client to respond
float maxDelay;
// conditions for sending pings
bool timedOut = false;
bool curRoundPingsSent = false;
bool newEntry = false;
// Tracking the status of the draft (admittedly could have been part of draftInfo struct)
int draftNum = 0;
bool startDraft = false;
bool draftStarted;
bool startNewRound = false;
struct draftInfo theDraft;
// Info on all players
vector<playerInfo> playerData;
// For estRTT, devRTT, timeout calculations
const float alpha = 0.875;
const float beta = 0.25;
// Boilerplate functions
void error(const char *msg)
{
perror(msg);
exit(1);
}
int max(int a, int b) {
if(a > b) return a;
return b;
}
int min(int a, int b) {
if(a < b) return a;
return b;
}
/* Methods are broken down into sections */
// 1. All purpose method for new read from a client
void readFromClient(int sockfd);
// 2. Methods for reading specifc parts of messages
void readHeader(struct clientInfo *curClient, int sockfd);
void readData(struct clientInfo *curClient);
void readPword(struct clientInfo *curClient);
// 3. Methods for handling particular types of messages
void handleHello(struct clientInfo *curClient);
void handleListRequest(struct clientInfo *curClient);
void handleChat(struct clientInfo *sender);
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 handleDraftPass(struct clientInfo *curClient);
void handleStartDraft(struct clientInfo *curClient);
void handlePingResponse(struct clientInfo *curClient);
// 4. Method for sending pings to all clients
void sendPing(struct clientInfo *curClient);
// 5. Methods called by the server to state of the draft
void sendStartDraft();
void draftNewRound();
void endDraftRound();
void endDraft();
// 6. Helper function, returns true if conditions for ending the current draft round are met
bool roundIsOver();
// 7. Helper functions for dealing with timespecs
void timespecAdd(timespec *a, timespec *b, timespec *c);
void timespecSubtract(timespec *a, timespec *b, timespec *c);
bool timespecLessthan(timespec *a, timespec *b);
// 8. Function for hashing passwords
string sha256(const string str);
fd_set active_fd_set, read_fd_set; // Declared here so all functions can use
/********************************************************************
* Section 0: main *
********************************************************************/
int main(int argc, char *argv[]) {
srand(unsigned (time(0)));
memset(clients,0,sizeof(clients));
// TODO: Give more options than this hard coded file
playerData = readCSV("nba1516.csv");
memset(&clients, 0, sizeof(clients));
int sockfd, newsockfd, portno, pid, i;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
// TODO: Flags for particular error message types
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]); // Get port number from args
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
FD_ZERO(&active_fd_set);
FD_SET(sockfd, &active_fd_set);
clilen = sizeof(cli_addr);
while(1) {
timespec curTime;
clock_gettime(CLOCK_MONOTONIC,&curTime);
// Determine timeout for select
timespec timeToEndRound;
if(draftStarted && !startNewRound) {
if(timespecLessthan(&theDraft.roundEndTime,&curTime)) {
// Time has elapsed!
fprintf(stderr, "About to endDraftRound\n");
endDraftRound();
continue; // Probably unecessary
} else {
timespecSubtract(&theDraft.roundEndTime,&curTime,&timeToEndRound);
fprintf(stderr, "Time til next round: %d.%ds\n", timeToEndRound.tv_sec,timeToEndRound.tv_nsec);
}
} else {
// Next round will never be if the draft is not going on!
timeToEndRound.tv_sec = 99999;
timeToEndRound.tv_nsec = 0;
}
timedOut = true;
// If the draft is going on, want to end as close to end of round as possible
// Otherwise wait a healthy amount more than necessary to accomodate maxDelay
int timeoutSecs = min(max(((int)(maxDelay + 1500) / 1000), 5), (timeToEndRound.tv_sec + 1) );
//fprintf(stderr, "timeoutSecs: %d\n", timeoutSecs);
struct timeval selectTimeout = {timeoutSecs,(timeToEndRound.tv_nsec / 1000)};
// Cases where we want to send pings sooner rather than later
if(startNewRound && !curRoundPingsSent) selectTimeout = {0,1000}; // Just making sure nobody quit
if(newEntry && !draftStarted) selectTimeout = {1,0}; // Idea is to get a ping in quickly; reality is if RTT is greater it causes issues
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)) {
timedOut = false;
if(i == sockfd) {
/* Connection request on original socket */
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 = true;
}
clientCounter++;
numClients++;
numActiveClients++;
//fprintf(stderr, "332: numActiveClients: %d\n", numActiveClients);
clientCounter = clientCounter % MAXCLIENTS;
}
fprintf(stderr, "New connection with newsockfd: %d\n", newsockfd);
startDraft = false; // Don't want to ambush new client with start of a draft
// 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 {
/* Data arriving on an already-connected socket */
readFromClient(i);
}
}
}
// If it's been quiet for long enough or we need to get the pings in now, lets ping!
if((timedOut && !draftStarted) || (startNewRound && !curRoundPingsSent)) {
for(int i = 0; i < MAXCLIENTS; i++) {
if(clients[i].active && clients[i].validated) {
// Don't ping if we're still waiting on a response...unless it's really hopeless
if((clients[i].pingSent == clients[i].pingRcvd) || ((curTime.tv_sec - clients[i].lastPingSent.tv_sec) > 30)) {
sendPing(&clients[i]);
}
}
}
if(startNewRound) {
curRoundPingsSent = true;
timedOut = false;
}
// Want to keep up the short timeouts until we get the newbie at least one ping
if(newEntry) newEntry = false;
}
// Making sure there's a chance for client input to come in before starting anything
if(startDraft && timedOut) sendStartDraft();
if(startNewRound && timedOut) draftNewRound();
}
close(sockfd);
return 0;
}
/********************************************************************
* Section 1: Determine which read to use *
********************************************************************/
void readFromClient (int sockfd) {
int i;
struct clientInfo *curClient;
/* 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 {
// This is a new user
fprintf(stderr, "readFromClient, not active client\n");
struct clientInfo newClient;
memset(&newClient, 0, sizeof(newClient));
newClient.sock = sockfd;
newClient.headerToRead = HEADERSIZE;
newClient.active = true;
newClient.validated = false;
bool inserted = false;
while(!inserted) {
if(clients[clientCounter].sock == 0) {
clients[clientCounter] = newClient;
inserted = true;
}
clientCounter++;
numActiveClients++;
//fprintf(stderr, "403: numActiveClients: %d\n", numActiveClients);
clientCounter = clientCounter % MAXCLIENTS;
}
break;
}
}
}
/* send to appropriate read method; headerToRead should always be positive */
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");
}
}
/********************************************************************
* Section 2: Read specific parts of messages *
********************************************************************/
void readHeader(struct clientInfo *curClient, int sockfd) {
char header_buffer[HEADERSIZE];
int nbytes;
/* 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 */
handleExit(curClient);
} else if (nbytes < curClient->headerToRead) {
/* still more to read */
curClient->headerToRead = curClient->headerToRead - nbytes;
memcpy(curClient->partialHeader, header_buffer, HEADERSIZE);
} else {
/* Parse header. */
struct header newHeader;
memcpy((char *)&newHeader, &header_buffer[0], HEADERSIZE);
newHeader.type = ntohs(newHeader.type);
newHeader.dataLength = ntohl(newHeader.dataLength);
newHeader.msgID = ntohl(newHeader.msgID);
curClient->headerToRead = HEADERSIZE;
fprintf (stderr, "Header read in: type: %hu, sourceID: %s, destID: %s, dataLength: %u, msgID: %u\n", newHeader.type, newHeader.sourceID, newHeader.destID, newHeader.dataLength, newHeader.msgID);
/* identify potential bad input; holdover from Assignment 2 */
if((strcmp(newHeader.sourceID,curClient->ID) != 0) && (strcmp(curClient->ID,"") != 0) && curClient->active) {
fprintf(stderr, "ERROR: wrong user ID in header\n");
handleError(curClient);
return;
}
if(strlen(newHeader.sourceID) >= IDLENGTH) {
fprintf(stderr, "ERROR: sourceID is too long\n");
handleError(curClient);
return;
}
if(strlen(newHeader.destID) >= IDLENGTH) {
fprintf(stderr, "ERROR: destID is too long\n");
handleError(curClient);
return;
}
if(newHeader.dataLength > MAXDATASIZE) {
fprintf(stderr, "ERROR: dataLength too large\n");
handleError(curClient);
return;
}
/* next step depends on header type */
if(newHeader.type == HELLO) {
if(newHeader.dataLength > 20) {
fprintf(stderr, "ERROR: HELLO has dataLength > 20 \n");
handleError(curClient);
return;
}
/* handle HELLO-specific bad input */
if(strcmp(curClient->ID,"") != 0) {
// If there is already and ID, this is not this client's first interaction with the server
fprintf(stderr, "ERROR: Attempt to HELLO from previously seen client\n");
handleError(curClient);
}
if(newHeader.msgID !=0) {
fprintf(stderr, "ERROR: HELLO has msgID != 0 \n");
handleError(curClient);
return;
}
if(strcmp(newHeader.destID, "Server") != 0) {
fprintf(stderr, "ERROR: HELLO not addressed to Server\n");
handleError(curClient);
return;
}
if(strcmp(newHeader.sourceID, "Server") == 0) {
fprintf(stderr, "ERROR: 'Server' is not a valid ID\n");
handleError(curClient);
return;
}
/* look for CLIENT_ALREADY_PRESENT error */
bool duplicate = false;
for(int i = 0; i < MAXCLIENTS; i++) {
if(strcmp(clients[i].ID, newHeader.sourceID) == 0) {
if(clients[i].active) {
// Can't sign in as active user
memcpy(curClient->ID, newHeader.sourceID, IDLENGTH);
handleClientPresent(curClient, newHeader.sourceID);
return;
}
// Could be client returning
duplicate = true;
}
}
if(!duplicate) {
// There is no chance of collision with existing user
curClient->validated = true;
} else {
// Need to check for correct password
curClient->validated = false;
}
// Make sure readPword is triggered
curClient->totalPwordExpected = newHeader.dataLength;
curClient->pwordToRead = newHeader.dataLength;
memcpy(curClient->ID, newHeader.sourceID, IDLENGTH);
} else if(newHeader.type == LIST_REQUEST) {
/* handle LIST_REQUEST-specific bad input */
if(strcmp(curClient->ID,"") == 0) {
fprintf(stderr,"ERROR: LIST_REQUEST from client without ID\n");
handleError(curClient);
return;
}
if(newHeader.dataLength != 0) {
fprintf(stderr, "ERROR: LIST_REQUEST has dataLength != 0\n");
handleError(curClient);
return;
}
if(newHeader.msgID != 0) {
fprintf(stderr, "ERROR: LIST_REQUEST has msgID != 0\n");
handleError(curClient);
return;
}
if(strcmp(newHeader.destID, "Server") != 0) {
fprintf(stderr, "ERROR: LIST_REQEUST not addressed to Server\n");
handleError(curClient);
return;
}
handleListRequest(curClient);
} else if(newHeader.type == CHAT) {
/* handle CHAT-specific bad input (not related to CANNOT_DELIVER) */
if(newHeader.msgID == 0) {
fprintf(stderr,"ERROR: CHAT has msgID == 0\n");
handleError(curClient);
return;
}
if(strcmp(curClient->ID,"") == 0) {
fprintf(stderr,"ERROR: CHAT from client without ID\n");
handleError(curClient);
return;
}
/* 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) {
/* Client formally exiting, make sure handleExit removes them completely */
curClient->active = false;
numActiveClients--;
//fprintf(stderr, "595: numActiveClients: %d\n", numActiveClients);
curClient->validated = false;
handleExit(curClient);
} else if(newHeader.type == PLAYER_REQUEST) {
handlePlayerRequest(curClient);
} else if(newHeader.type == DRAFT_REQUEST) {
// Need to read in player that is being drafted
memset(curClient->partialData, 0, MAXDATASIZE);
curClient->mode = DRAFT_REQUEST;
curClient->dataToRead = newHeader.dataLength;
curClient->totalDataExpected = newHeader.dataLength;
}else if(newHeader.type == PING_RESPONSE) {
// Client is sending a timestamp of its own, though the server doesn't use it
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) {
// Sorry about the confusing name; client is toggling their readiness
handleStartDraft(curClient);
} else if(newHeader.type == DRAFT_PASS) {
// Need to read in player being passed on
memset(curClient->partialData, 0, MAXDATASIZE);
curClient->mode = DRAFT_PASS;
curClient->dataToRead = newHeader.dataLength;
curClient->totalDataExpected = newHeader.dataLength;
} else {
fprintf(stderr, "ERROR: bad header type\n");
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 */
handleExit(curClient);
} 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);
//fprintf(stderr,"Message read in: curClient->partialData: %s\n",curClient->partialData);
curClient->dataToRead = 0;
// Send to the appropraite handler
if(curClient->mode == CHAT) {
handleChat(curClient);
} else if(curClient->mode == DRAFT_REQUEST) {
handleDraftRequest(curClient);
} else if(curClient->mode == PING_RESPONSE) {
handlePingResponse(curClient);
} else if(curClient->mode == DRAFT_PASS) {
handleDraftPass(curClient);
} else {
fprintf(stderr, "ERROR: Done reading data but client in invalid mode\n");
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 */
handleExit(curClient);
} else if (nbytes < curClient->pwordToRead) {
/* still more pword to read */
curClient->pwordToRead = curClient->pwordToRead - nbytes;
memcpy(curClient->pword, data_buffer, curClient->totalPwordExpected);
} else {
/* entire password read */
string hashed = sha256(data_buffer);
char hashBuffer[65];
for(int i = 0; i < hashed.length(); i++) {
hashBuffer[i] = hashed[i];
}
//fprintf(stderr, "Hashed pword: %s has length %d\n", hashed, hashed.length());
memcpy(curClient->pword, hashBuffer, hashed.length());
//fprintf(stderr, "Password read in: curClient->password: %s\n", curClient->pword);
curClient->pwordToRead = 0;
// Ready to deal with new client now that we have their password
handleHello(curClient);
}
}
/********************************************************************
* Section 3: Handlers for specific message types *
********************************************************************/
void handleHello(struct clientInfo *curClient) {
bool returning = false;
if(curClient->validated == false) {
returning = true; // New clients are automatically validated before getting here
for(int i = 0; i < MAXCLIENTS; i++) {
// There are two clients with the same ID, let's get them both
if((strcmp(clients[i].ID, curClient->ID) == 0) && !(clients[i].sock == curClient->sock)) {
if(strcmp(clients[i].pword, curClient->pword) == 0) {
//fprintf(stderr, "Password matches password of existing client, removing placeholder\n");
curClient->validated = true;
curClient->readyToDraft = clients[i].readyToDraft; // If the client was previously ready to draft, they (hopefully) still are
handleError(&clients[i]); // Remove the old client without removing all trace of the ID which the new client also has
} else {
//fprintf(stderr, "Password does not match existing client! You're fired!\n");
curClient->active = false;
numActiveClients--;
//fprintf(stderr, "735: numActiveClients: %d\n", numActiveClients);
handleError(curClient);
return;
}
}
}
}
char helloMessage[50];
memset(helloMessage,0,50);
// I later learned easier ways to to this but hey
if(returning) {
strcpy(helloMessage,"Welcome back ");
memcpy(helloMessage + strlen(helloMessage), curClient->ID, strlen(curClient->ID));
} else {
strcpy(helloMessage,"Welcome for the first time ");
memcpy(helloMessage + strlen(helloMessage), curClient->ID, strlen(curClient->ID));
}
helloMessage[strlen(helloMessage)] = '\0';
/* build HELLO_ACK header */
struct header responseHeader;
responseHeader.type = htons(HELLO_ACK);
strcpy(responseHeader.sourceID, "Server");
memcpy(responseHeader.destID, curClient->ID, IDLENGTH);
responseHeader.dataLength = htonl(strlen(helloMessage) + 1);
if(draftStarted && curClient->readyToDraft) {
responseHeader.msgID = htonl(1);
} else {
responseHeader.msgID = htonl(0);
}
//fprintf (stderr, "HELLO_ACK responseHeader: type: %hu, sourceID: %s, destID: %s, dataLength: %u, msgID: %u\n", ntohs(responseHeader.type), responseHeader.sourceID, responseHeader.destID, ntohl(responseHeader.dataLength), ntohl(responseHeader.msgID));
/* send HELLO_ACK */
int bytes, sent, total;
total = HEADERSIZE; sent = 0;
fprintf(stderr, "handleHello: Writing to %s with sock %d\n", curClient->ID,curClient->sock);
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(helloMessage) + 1;
sent = 0;
while(sent < total) {
bytes = write(curClient->sock, helloMessage+sent, total-sent);
if(bytes < 0) error("ERROR writing to socket");
if(bytes == 0) break;
sent+= bytes;
//fprintf(stdout,"Sent %d bytes of the helloMessage\n");
}
handleListRequest(curClient);
// curClient->timeout should be the default
if(maxDelay < curClient->timeout) maxDelay = curClient->timeout;
// If the client had previously participated in the draft
// Note: All clients are set to not ready at the end of the draft so a
// client will only return to a draft they were previously involved in
if(draftStarted && curClient->readyToDraft) {
struct header responseHeader;
memset(&responseHeader,0,sizeof(responseHeader));
responseHeader.type = htons(DRAFT_STARTING);
strcpy(responseHeader.destID, curClient->ID);
strcpy(responseHeader.sourceID, "Server");
responseHeader.msgID = htonl(ROUNDTIME | PARTICIPATING_MASK);
string s;
s = "Welcome back to the draft! Round "; s += to_string(theDraft.index+1); s += " is underway.\n";
char stringBuffer[s.length() + 1];
strcpy(stringBuffer, s.c_str());
stringBuffer[s.length()] = '\0';
responseHeader.dataLength = htonl(s.length() + 1);
int bytes, sent, total;
total = HEADERSIZE; sent = 0;
fprintf(stderr, "handleHello (draftStarted): Writing to %s with sock %d\n", curClient->ID,curClient->sock);
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;
}
}
// Even if the client isn't participating, they need to get the information about the ongoing draft
if(draftStarted && !curClient->readyToDraft) {
struct header responseHeader;
memset(&responseHeader,0,sizeof(responseHeader));
responseHeader.type = htons(DRAFT_STARTING);
strcpy(responseHeader.destID, curClient->ID);
strcpy(responseHeader.sourceID, "Server");
responseHeader.msgID = htonl(ROUNDTIME);
string s;
s = "Round "; s += to_string(theDraft.index+1); s += " of the draft is underway. Feel free to watch the results!\n";
char stringBuffer[s.length() + 1];
strcpy(stringBuffer, s.c_str());
stringBuffer[s.length()] = '\0';
responseHeader.dataLength = htonl(s.length() + 1);
int bytes, sent, total;
total = HEADERSIZE; sent = 0;
fprintf(stderr, "handleHello (draftStarted, client not ready): Writing to %s with sock %d\n", curClient->ID,curClient->sock);
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;
}
}
// Tell everyone else a client has logged in
memset(&responseHeader,0,sizeof(responseHeader));
strcpy(responseHeader.sourceID, "Server");
responseHeader.msgID = htonl(0);
for(int i = 0; i < MAXCLIENTS; i++) {
if(clients[i].active && (clients[i].sock != curClient->sock)) {
strcpy(responseHeader.destID, clients[i].ID);
responseHeader.type = htons(CHAT);
string s = curClient->ID;
if(returning) {
s += " has logged back in";
} else {
s += " joined for the first time";
}
char stringBuffer[s.length() + 1];
strcpy(stringBuffer, s.c_str());
stringBuffer[s.length()] = '\0';
responseHeader.dataLength = htonl(s.length() + 1);
int bytes, sent, total;
total = HEADERSIZE; sent = 0;
fprintf(stderr, "handleHello (CHAT to active clients): Writing to %s with sock %d\n", clients[i].ID,clients[i].sock);
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;
}
handleListRequest(&clients[i]);
}
}
// Shorten the select timeout to get the new client a ping ASAP
newEntry = true;
}
// Relic of Assignment 2 without character limit
void handleListRequest(struct clientInfo *curClient) {
/* construct IDs buffer */
char IDBuffer[MAXCLIENTS * (IDLENGTH + 2)];
memset(IDBuffer, 0, (MAXCLIENTS * (IDLENGTH + 2)));
int i, bufferIndex, IDLength;
bufferIndex = 0;
/* IDs are added as long as they fit */
for(i = 0; i < MAXCLIENTS; i++) {
if(clients[i].sock != NULL) {
IDLength = strlen(clients[i].ID);
IDLength++;
strcpy(&IDBuffer[bufferIndex], clients[i].ID);
bufferIndex = bufferIndex + IDLength;
if(!(clients[i].active)) {
IDBuffer[bufferIndex-1] = '*';
IDBuffer[bufferIndex] = ' ';
bufferIndex++;
}
}
}
/* build CLIENT_LIST header */
struct header responseHeader;
responseHeader.type = htons(CLIENT_LIST);
strcpy(responseHeader.sourceID, "Server");
strcpy(responseHeader.destID, curClient->ID);
responseHeader.dataLength = htonl(bufferIndex);
responseHeader.msgID = htonl(0);
//fprintf (stderr, "CLIENT_LIST responseHeader: type: %hu, sourceID: %s, destID: %s, dataLength: %u, msgID: %u\n", responseHeader.type, responseHeader.sourceID, responseHeader.destID, responseHeader.dataLength, responseHeader.msgID);
/* send CLIENT_LIST header */
int bytes, sent, total;
total = HEADERSIZE; sent = 0;
fprintf(stderr, "handleListRequest: Writing to %s with sock %d\n", curClient->ID,curClient->sock);
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);
/* send IDBuffer */
total = bufferIndex; sent = 0;
do {
bytes = write(curClient->sock, (char *)&IDBuffer+sent, total-sent);
if(bytes < 0) error("ERROR writing to socket");
if(bytes == 0) break;
sent+=bytes;
} while (sent < total);
}
// Relic from Assignment 2
void handleChat(struct clientInfo *sender) {
int i; int badRecipient = 1;
struct clientInfo *receiver = 0;
/* find the recipient and make sure they are valid */
for(i = 0; i < MAXCLIENTS; i++) {
if((strcmp(clients[i].ID, sender->destID) == 0) && clients[i].active) {
if((strcmp(sender->destID, sender->ID) != 0) && (strcmp(sender->destID,"") != 0)) {
receiver = &clients[i];
badRecipient = 0;
}
}
}
if(badRecipient == 1) {
handleCannotDeliver(sender);
return;
}