-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.cpp
705 lines (635 loc) · 19 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
#include "Server.hpp"
#define MAX_USERS 10
using namespace irc;
Server::Server(std::string password, const char* port) : password(password), port(port) {
std::cout << "Initializing server..." << std::endl;
this->users = std::vector<User *>();
this->channels = std::vector<Channel *>();
this->pfds = std::vector<pollfd>();
this->conf = std::map<std::string, std::string>();
this->operators = std::vector<User *>();
}
Server::~Server() {
std::cout << "Closing server..." << std::endl;
for (std::vector<User *>::reverse_iterator it = this->users.rbegin(); it != this->users.rend(); it++) {
this->deleteUser(*it, "Closing server");
}
for (std::vector<pollfd>::reverse_iterator it = pfds.rbegin(); it != pfds.rend(); it++) {
close((*it).fd);
}
for (std::vector<Channel *>::reverse_iterator it = this->channels.rbegin(); it != this->channels.rend(); it++) {
delete *it;
}
}
int Server::readConfFile() {
std::ifstream in;
int res = 0;
std::string line;
std::string key;
std::string value = "";
size_t found;
in.open("./ft_irc.conf", std::ifstream::in);
if (!in.good()) {
std::cerr << "Can't open configuration file" << std::endl;
std::cerr << "Please check that ./ft_irc.conf is present in Server folder" << std::endl;
return (-1);
}
while (!in.eof() && in.good()) {
value = "";
std::getline(in, line);
if ((found = line.find_first_not_of(' ')) != std::string::npos) {
line.erase(0, found);
}
if (line.empty() || line[found] == '#') {
continue;
} else if ((found = line.find("=\"")) == std::string::npos) {
std::cerr << "Should be under format key=\"value\"" << std::endl;
res = -1;
break;
}
key = line.substr(0, found);
line.erase(0, found + 2);
while ((found = line.find('"')) == std::string::npos) {
value.append(line);
std::getline(in, line);
value.append(" ");
}
value += line.substr(0, found);
line.erase(0, found + 1);
if (!line.empty()) {
std::cerr << "Error in configuration file" << std::endl;
std::cerr << "key=\"value\" should be followed by a line return" << std::endl;
res = -1;
break;
}
this->conf.insert(std::make_pair(key, value));
}
if (!in.eof()) {
std::cerr << "Error while reading configuration file" << std::endl;
res = -1;
}
in.close();
return res;
}
int Server::checkConf() {
if (this->conf.count("name") == 0 || this->conf.count("version") == 0
|| this->conf.count("adminloc1") == 0 || this->conf.count("adminemail") == 0
|| this->conf.count("creation") == 0) {
std::cerr << "Missing at least one non-optionnal configuration parameter" << std::endl;
return (-1);
}
if ((this->getName()).size() > 63) {
std::cerr << "Server name should be under 63 characters (please, modify .conf file)" << std::endl;
return (-1);
}
if (this->conf.count("op_pwd") == 0) {
this->conf.insert(std::make_pair("op_pwd", "admin"));
}
return 0;
}
int Server::initServer() {
struct addrinfo hints;
struct addrinfo *ai;
struct addrinfo *p;
int server_fd;
int opt = 1;
int res;
if (this->readConfFile() == -1 || this->checkConf() == -1) {
return (-1);
}
std::memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if ((res = getaddrinfo(NULL, port, &hints, &ai)) != 0) {
std::cerr << "Error : getaddrinfo() - " << gai_strerror(res) << std::endl;
return (-1);
}
for (p = ai; p != NULL; p = p->ai_next) {
server_fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (server_fd < 0) {
continue;
}
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
if (bind(server_fd, p->ai_addr, p->ai_addrlen) < 0) {
close(server_fd);
continue;
}
break;
}
freeaddrinfo(ai);
if (p == NULL) {
return (-1);
}
if (listen(server_fd, 10) == -1) {
return (-1);
}
this->server_socket = server_fd;
return this->server_socket;
}
int Server::runServer() {
this->addSocketToPoll(this->server_socket);
std::cout << "Server started" << std::endl;
while (running == true) {
int poll_count = poll(&pfds[0], pfds.size(), -1);
if (running == true && poll_count < 0) {
std::cerr << "Error: poll()" << std::endl;
return (-1);
} else if (running == true) {
if (pfds[0].revents & POLLIN) {
this->createUser();
}
this->receiveDatas();
}
}
return 0;
}
void Server::addSocketToPoll(int socket_fd) {
fcntl(socket_fd, F_SETFL, O_NONBLOCK);
this->pfds.push_back(pollfd());
this->pfds.back().fd = socket_fd;
this->pfds.back().events = POLLIN;
}
void Server::createUser() {
struct sockaddr_in client_addr;
socklen_t addr_len;
int client_fd;
char host[1024];
char service[20];
addr_len = sizeof(client_addr);
client_fd = accept(this->server_socket, (struct sockaddr *)&client_addr, &addr_len);
if (this->users.size() == MAX_USERS) {
std::string refused = "Too many users on server, your connection was refused\r\n";
irc::sendString(client_fd, refused);
// No need to close connection if error with sendString, as User is not created
// and fd is closed anyway
std::cout << "A new connection was refused because there's already too many clients" << std::endl;
close(client_fd);
return ;
}
if (getnameinfo((const sockaddr *)&client_addr, sizeof(client_addr), \
host, sizeof(host), service, sizeof(service), NI_NOFQDN) == -1) {
std::cerr << "Error: getnameinfo()" << std::endl;
close(client_fd);
return ;
}
std::string hostname(host);
this->addSocketToPoll(client_fd);
std::cout << "Accepting new connection from " << inet_ntoa(client_addr.sin_addr) << " on fd: " << client_fd << std::endl;
this->users.push_back(new User(client_fd, hostname, client_addr, this));
this->datas.push_back("");
}
void Server::deleteUser(User* user, std::string reason) {
for (std::vector<User *>::iterator it1 = this->users.begin(); \
it1 != this->users.end(); it1++) {
if ((*it1) == user) {
this->deleteUserFromChannels(user, reason);
this->deleteServOperator(user);
this->sendError(user, reason);
int position = it1 - this->users.begin();
std::vector<std::string>::iterator it2 = this->datas.begin();
std::advance(it2, position);
this->datas.erase(it2);
std::vector<pollfd>::iterator it3 = this->pfds.begin();
std::advance(it3, position + 1);
std::cout << "\nClosing connection to client fd = " << (*it3).fd << "\n" << std::endl;
close((*it3).fd);
this->pfds.erase(it3);
delete *it1;
this->users.erase(it1);
return ;
}
}
}
void Server::deleteUserFromChannels(User* user, std::string reason) {
std::vector<Channel *> chans = this->channels;
for (size_t i = 0; i < chans.size(); i++) {
if (chans[i]->userIsInChan(user) == true) {
chans[i]->deleteChanUser(user, "PART " + chans[i]->getChanName() + " :" + reason);
}
}
}
Channel* Server::createChannel(std::string name) {
srand(time(0));
if (name.find_first_of(" :,\007") != std::string::npos || name.find_first_of("#") != 0 || name.length() > 50) {
this->channels.push_back(new Channel(this, "#"));
return this->channels.back();
}
if (name[0] == '!') {
int random;
std::string name;
std::string s;
std::stringstream out;
int i;
i = 0;
while (i < 5) {
random = rand() % 10;
out << random;
s = out.str();
name.insert(0, s);
i++;
}
}
this->channels.push_back(new Channel(this, name));
return this->channels.back();
}
int Server::deleteChannel (Channel* channel) {
if (channel->getNbUsersInChan() != 0) {
return 0;
}
for (std::vector<Channel *>::iterator it1 = this->channels.begin(); \
it1 != this->channels.end(); it1++) {
if ((*it1) == channel) {
delete *it1;
this->channels.erase(it1);
return 1;
}
}
return 0;
}
void Server::deleteEmptyChannels () {
std::vector<Channel *>::iterator it = this->channels.begin();
while (it != this->channels.end()) {
if (this->deleteChannel(*it) == 1) {
it = this->channels.begin();
} else {
it++;
}
}
}
void Server::receiveDatas() {
char buf[SERV_BUF_SIZE + 1];
std::string s_buf;
for (std::vector<pollfd>::iterator it = pfds.begin() + 1; it != pfds.end(); ++it) {
if ((*it).revents & POLLIN) {
ssize_t bytes_recv = recv((*it).fd, &buf, SERV_BUF_SIZE, 0);
if (bytes_recv <= 0) {
if (bytes_recv == -1) {
std::cerr << "Error : recv()" << std::endl;
} else {
std::cout << "Client " << (*it).fd << " exited" << std::endl;
}
int position = it - this->pfds.begin();
std::vector<User *>::iterator it1 = this->users.begin();
std::advance(it1, position - 1);
this->deleteUser(*it1, "Fatal error");
break ;
} else {
buf[bytes_recv] = 0;
std::cout << "\nFrom client (fd = " << (*it).fd << "): " << buf;
s_buf = buf;
this->datasExtraction(s_buf, it - pfds.begin() - 1);
break ;
}
}
}
}
void Server::datasExtraction(std::string& buf, size_t pos) {
User *user = this->getSpecificUser(pos);
size_t nbr_us = datas.size();
datas[pos].append(buf);
size_t cmd_end = datas[pos].find("\r\n");
while (datas.size() == nbr_us && cmd_end != std::string::npos) {
std::string content = datas[pos].substr(0, cmd_end);
if (cmd_end + 2 >= datas[pos].size()) {
datas[pos].clear();
cmd_end = std::string::npos;
} else {
datas[pos].erase(0, cmd_end + 2);
cmd_end = datas[pos].find("\r\n");
}
Command* cmd = new Command(getServer(), user, content);
std::cout << "New command: " << content << std::endl;
cmd->parseCommand();
delete cmd;
}
}
// Here, user_nb is from 0 to max - 1.
User* Server::getSpecificUser(size_t user_nb) {
if (user_nb < this->users.size())
return this->users[user_nb];
return NULL;
}
Channel* Server::getChannelByName(std::string name) {
unsigned long i;
std::string curr_chan;
i = 0;
name = irc::trim(name, " ");
std::transform(name.begin(), name.end(), name.begin(), ::toupper);
while (i < channels.size())
{
curr_chan = channels[i]->getChanName();
transform(curr_chan.begin(), curr_chan.end(), curr_chan.begin(), ::toupper);
if (curr_chan == name)
return (channels[i]);
i++;
}
return (NULL);
}
User* Server::getUserByNick(std::string nick)
{
unsigned long i;
i = 0;
while (i < users.size()) {
if (users[i]->getNickname() == nick) {
return (users[i]);
}
i++;
}
return (NULL);
}
std::string Server::getPass() {
return (password);
}
std::string Server::getOpPass() {
return ((this->conf.find("op_pwd"))->second);
}
std::string Server::getVersion() {
return (this->conf.find("version")->second);
}
std::vector<User *> Server::getServOp() {
return (operators);
}
std::vector<User *> Server::getServUsers() {
return (users);
}
std::string Server::getName() {
return ((this->conf.find("name"))->second);
}
Server& Server::getServer() {
return *this;
}
std::string Server::getInfos() {
return ((this->conf.find("infos"))->second);
}
int Server::getMaxChannelbyUser() const {
return 10;
}
void Server::checkPassword(User* user, std::string parameters) {
std::vector<std::string> params;
if (user->isRegistered() == true) {
if (irc::numericReply(462, user, params) == -1) {
this->deleteUser(user, "Fatal error");
}
return ;
} else if (parameters.empty()) {
params.push_back("PASS");
irc::numericReply(461, user, params);
this->deleteUser(user, "Fatal error");
return ;
} else if (parameters.compare(this->password) != 0) {
irc::numericReply(464, user, params);
this->deleteUser(user, "Fatal error");
return ;
}
user->setStatus(NICK);
}
void Server::checkNick(User* user, std::string parameters) {
std::vector<std::string> params;
if (user->getStatus() == PASS) {
this->checkPassword(user, "");
return ;
} else if (parameters.empty()) {
if (irc::numericReply(431, user, params) == -1 || user->isRegistered() == false) {
this->deleteUser(user, "Fatal error");
}
return ;
}
params = irc::split(parameters, " ", 0);
if (this->getUserByNick(params[0]) != NULL) {
if (irc::numericReply(433, user, params) == -1 || user->isRegistered() == false) {
this->deleteUser(user, "Fatal error");
}
return ;
} else if (params[0].size() > 8 ||
(params[0].find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;[]\\`_^{}|") != std::string::npos) ||
((params[0].find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ;[]\\`_^{}|")) == 0))
{
if (irc::numericReply(432, user, params) == -1 || user->isRegistered() == false) {
this->deleteUser(user, "Fatal error");
}
return ;
}
if (user->isRegistered() == false) {
user->nick(params[0], false);
user->setStatus(USER);
} else {
user->nick(params[0], true);
}
}
void Server::checkUserCmd(User* user, std::string parameters) {
std::vector<std::string> params;
if (user->isRegistered() == true) {
if (irc::numericReply(462, user, params) == -1) {
this->deleteUser(user, "Fatal error");
}
return ;
}
params = irc::split(parameters, " ", 0);
if (params.size() < 4) {
params.clear();
params.push_back("USER");
irc::numericReply(461, user, params);
this->deleteUser(user, "Fatal error");
return ;
}
user->userCmd(params);
user->setStatus(REGISTERED);
this->welcomeUser(user);
}
void Server::welcomeUser(User *user) {
std::vector<std::string> params;
params.push_back(user->getUsername());
params.push_back(user->getHostname());
if (irc::numericReply(1, user, params) == -1) {
this->deleteUser(user, "Fatal error");
return ;
}
params.clear();
params.push_back(this->conf.find("version")->second);
if (irc::numericReply(2, user, params) == -1) {
this->deleteUser(user, "Fatal error");
return ;
}
params.clear();
params.push_back(this->conf.find("creation")->second);
if (irc::numericReply(3, user, params) == -1) {
this->deleteUser(user, "Fatal error");
return ;
}
params.clear();
params.push_back(this->conf.find("version")->second);
params.push_back("aiwro");
params.push_back("oitklbI");
if (irc::numericReply(4, user, params) == -1) {
this->deleteUser(user, "Fatal error");
return ;
}
this->getMotd(user, "");
}
void Server::listChannels (User* user) {
std::vector<std::string> params;
int visible_users;
char buff[3];
for (std::vector<Channel *>::iterator it = this->channels.begin(); it != this->channels.end(); it++) {
params.push_back((*it)->getChanName());
visible_users = (*it)->getNbUsersInChan();
sprintf(buff, "%d", visible_users);
params.push_back(buff);
params.push_back((*it)->getChanTopic());
irc::numericReply(322, user, params);
params.clear();
}
}
void Server::getMotd(User* user, std::string parameters) {
std::vector<std::string> param = irc::split(parameters, " ", 0);
std::string motd = (this->conf.find("motd"))->second;
if (!param[0].empty() && param[0].compare((this->conf.find("name"))->second)) {
if (irc::numericReply(402, user, param) == -1) {
this->deleteUser(user, "Fatal error");
}
return ;
} else if (motd.empty()) {
if (irc::numericReply(422, user, param) == -1) {
this->deleteUser(user, "Fatal error");
}
return ;
}
if (irc::numericReply(375, user, param) == -1) {
this->deleteUser(user, "Fatal error");
return ;
}
param.clear();
for (size_t i = 0; i < motd.size(); i += 80) {
param.push_back(motd.substr(i, 80));
if (irc::numericReply(372, user, param) == -1) {
this->deleteUser(user, "Fatal error");
return ;
}
param.clear();
}
if (irc::numericReply(376, user, param) == -1) {
this->deleteUser(user, "Fatal error");
}
}
void Server::retrieveTime(User* user, std::string parameters) {
std::string name = this->getName();
if (!parameters.empty() && parameters.compare(name)) {
std::vector<std::string> params;
params.push_back(name);
if (irc::numericReply(402, user, params) == -1) {
this->deleteUser(user, "Fatal error");
}
return ;
}
std::time_t time;
std::time(&time);
std::string s_time = std::asctime(std::localtime(&time));
std::vector<std::string> params;
params.push_back(name);
std::cout << "in retrieve time name: " << name << std::endl;
params.push_back(s_time);
std::cout << "in retrieve time s_time: " << s_time << std::endl;
if (irc::numericReply(391, user, params) == -1) {
this->deleteUser(user, "Fatal error");
}
return ;
}
void Server::retrieveVersion(User* user, std::string parameters) {
std::string name = this->getName();
std::vector<std::string> params;
if (!parameters.empty() && parameters.compare(name)) {
params.push_back(name);
if (irc::numericReply(402, user, params) == -1) {
this->deleteUser(user, "Fatal error");
}
return ;
}
params.push_back(this->conf.find("version")->second);
params.push_back("");
params.push_back("");
if (irc::numericReply(351, user, params) == -1) {
this->deleteUser(user, "Fatal error");
}
}
void Server::getAdmin(User* user, std::string parameters) {
std::string name = this->getName();
std::vector<std::string> params;
if (!parameters.empty() && parameters.compare(name)) {
params.push_back(name);
irc::numericReply(402, user, params);
return ;
}
irc::numericReply(256, user, params);
params.push_back(this->conf.find("adminloc1")->second);
irc::numericReply(257, user, params);
params.clear();
params.push_back(this->conf.find("adminloc2")->second);
irc::numericReply(258, user, params);
params.clear();
params.push_back(this->conf.find("adminemail")->second);
irc::numericReply(259, user, params);
}
void Server::sendError (User* user, std::string parameter) {
int fd = user->getFd();
parameter.insert(0, "ERROR :");
parameter += "\r\n";
irc::sendString(fd, parameter);
}
void Server::sendPong (User* user, std::string server_names) {
std::vector<std::string> serv;
std::vector<std::string> params;
std::string pong_msg;
int ret;
std::string name = this->conf.find("name")->second;
serv = irc::split(server_names, " ", 0);
if (serv[0].empty()) {
ret = irc::numericReply(409, user, params);
} else if (serv.size() > 1 && serv[1] != name) {
params.push_back(serv[1]);
ret = irc::numericReply(402, user, params);
} else {
pong_msg = ":" + name + " PONG " + name + " :" + serv[0] + "\r\n";
ret = irc::sendString(user->getFd(), pong_msg);
}
if (ret == -1) {
this->deleteUser(user, "Fatal error");
}
}
int Server::setServOperator(User* user) {
std::vector<User *>::iterator it = std::find(this->operators.begin(), this->operators.end(), user);
if (it == this->operators.end()) {
this->operators.push_back(user);
user->set_o(true);
}
std::vector<std::string> params;
if (irc::numericReply(381, user, params) == -1) {
return (-1);
}
return 0;
}
void Server::deleteServOperator(User* user) {
std::vector<User *>::iterator it = std::find(this->operators.begin(), this->operators.end(), user);
if (it != operators.end()) {
this->operators.erase(it);
}
}
bool Server::isServOperator(User *user) {
std::vector<User *>::iterator it = std::find(this->operators.begin(), this->operators.end(), user);
if (it != operators.end()) {
return true;
}
return false;
}
void Server::sendWallops(std::string msg) {
std::string pref_msg = ":" + this->getName();
std::vector<User *>::iterator it = this->users.begin();
while (it != this->users.end())
{
std::string full_msg = pref_msg + " NOTICE " +(*it)->getNickname() + " :" + msg + "\r\n";
if ((*it)->get_w()) {
irc::sendString((*it)->getFd(), full_msg);
}
it++;
}
}