-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
711 lines (653 loc) · 20.8 KB
/
Copy pathserver.cpp
File metadata and controls
711 lines (653 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
//Altan Gulen
//Network Programming
//Code for using network sockets borrowed from beej's guide to network programming: http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html
#include <stdio.h>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <errno.h>
#include <sstream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdlib.h>
#include "User.h"
#include "Chatroom.h"
#define PORT "9999"
#define MESSAGE_SIZE 80
#define MAXBUF 200
#define MAXCON 500
vector<string> splitString(string str);
char* convertToChar(string str);
Chatroom findRoom(string roomName, vector<Chatroom> &roomList);
User getClientUsername(map<int, User> &userSockets, int user_fd);
void addNewUser(User &newUser, int user_fd, vector<User> &userList, map<int, User> &userSockets);
void *get_in_addr(struct sockaddr *sa);
int main(int argc, char* argv[])
{
vector<User> userList;
vector<Chatroom> roomList;
map<int, User> userSockets;
//bool verboseMode = false;
fd_set master;
fd_set clients;
int fdmax;
int listener; //socket to listen to
int newfd; //new socket from accept
struct sockaddr_storage remoteaddr;
socklen_t addrlen;
int yes;
struct addrinfo hints, *ai, *p;
char remoteIP[INET6_ADDRSTRLEN];
int rv;
FD_ZERO(&master);
FD_ZERO(&clients);
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; //Use my IP
if(argc == 2 && (strcmp(argv[1], "-v") == 0))
//verboseMode = true;
if((rv = getaddrinfo(NULL, PORT, &hints, &ai)) != 0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
for(p = ai; p != NULL; p = p->ai_next) {
listener = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (listener < 0) {
continue;
}
setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); // removes the wait to restart the server
if (bind(listener, p->ai_addr, p->ai_addrlen) < 0) // bind to address and port
{
close(listener);
continue;
}
printf("listening on %s\n",
inet_ntop(p->ai_family,
get_in_addr((struct sockaddr*)&(p->ai_addr)), remoteIP, INET6_ADDRSTRLEN)
);
break;
}
if(p == NULL)
{
fprintf(stderr, "server:failed to bind\n");
exit(2);
}
freeaddrinfo(ai);
if(listen(listener, 10) == -1)
{
perror("listen");
exit(3);
}
FD_SET(listener, &master); //Adds listener to master fdset
fdmax = listener;
//Server listening loop
while(1)
{
char* buf = convertToChar("DEFAULT VALUE");
string bufString = "";
string command;
string response;
ssize_t numBytes = -2;
clients = master;
if(select(fdmax + 1, &clients, NULL, NULL, NULL) == -1)
{
perror("select:");
exit(1);
}
for(int i = 0; i <= fdmax; i++)
{
if(FD_ISSET(i, &clients))
{
if(i == listener)
{
//A client wants to talk!
addrlen = sizeof remoteaddr;
newfd = accept(listener, //accept this socket
(struct sockaddr *)&remoteaddr, //who are you?
&addrlen);
if(newfd == -1)
{
perror("accept");
}
else
{
FD_SET(newfd, &master); //add new socket to master list
if(newfd > fdmax) //update length of fd set
{
fdmax = newfd;
}
}
}
else
{
User currentUser;
//we're talking to a client
if((numBytes = recv(i, buf, MAXBUF, 0)) <= 0)
{
if(numBytes == 0) {} //Socket is closed
else //Error occurred
{
perror("recv");
}
close(i); //close socket
FD_CLR(i, &master); //delete from master list
}
else //Got good data from client
{
bufString += buf;
if(bufString.find("CHAT") != string::npos) //Connecting to server
{
response = "TAHC\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (CHAT)");
exit(1);
}
}
else if(bufString.find("USERS") != string::npos) //List all users
{
if(((currentUser = getClientUsername(userSockets, i)).getName()).empty())
{
break; //Client has no username, do not process command
}
if(currentUser.isLoggedIn())
{
cout << "I AM " << currentUser.getName();
response = "List of users on server:\n";
for(unsigned int j = 0; j < userList.size(); j++)
response += "\t" + userList[j].getName() + "\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (USERS)");
exit(1);
}
}
}
else if(bufString.find("USER") != string::npos) //<nickname> <password> --> Log in. Give 3 tries. if new user, create it.
{
if(fdmax > 1)
{
vector<string> tokens = splitString(bufString);
string name = tokens[1];
string givenPassword = tokens[2];
response = "";
for(unsigned int j = 0; j < userList.size(); j++)
{
if(userList[j].getName() == name)
{
response = "That username is taken.\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (USER - username taken)");
exit(1);
}
}
}
if(userList.size() == 0) //This is our first user!
{
User newUser(tokens[1], tokens[2], true, i);
addNewUser(newUser, i, userList, userSockets);
response = "Welcome to the chat server ";
response += name;
response += "!\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (USER - welcome to server)");
exit(1);
}
response = "";
}
else
{
for(unsigned int j = 0; j < userList.size(); j++) //Loop through all users
{
if(userList[j].getName() == name) //Check if user exists
{
if(userList[j].getPassword() != givenPassword) //Check if passwords match or not
{
if(!userList[j].isLoggedIn())
{
//User gets 2 more tries to get correct password
for(int k = 1; k < 3; k++)
{
response += "Username recognized, but incorrect password given.\nEnter a password:";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (USER - password attempt)");
exit(1);
}
while(1) //Wait for password input
{
if((numBytes = recv(i, buf, MAXBUF, 0)) <= 0)
{
perror("recv (USER - password attempt)");
exit(1);
}
else //Got new password input!
{
givenPassword = buf;
break;
}
}
if(givenPassword == userList[i].getPassword())
{
if(userList[i].isLoggedIn()) //Check if user is already logged in
{
response = "You are already logged in as ";
response += (userSockets.find(i)->second).getName();
response += "\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (USER - already logged in)");
exit(1);
}
}
else
userList[i].setLoggedIn(true);
break; //Correct password given, get out of password attempt loop
}
else
{
if(k == 1) //If the user has failed to login on their third try, then disconnect
{
response = "You have reached the maximum amount of attempts to login. Disconnecting.\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (USER - max attempts reached");
exit(1);
}
close(i);
FD_CLR(i, &master); //delete from master list
}
}
}
}
}
else
{
if(userList[i].isLoggedIn()) //Check if user is already logged in
{
response = "You are already logged in as ";
response += (userSockets.find(i)->second).getName();
response += "\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (USER - already logged in)");
exit(1);
}
}
}
}
else //User doesn't exist, create it
{
User newUser(tokens[1], tokens[2], true, i);
addNewUser(newUser, i, userList, userSockets);
response = "Welcome to the chat server ";
response += name;
response += "!\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (USER - welcome to server)");
exit(1);
}
break;
}
}
}
}
cout << "Num users:" << userList.size() << endl;
}
else if(bufString.find("ROOMS") != string::npos) //List all rooms
{
if(((currentUser = getClientUsername(userSockets, i)).getName()).empty())
{
break; //Client has no username, do not process command
}
if(currentUser.isLoggedIn())
{
response = "List of rooms on server:\n";
for(unsigned int i = 0; i < roomList.size(); i++)
response += "\t" + roomList[i].getName() + "\n";
}
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (ROOMS)");
exit(1);
}
}
else if(bufString.find("JOIN") != string::npos) //<room> --> join room. if doesn't exist, create it.
{
if(((currentUser = getClientUsername(userSockets, i)).getName()).empty())
{
break; //Client has no username, do not process command
}
if(currentUser.isLoggedIn())
{
vector<string> tokens = splitString(bufString);
string roomName = tokens[1];
if(roomName[0] != '@')
{
response = "All room names must start with the '@' symbol.\n";
response += "Type another command\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (JOIN - illegal roomname)");
exit(1);
}
}
else
{
Chatroom room = findRoom(roomName, roomList);
if(room.getName() != "")
{
room.addUser(currentUser);
response = currentUser.getName() + " has joined " + room.getName() + ".\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (JOIN - joining existing room)");
exit(1);
}
}
else //Create new room
{
Chatroom newRoom(roomName);
roomList.push_back(newRoom);
newRoom.addUser(currentUser);
response = newRoom.getName() + " created. You are the first user.\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (JOIN - creating new room)");
exit(1);
}
}
}
}
}
else if(bufString.find("PART") != string::npos) //<room> --> leave room
{
if(((currentUser = getClientUsername(userSockets, i)).getName()).empty())
{
break; //Client has no username, do not process command
}
if(currentUser.isLoggedIn())
{
vector<string> tokens = splitString(bufString);
string roomName = tokens[1];
if(roomName[0] != '@')
{
response = "All room names must start with the '@' symbol.\n";
response += "Type another command\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (PART - illegal roomname)");
exit(1);
}
}
else
{
Chatroom room = findRoom(roomName, roomList);
if(!room.getName().empty())
{
room.removeUser(currentUser);
response = currentUser.getName() + " has left " + room.getName() + ".\n";
response += "No more messages will be received from this room.\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (JOIN - joining existing room)");
exit(1);
}
}
}
}
}
else if(bufString.find("LIST") != string::npos) //<room> --> list users in specified room
{
if(((currentUser = getClientUsername(userSockets, i)).getName()).empty())
{
break; //Client has no username, do not process command
}
if(currentUser.isLoggedIn())
{
vector<string> tokens = splitString(bufString);
string roomName = tokens[1];
if(roomName[0] != '@')
{
response = "All room names must start with the '@' symbol.\n";
response += "Type another command\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (PART - illegal roomname)");
exit(1);
}
}
else
{
Chatroom room = findRoom(roomName, roomList);
if(!room.getName().empty())
{
if(room.getUsers().size() == 0)
{
response = "No users in " + room.getName() + ".\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (PART - illegal roomname)");
exit(1);
}
}
else
{
response = "List of users in " + room.getName() + ":\n";
for(unsigned int i = 0; i < room.getUsers().size(); i++)
response += "\t" + room.getUsers()[i].getName() + "\n";
}
}
}
}
}
else if(bufString.find("SAY") != string::npos) //<target> <length> <msg> --> target can be user or room.
{
if(((currentUser = getClientUsername(userSockets, i)).getName()).empty())
{
break; //Client has no username, do not process command
}
if(currentUser.isLoggedIn())
{
vector<string> tokens = splitString(bufString);
string target = tokens[1];
string message = tokens[3];
for(unsigned int j = 3; j < tokens.size(); j++)
{
message += tokens[j];
}
message += "\n";
int length = message.size();
response = "";
//Check target exists
if(target[0] == '@') //Is target a chatroom?
{
bool foundRoom = false;
for (unsigned int j = 0; j < roomList.size(); ++j) //Loop through rooms
{
if(target == roomList[j].getName())
{
foundRoom = true;
//Loop through users in current room - send message to all of them
for(unsigned int k = 0; k < roomList[j].getUsers().size(); ++k)
{
int target_fd = roomList[j].getUsers()[k].getfd();
if((numBytes = send(target_fd, convertToChar(message), length, 0)) < 0)
{
perror("send (SAY - sending to room)");
exit(1);
}
}
}
}
if(!foundRoom)
{
response = "That room does not exist.\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (SAY - room doesn't exist)");
exit(1);
}
}
}
else //Target is a user
{
bool foundUser = true;
for(unsigned int j = 0; j < userList.size(); ++j) //Loop through users
{
if(target == userList[j].getName()) //Does user exist?
{
foundUser = true;
int target_fd = userList[j].getfd();
if((numBytes = send(target_fd, convertToChar(message), length, 0)) < 0)
{
perror("send (SAY - sending to single user)");
exit(1);
}
}
}
if(!foundUser)
{
response = "That user does not exist.\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (SAY - room doesn't exist)");
exit(1);
}
}
}
}
}
else if(bufString.find("QUIT") != string::npos) //Disconnect user, make him/her leave all rooms
{
if(((currentUser = getClientUsername(userSockets, i)).getName()).empty())
{
break; //Client has no username, do not process command
}
if(currentUser.isLoggedIn())
{
response = "";
for(unsigned int j = 0; j < roomList.size(); ++j)
{
bool leftRoom = roomList[j].removeUser(currentUser);
if(leftRoom)
{
response += "You have left " + roomList[j].getName() + "\n";
}
}
response += "Logging out...\n";
response += "Good-Bye!\n";
currentUser.setLoggedIn(false);
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (QUIT)");
exit(1);
}
close(i);
FD_CLR(i, &master); //delete from master list
}
}
else //Illegal command
{
response = "Illegal command given.\n";
response += "List of legal commands:\n";
response += "\tCHAT - server connect\n";
response += "\tUSERS - prints list of users\n";
response += "\tUSER <name> <password> - login and username creation\n";
response += "\tROOMS - prints list of rooms\n";
response += "\tJOIN <room> - join a room or create a room if given \n\t\t room name doesn't exist\n";
response += "\tPART <room> - leave a joined room\n";
response += "\tLIST <room> - list users in a room\n";
response += "\tSAY <target> <length> <message> - send a message to a user \n\t\t or entire room\n";
response += "\tQUIT - disconnect and leave all joined room\n";
if((numBytes = send(i, convertToChar(response), response.size(), 0)) < 0)
{
perror("send - illegal command)");
exit(1);
}
}
}
}
}
}
}
return 0;
}
//Splits strings by whitespace
vector<string> splitString(string str)
{
string buffer;
stringstream ss(str);
vector<string> tokens;
while(ss >> buffer)
tokens.push_back(buffer);
for(unsigned int i = 0; i < tokens.size(); i++)
{
cout << tokens[i] << endl;
}
return tokens;
}
//Returns room from Chatroom list
Chatroom findRoom(string roomName, vector<Chatroom> &roomList)
{
for(unsigned int i = 0; i < roomList.size(); i++)
{
if(roomName == roomList[i].getName())
return roomList[i];
}
return Chatroom("");
}
User getClientUsername(map<int, User> &userSockets, int user_fd)
{
typename map<int,User>::iterator p;
User currentUser("", "");
if((p = userSockets.find(user_fd)) != userSockets.end()) //Does this client have a username?
{
currentUser = p->second;
return currentUser;
}
return currentUser;
}
char* convertToChar(string str)
{
char* converted = new char[str.size() + 1];
converted[str.size()] = '\0';
memcpy(converted, str.c_str(), str.size());
return converted;
}
void addNewUser(User &newUser, int user_fd, vector<User> &userList, map<int, User> &userSockets)
{
string response;
int numBytes = 0;
userList.push_back(newUser);
userSockets.insert( pair<int,User>(user_fd, newUser) );
response = "New user created with given credentials.\n";
if((numBytes = send(user_fd, convertToChar(response), response.size(), 0)) < 0)
{
perror("send (USER - create new user)");
exit(1);
}
cout << endl << "test1" << endl;
return;
}
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
//IPv6
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}