-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.cpp
More file actions
570 lines (474 loc) · 17.2 KB
/
Copy pathserver.cpp
File metadata and controls
570 lines (474 loc) · 17.2 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
#include "Server.hpp"
Server::Server(const std::string &port_str, const std::string &password) : password(password)
{
initServer(port_str);
}
Server::~Server()
{
close(server_fd);
for (std::map<int, Client *>::iterator it = clients.begin(); it != clients.end(); ++it)
{
close(it->first);
delete it->second;
}
for (std::map<std::string, Channel *>::iterator it = channels.begin(); it != channels.end(); ++it)
{
delete it->second;
}
}
void Server::setNonBlocking(int fd)
{
fcntl(fd, F_SETFL, O_NONBLOCK);
}
bool Server::isNumber(const std::string& input)
{
for (size_t j = 0; j < input.size(); j++)
if (!std::isdigit(input[j]))
return false;
return true;
}
void Server::initServer(const std::string &port_str)
{
int port = std::atoi(port_str.c_str());
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1)
{
std::cerr << RED_COLOR << "Socket creation failed" << RESET_COLOR << std::endl;
std::exit(EXIT_FAILURE);
}
setNonBlocking(server_fd);
int opt = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)))
{
std::cerr << RED_COLOR << "Set socket options failed" << RESET_COLOR << std::endl;
}
sockaddr_in address;
std::memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(port);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0)
{
std::cerr << RED_COLOR << "Bind failed" << RESET_COLOR << std::endl;
std::exit(EXIT_FAILURE);
}
if (listen(server_fd, SOMAXCONN) < 0)
{
std::cerr << RED_COLOR << "Listen failed" << RESET_COLOR << std::endl;
std::exit(EXIT_FAILURE);
}
struct pollfd server_pollfd;
server_pollfd.fd = server_fd;
server_pollfd.events = POLLIN;
poll_fds.push_back(server_pollfd);
registerCommands();
std::cout << GREEN_COLOR << "Server listening on port " << port << RESET_COLOR << std::endl;
}
void Server::run()
{
while (true)
{
int poll_count = poll(&poll_fds[0], poll_fds.size(), -1);
if (poll_count == -1)
{
std::cerr << RED_COLOR << "Poll error: " << strerror(errno) << RESET_COLOR << std::endl;
std::exit(EXIT_FAILURE);
}
for (size_t i = 0; i < poll_fds.size(); ++i)
{
if (poll_fds[i].revents & POLLIN)
{
if (poll_fds[i].fd == server_fd)
{
acceptNewClient();
}
else
{
handleClientMessage(poll_fds[i].fd);
}
}
}
}
}
void Server:: acceptNewClient()
{
sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len);
if (client_fd == -1)
{
std::cerr << RED_COLOR << "Accept failed" << RESET_COLOR << std::endl;
return;
}
setNonBlocking(client_fd);
if (clients.size() >= MAX_CLIENTS)
{
std::string msg = "ERROR :Server full\r\n";
send(client_fd, msg.c_str(), msg.length(), 0);
close(client_fd);
return;
}
clients[client_fd] = new Client(client_fd);
struct pollfd client_pollfd;
client_pollfd.fd = client_fd;
client_pollfd.events = POLLIN;
poll_fds.push_back(client_pollfd);
std::cout << GREEN_COLOR << "New client connected: FD " << client_fd << RESET_COLOR << std::endl;
sendMessage(client_fd, "You must log in with PASS first\r\n");
}
void Server::removeClient(Client *client, const std::vector<std::string> ¶ms)
{
(void)params;
int fd = client->getFd();
close(fd);
delete clients[fd];
clients.erase(fd);
for (std::vector<struct pollfd>::iterator it = poll_fds.begin(); it != poll_fds.end(); ++it)
{
if (it->fd == fd)
{
poll_fds.erase(it);
break;
}
}
std::cout << RED_COLOR << "Client disconnected: FD " << fd << RESET_COLOR << std::endl;
}
void Server::handleClientMessage(int fd)
{
char buffer[BUFFER_SIZE];
int bytes_received = recv(fd, buffer, BUFFER_SIZE - 1, 0);
if (bytes_received <= 0)
{
Client *client = clients[fd];
std::vector<std::string> params;
removeClient(client, params);
return;
}
buffer[bytes_received] = '\0';
std::string message(buffer);
Client *client = clients[fd];
parseCommand(client, message);
}
void Server::sendMessage(int fd, const std::string &message)
{
send(fd, message.c_str(), message.length(), 0);
}
void Server::sendWelcomeMessage(Client *client)
{
sendMessage(client->getFd(), ":" + client->getHostname() + " 001 " + client->getNickname() + " :Welcome to the Internet Relay Network " + client->getNickname() + "!" + "@" + client->getHostname() + "\r\n");
sendMessage(client->getFd(), ":" + client->getHostname() + " 002 " + client->getNickname() + " :Your host is " + client->getHostname() + "\r\n");
sendMessage(client->getFd(), ":" + client->getHostname() + " 003 " + client->getNickname() + " :This server was created\r\n");
}
void Server::registerCommands()
{
command_map["PASS"] = &Server::handlePASS;
command_map["NICK"] = &Server::handleNICK;
command_map["USER"] = &Server::handleUSER;
command_map["CREATE"] = &Server::createChannel;
command_map["JOIN"] = &Server::joinChannel;
command_map["QUIT"] = &Server::removeClient;
channel_command_map["DELETE"] = &Server::deleteChannel;
channel_command_map["LEAVE"] = &Server::leaveChannel;
channel_command_map["ADDOP"] = &Server::addOpToChannel;
channel_command_map["KICK"] = &Server::kickMemberFromChannel;
channel_command_map["LSTMEMBERS"] = &Server::listChannelMembers;
common_command_map["PRIVMSG"] = &Server::handlePRIVMSG;
common_command_map["PING"] = &Server::handlePING;
common_command_map["LIST"] = &Server::listChannels;
common_command_map["HELP"] = &Server::handleHelp;
}
void Server::parseCommand(Client *client, const std::string &message)
{
std::string msg = message;
size_t pos;
while ((pos = msg.find("\n")) != std::string::npos)
{
std::string line = msg.substr(0, pos);
msg.erase(0, pos + 2);
if (line.empty())
continue;
std::istringstream iss(line);
std::string command;
iss >> command;
std::vector<std::string> params;
std::string param;
while (iss >> param)
{
params.push_back(param);
}
if (!client->getIsAuthenticated() && command != "PASS")
{
sendMessage(client->getFd(), Prefix(client) + "You must log in with PASS first\r\n");
continue;
}
if (client->getNickname().empty() && command != "NICK" && command != "PASS")
{
sendMessage(client->getFd(), Prefix(client) + "ERROR You must set a nickname first with NICK\r\n");
continue;
}
if (client->getHostname().empty() && command != "USER" && command != "PASS" && command != "NICK")
{
sendMessage(client->getFd(), Prefix(client) + "ERROR You must set a username first with USER\r\n");
continue;
}
for (std::map<std::string, Channel *>::iterator it = channels.begin(); it != channels.end(); ++it)
{
if (it->second->isMember(client))
{
if (channel_command_map.find(command) != channel_command_map.end())
(this->*channel_command_map[command])(it->second, client, params);
else if (common_command_map.find(command) != common_command_map.end())
(this->*common_command_map[command])(client, params);
else
it->second->broadcastMessage(message, client);
return;
}
}
if (command_map.find(command) != command_map.end())
(this->*command_map[command])(client, params);
else if (common_command_map.find(command) != common_command_map.end())
(this->*common_command_map[command])(client, params);
else
sendMessage(client->getFd(), Prefix(client) + "ERROR :Unknown command\r\n");
}
}
void Server::listChannels(Client *client, const std::vector<std::string> ¶ms)
{
(void)params;
if (channels.empty())
{
sendMessage(client->getFd(), Prefix(client) + "ERRROR :No available channels.\r\n");
return;
}
std::string channel_list = "Available channels:\r\n";
for (std::map<std::string, Channel *>::iterator it = channels.begin(); it != channels.end(); ++it)
{
std::string channel_name = it->first;
int member_count = it->second->getMembers().size();
std::stringstream ss;
ss << member_count;
channel_list += channel_name + " (" + ss.str() + " members)\r\n";
}
sendMessage(client->getFd(), Prefix(client) + channel_list);
}
void Server::deleteChannel(Channel *channel, Client *client, const std::vector<std::string> ¶ms)
{
(void)params;
channel->deleteChannel(client);
}
void Server::removeChannel(Channel *channel)
{
channels.erase(channel->getName());
}
void Server::leaveChannel(Channel *channel, Client *client, const std::vector<std::string> ¶ms)
{
(void)params;
channel->leaveChannel(client);
}
void Server::listChannelMembers(Channel *channel, Client *client, const std::vector<std::string> ¶ms)
{
(void)params;
channel->listMembers(client);
}
void Server::createChannel(Client *client, const std::vector<std::string> ¶ms)
{
if (params.size() < 2)
{
sendMessage(client->getFd(), Prefix(client) + "Error: Usage: CREATE <channel name> <password>\r\n");
return;
}
std::string name = params[0];
std::string pass = params[1];
if (channels.find(name) != channels.end())
{
sendMessage(client->getFd(), Prefix(client) + "Error: Channel already exists.\r\n");
return;
}
Channel *new_channel = new Channel(name, this);
new_channel->setPassword(pass);
new_channel->addMember(client);
new_channel->addOp(client);
channels[name] = new_channel;
sendMessage(client->getFd(), Prefix(client) + "Channel created successfully: " + name + "\r\n");
}
void Server::joinChannel(Client *client, const std::vector<std::string> ¶ms)
{
if (params.size() != 2)
{
sendMessage(client->getFd(), Prefix(client) + "Error Usage: JOIN <channel name> <password>\r\n");
return;
}
std::string name = params[0];
std::string pass = params[1];
if (channels.find(name) == channels.end())
sendMessage(client->getFd(), Prefix(client) + "ERROR :Channel does not exist\r\n");
else
{
if (channels[name]->isBlacklisted(client))
{
sendMessage(client->getFd(), Prefix(client) + "ERROR :You have been banned from this channel\r\n");
return;
}
if (channels[name]->getPassword() == pass)
{
channels[name]->addMember(client);
std::cout << GREEN_COLOR << client->getNickname() << " joined channel: " << name << RESET_COLOR << std::endl;
channels[name]->broadcastMessage(client->getNickname() + " has joined the channel\r\n", client);
sendMessage(client->getFd(), Prefix(client) + "SUCCESS :You have joined the channel\r\n");
}
else
sendMessage(client->getFd(), Prefix(client) + "ERROR :Invalid password\r\n");
}
}
void Server::kickMemberFromChannel(Channel *channel, Client *client, const std::vector<std::string> ¶ms)
{
if (params.size() != 1)
{
sendMessage(client->getFd(), Prefix(client) + "ERROR :No nickname given\r\n");
return;
}
std::string nickname = params[0];
channel->kickMember(client, nickname);
}
void Server::addOpToChannel(Channel *channel, Client *client, const std::vector<std::string> ¶ms)
{
if (params.size() != 1)
{
sendMessage(client->getFd(), Prefix(client) + "ERROR :No nickname given\r\n");
return;
}
std::string nickname = params[0];
if (channel->isOp(client))
{
if (client->getNickname() == nickname)
{
sendMessage(client->getFd(), Prefix(client) + "ERROR :You cannot make yourself op\r\n");
return;
}
std::set<Client *> members = channel->getMembers();
for (std::set<Client *>::iterator memberIt = members.begin(); memberIt != members.end(); ++memberIt)
{
if ((*memberIt)->getNickname() == nickname)
{
channel->addOp(*memberIt);
sendMessage(client->getFd(), Prefix(client) + "SUCCESS :User has been made op\r\n");
return;
}
}
sendMessage(client->getFd(), Prefix(client) + "ERROR :User not found in this channel\r\n");
return;
}
sendMessage(client->getFd(), Prefix(client) + "ERROR :You are not op\r\n");
}
void Server::handlePASS(Client *client, const std::vector<std::string> ¶ms)
{
if (params.empty())
{
sendMessage(client->getFd(), Prefix(client) + "ERROR :No password given\r\n");
return;
}
if (params[0] == password)
{
client->setIsAuthenticated(true);
sendMessage(client->getFd(), Prefix(client) + "SUCCESS :Auth Password accepted\r\n");
}
else
{
sendMessage(client->getFd(), Prefix(client) + "ERROR :Invalid password\r\n");
}
}
void Server::handleNICK(Client *client, const std::vector<std::string> ¶ms)
{
if (params.empty())
{
sendMessage(client->getFd(), Prefix(client) + "ERROR :No nickname given\r\n");
return;
}
std::string new_nickname = params[0];
for (std::map<int, Client *>::const_iterator it = clients.begin(); it != clients.end(); ++it)
{
if (it->second->getNickname() == new_nickname && it->first != client->getFd())
{
sendMessage(client->getFd(), "ERROR :Nickname is already in use\r\n");
return;
}
}
client->setNickname(new_nickname);
sendMessage(client->getFd(), Prefix(client) + "SUCCESS :Nickname set to " + new_nickname + "\r\n");
}
void Server::handleUSER(Client *client, const std::vector<std::string> ¶ms)
{
if (params.size() != 4)
{
sendMessage(client->getFd(), Prefix(client) + "ERROR : Usage: USER <username> <hostname> <servername> <realname>\r\n");
return;
}
client->setUsername(params[0]);
client->setHostname(params[1]);
client->setServername(params[2]);
client->setRealname(params[3]);
sendMessage(client->getFd(), Prefix(client) + "SUCCESS :User registered\r\n");
sendWelcomeMessage(client);
}
void Server::handlePING(Client *client, const std::vector<std::string> ¶ms)
{
if (params.size() < 1)
{
sendMessage(client->getFd(), Prefix(client) + "ERROR :No PING token given\r\n");
return;
}
std::string response = "PONG :" + params[0] + "\r\n";
sendMessage(client->getFd(), Prefix(client) + response);
}
void Server::handlePRIVMSG(Client *client, const std::vector<std::string> ¶ms)
{
if (params.size() < 2)
{
sendMessage(client->getFd(), Prefix(client) + "ERROR :Not enough parameters\r\n");
return;
}
std::string recipient = params[0];
std::string message = params[1];
for (size_t i = 2; i < params.size(); ++i)
{
message += " " + params[i];
}
Client *targetClient = NULL;
for (std::map<int, Client *>::const_iterator it = clients.begin(); it != clients.end(); ++it)
{
if (it->second->getNickname() == recipient)
{
targetClient = it->second;
break;
}
}
if (targetClient)
{
std::string full_message = ":" + client->getNickname() + " PRIVMSG " + recipient + " " + message + "\r\n";
sendMessage(targetClient->getFd(), Prefix(client) + full_message);
}
else
{
sendMessage(client->getFd(), Prefix(client) + "ERROR :No such nick\r\n");
}
}
const std::string Server::Prefix(Client *client) const
{
return ":" + client->getNickname() + "!" + client->getUsername() + "@" + client->getHostname() + " ";
}
void Server::handleHelp(Client *client, const std::vector<std::string> ¶ms)
{
(void)params;
std::string help_message = "Available commands:\r\n";
help_message += "PASS <password> - Authenticate with server\r\n";
help_message += "NICK <nickname> - Set your nickname\r\n";
help_message += "USER <username> <hostname> <servername> <realname> - Set your user information\r\n";
help_message += "PING <token> - Ping the server\r\n";
help_message += "CREATE <channel name> <password> - Create a new channel\r\n";
help_message += "JOIN <channel name> <password> - Join a channel\r\n";
help_message += "LIST - List available channels\r\n";
help_message += "PRIVMSG <nickname> <message> - Send a private message to a user\r\n";
help_message += "HELP - Display this help message\r\n";
help_message += "QUIT - Disconnect from the server\r\n";
sendMessage(client->getFd(), Prefix(client) + help_message);
}