-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_grp.cpp
More file actions
559 lines (504 loc) · 21.1 KB
/
Copy pathserver_grp.cpp
File metadata and controls
559 lines (504 loc) · 21.1 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
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <mutex>
#include <thread>
#include <atomic>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <fstream>
#include <sstream>
#define PORT 12345
#define BUFFER_SIZE 1024
using namespace std;
mutex cout_mutex;
mutex user_mutex;
mutex group_mutex;
mutex send_mutex;
unordered_map <int, string> clients; // Client socket -> username
unordered_map <string,int> user_socket; // Username -> client socket
unordered_map <string, string> users; // Username -> password
unordered_map <string, unordered_set <int> > groups; // Group -> client sockets
atomic<bool> shutdown_server(false);
void listen_for_exit_command() {
string input;
while (true) {
cin >> input;
if (input == "/exit") {
if(clients.size()!=0){
{
lock_guard<mutex> lock(cout_mutex);
std::cout<<"Error: There are still clients connected. Please disconnect all clients before shutting down the server.\n";
continue;
}
}
shutdown_server = true; // Set the shutdown flag
break;
}
}
}
// sends message to all clients except the sender
void broadcast_message(const string &message, int sender_socket) {
for (auto &client : clients) {
if (client.first != sender_socket) {
{
lock_guard<mutex> lock(send_mutex);
send(client.first, message.c_str(), message.size(), 0);
}
}
}
}
// sends message to a specific client
void message_person(const string &message, int sender_socket, string receiver) {
if(user_socket.find(receiver) != user_socket.end()){
{
lock_guard<mutex> lock(send_mutex);
send(user_socket[receiver], message.c_str(), message.size(), 0);
}
}
else{
string user_not_found = "Error: User not found.\n";
{
lock_guard<mutex> lock(send_mutex);
send(sender_socket, user_not_found.c_str(), user_not_found.size(), 0);
}
}
}
// creates a group
void create_group(const string &group_name, int client_socket) {
// size_t space_pos = group_name.find(' ');
// if (space_pos != string::npos) {
// string invalid_group_name = "Error: Group name cannot contain spaces.\n";
// {
// lock_guard<mutex> lock(send_mutex);
// send(client_socket, invalid_group_name.c_str(), invalid_group_name.size(), 0);
// }
// return;
// }
if (groups.find(group_name) == groups.end()) {
groups[group_name].insert(client_socket);
string group_created = "Group " + group_name + " has been created by " + clients[client_socket] + ".\n";
{
lock_guard<mutex> lock(user_mutex);
broadcast_message(group_created, client_socket);
}
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, group_created.c_str(), group_created.size(), 0);
}
}
else {
// Group already exists
string group_exists = "Error: Group already exists.\n";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, group_exists.c_str(), group_exists.size(), 0);
}
}
}
// sends message to all clients in a group
void group_message(const string &message, int sender_socket, string group) {
if (groups.find(group) != groups.end()) {
if (groups[group].find(sender_socket) == groups[group].end()) {
string not_in_group = "Error: You are not part of this group.\n";
{
lock_guard<mutex> lock(send_mutex);
send(sender_socket, not_in_group.c_str(), not_in_group.size(), 0);
}
return;
}
for (auto &client : groups[group]) {
if (client != sender_socket) {
{
lock_guard<mutex> lock(send_mutex);
send(client, message.c_str(), message.size(), 0);
}
}
}
}
else {
string group_not_found = "Error: Group not found.\n";
{
lock_guard<mutex> lock(send_mutex);
send(sender_socket, group_not_found.c_str(), group_not_found.size(), 0);
}
}
}
// handles the client
void handle_client(int client_socket) {
char buffer[BUFFER_SIZE] = {0}; // buffer to store messages
string auth_request = "Enter username: ";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, auth_request.c_str(), auth_request.size(), 0);
}
// Read the username
int valread = read(client_socket, buffer, BUFFER_SIZE);
if (valread > 0) {
buffer[valread] = '\0';
string input(buffer);
size_t space_pos = input.find(' ');
string username = input;
memset(buffer, 0, BUFFER_SIZE);
string auth_request2 = "Enter password: ";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, auth_request2.c_str(), auth_request2.size(), 0);
}
string password;
// Read the password
valread = read(client_socket, buffer, BUFFER_SIZE);
if (valread > 0) {
buffer[valread] = '\0';
password = buffer;
}
else{
// Error reading password
string failure_message = "Authentication failed. Disconnecting...\n";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, failure_message.c_str(), failure_message.size(), 0);
}
close(client_socket);
return;
}
if (users.find(username) != users.end() && users[username] == password) {
{
// Check if the user is already connected
lock_guard<mutex> lock(user_mutex);
for (auto &user : clients) {
if (user.second == username) {
string already_connected = "Error: User already connected. Disconnecting...\n";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, already_connected.c_str(), already_connected.size(), 0);
}
close(client_socket);
return;
}
}
clients[client_socket] = username;
user_socket[username] = client_socket;
}
string success_message = "Authentication successful. Welcome!\n";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, success_message.c_str(), success_message.size(), 0);
}
{
lock_guard<mutex> lock(cout_mutex);
std::cout << "User " << username << " authenticated successfully." << endl;
}
string interaction_message = "You are now connected to the server.\n";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, interaction_message.c_str(), interaction_message.size(), 0);
}
usleep(1000);
// Handle user interaction
while(true){
memset(buffer, 0, BUFFER_SIZE);
int message = read(client_socket, buffer, BUFFER_SIZE);
if(message>0){
buffer[message] = '\0';
string input(buffer);
bool flag_more_info = true;
while(flag_more_info){
space_pos = input.find(' ');
{
lock_guard<mutex> lock(cout_mutex);
string message = "[" + username+ "]" + ": " + input + "\n";
std::cout<<message<<"\n";
}
string function;
string information;
if(space_pos == string::npos){
function = input;
}
else{
function = input.substr(0, space_pos);
information = input.substr(space_pos + 1);
}
size_t slash_pos = information.find('/');
string information_cp = information;
if (slash_pos != string::npos) {
information = information_cp.substr(0,slash_pos);
input = information_cp.substr(slash_pos);
flag_more_info = true;
}
else{
flag_more_info = false;
}
if(function == "/broadcast"){
string final_message = "[Broadcast message by " + username + "]: " + information;
{
lock_guard<mutex> lock(user_mutex);
broadcast_message(final_message, client_socket);
}
}
else if(function == "/msg"){
int second_space = information.find(' ');
string receiver = information.substr(0, second_space);
string message = information.substr(second_space + 1);
string final_message = "[" + username + "]: " + message;
{
lock_guard<mutex> lock(user_mutex);
message_person(final_message, client_socket, receiver);
}
}
else if (function == "/create_group") {
{
lock_guard<mutex> lock(group_mutex);
create_group(information, client_socket);
}
}
else if (function == "/join_group") {
{
lock_guard<mutex> lock(group_mutex);
if (groups.find(information) != groups.end()) {
groups[information].insert(client_socket);
string joined_group = username + " has joined the group " + information + ".\n";
group_message(joined_group, client_socket, information);
string alert = "You have joined the group " + information + ".\n";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, alert.c_str(), alert.size(), 0);
}
}
else {
string group_not_found = "Error: Group not found.\n";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, group_not_found.c_str(), group_not_found.size(), 0);
}
}
}
}
else if (function == "/leave_group") {
{
lock_guard<mutex> lock(group_mutex);
if (groups.find(information) != groups.end()) {
if(groups[information].find(client_socket) == groups[information].end()){
string not_in_group = "Error: You are not part of this group.\n";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, not_in_group.c_str(), not_in_group.size(), 0);
}
continue;
}
else{
string left_group = username + " has left the group " + information + ".\n";
group_message(left_group, client_socket, information);
string alert = "You have left the group " + information + ".\n";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, alert.c_str(), alert.size(), 0);
}
groups[information].erase(client_socket);
}
}
else {
string group_not_found = "Error: Group not found.\n";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, group_not_found.c_str(), group_not_found.size(), 0);
}
}
}
}
else if (function == "/group_msg") {
int second_space = information.find(' ');
string group = information.substr(0, second_space);
string message = information.substr(second_space + 1);
string final_message = "[" + group + " - " + username + "]: " + message;
{
lock_guard<mutex> lock(group_mutex);
group_message(final_message, client_socket, group);
}
}
else if(function == "/exit"){
string exit_message = "Exiting...\n";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, exit_message.c_str(), exit_message.size(), 0);
}
break;
}
else if(function == "/list_users"){
string user_list = "Users connected to the server:\n";
{
lock_guard<mutex> lock(user_mutex);
for (auto &user : clients) {
user_list += user.second + "\n";
}
}
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, user_list.c_str(), user_list.size(), 0);
}
}
else if(function == "/list_groups"){
string group_list = "Groups available:\n";
{
lock_guard<mutex> lock(group_mutex);
for (auto &group : groups) {
group_list += group.first + "\n";
}
}
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, group_list.c_str(), group_list.size(), 0);
}
}
else {
string invalid_command = "Error: Invalid command.\n";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, invalid_command.c_str(), invalid_command.size(), 0);
}
}
}
}
}
// Remove user upon disconnection
{
lock_guard<mutex> lock(user_mutex);
clients.erase(client_socket);
user_socket.erase(username);
}
{
lock_guard<mutex> lock(cout_mutex);
std::cout << "User " << username << " disconnected." << endl;
}
}
else {
string failure_message = "Authentication failed. Disconnecting...\n";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, failure_message.c_str(), failure_message.size(), 0);
}
close(client_socket);
return;
}
}
else {
string failure_message = "Authentication failed. Disconnecting...\n";
{
lock_guard<mutex> lock(send_mutex);
send(client_socket, failure_message.c_str(), failure_message.size(), 0);
}
close(client_socket);
return;
}
close(client_socket);
}
int main() {
ifstream file("users.txt");
if (!file.is_open()) {
cerr << "Error: Could not open the file." << endl;
return 1;
}
string line;
while (getline(file, line)) {
istringstream lineStream(line);
string part1, part2;
// Use getline to extract the two parts
if (getline(lineStream, part1, ':') && getline(lineStream, part2)) {
users[part1] = part2;
} else {
cerr << "Warning: Malformed line: " << line << endl;
}
}
file.close();
int server_fd; // fd for server socket
struct sockaddr_in address; // server address information
int opt = 1; // Option
int addrlen = sizeof(address);
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("Socket failed");
exit(EXIT_FAILURE);
}
//Set socket options to reuse address and port
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("Setsockopt failed");
close(server_fd);
exit(EXIT_FAILURE);
}
// Configure server address structure
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Bind the socket to the specified address and port
if ((::bind(server_fd, (struct sockaddr *)&address, sizeof(address))) < 0) {
perror("Bind failed");
close(server_fd);
exit(EXIT_FAILURE);
}
// Start listening for incoming connections
if (listen(server_fd, 3) < 0) {
perror("Listen failed");
close(server_fd);
exit(EXIT_FAILURE);
}
{
lock_guard<mutex> lock(cout_mutex);
std::cout << "Server is listening on port " << PORT << "..." << endl;
}
fcntl(server_fd, F_SETFL, O_NONBLOCK); // Make the server socket non-blocking
thread exit_thread(listen_for_exit_command);
exit_thread.detach(); //listen for the exit command in the background
vector<thread> threads;
while (!shutdown_server) {
int new_socket; // Socket for the new client connection
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
if (errno == EWOULDBLOCK || errno == EAGAIN) {
// No pending connections, sleep for a short time and retry
this_thread::sleep_for(chrono::milliseconds(100));
continue;
}
else if (shutdown_server) {
// Accept failed because the server is shutting down
break;
}
perror("Accept failed");
close(server_fd);
exit(EXIT_FAILURE);
}
{
lock_guard<mutex> lock(cout_mutex);
std::cout << "Connection established with a client." << endl;
}
// Handle the client in a separate thread
threads.emplace_back(::thread(handle_client, new_socket));
}
// Server is shutting down
std::cout << "Server is shutting down..." << endl;
// Close all client sockets
for (auto client_socket : clients) {
close(client_socket.first);
}
std::cout<<"Closing server socket..."<<endl;
// Close the server socket
close(server_fd);
std::cout<<"Server socket closed."<<endl;
// Join all client threads
for (thread &t : threads) {
if (t.joinable()) {
t.join();
}
}
std::cout<<"All client threads joined."<<endl;
// Join the exit thread
if (exit_thread.joinable()) {
exit_thread.join();
}
std::cout << "Server has shut down cleanly." << endl;
return 0;
}