passokjoin

This commit is contained in:
Ladebeze66 2024-05-13 19:20:49 +02:00
parent 070f446102
commit 58606f36a6
16 changed files with 264 additions and 226 deletions

98
.vscode/settings.json vendored
View File

@ -57,53 +57,53 @@
"C_Cpp_Runner.useLinkTimeOptimization": false, "C_Cpp_Runner.useLinkTimeOptimization": false,
"C_Cpp_Runner.msvcSecureNoWarnings": false, "C_Cpp_Runner.msvcSecureNoWarnings": false,
"files.associations": { "files.associations": {
"array": "cpp", "array": "cpp",
"atomic": "cpp", "atomic": "cpp",
"bit": "cpp", "bit": "cpp",
"*.tcc": "cpp", "*.tcc": "cpp",
"cctype": "cpp", "cctype": "cpp",
"clocale": "cpp", "clocale": "cpp",
"cmath": "cpp", "cmath": "cpp",
"compare": "cpp", "compare": "cpp",
"concepts": "cpp", "concepts": "cpp",
"cstdarg": "cpp", "cstdarg": "cpp",
"cstddef": "cpp", "cstddef": "cpp",
"cstdint": "cpp", "cstdint": "cpp",
"cstdio": "cpp", "cstdio": "cpp",
"cstdlib": "cpp", "cstdlib": "cpp",
"cstring": "cpp", "cstring": "cpp",
"cwchar": "cpp", "cwchar": "cpp",
"cwctype": "cpp", "cwctype": "cpp",
"deque": "cpp", "deque": "cpp",
"string": "cpp", "string": "cpp",
"unordered_map": "cpp", "unordered_map": "cpp",
"vector": "cpp", "vector": "cpp",
"exception": "cpp", "exception": "cpp",
"algorithm": "cpp", "algorithm": "cpp",
"functional": "cpp", "functional": "cpp",
"iterator": "cpp", "iterator": "cpp",
"memory": "cpp", "memory": "cpp",
"memory_resource": "cpp", "memory_resource": "cpp",
"numeric": "cpp", "numeric": "cpp",
"random": "cpp", "random": "cpp",
"string_view": "cpp", "string_view": "cpp",
"system_error": "cpp", "system_error": "cpp",
"tuple": "cpp", "tuple": "cpp",
"type_traits": "cpp", "type_traits": "cpp",
"utility": "cpp", "utility": "cpp",
"initializer_list": "cpp", "initializer_list": "cpp",
"iosfwd": "cpp", "iosfwd": "cpp",
"iostream": "cpp", "iostream": "cpp",
"istream": "cpp", "istream": "cpp",
"limits": "cpp", "limits": "cpp",
"new": "cpp", "new": "cpp",
"numbers": "cpp", "numbers": "cpp",
"ostream": "cpp", "ostream": "cpp",
"sstream": "cpp", "sstream": "cpp",
"stdexcept": "cpp", "stdexcept": "cpp",
"streambuf": "cpp", "streambuf": "cpp",
"typeinfo": "cpp", "typeinfo": "cpp",
"ctime": "cpp", "ctime": "cpp",
"map": "cpp" "map": "cpp"
} }
} }

View File

@ -6,7 +6,7 @@
# By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ # # By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ # # +#+#+#+#+#+ +#+ #
# Created: 2024/05/09 13:54:36 by fgras-ca #+# #+# # # Created: 2024/05/09 13:54:36 by fgras-ca #+# #+# #
# Updated: 2024/05/09 13:54:48 by fgras-ca ### ########.fr # # Updated: 2024/05/12 18:19:36 by fgras-ca ### ########.fr #
# # # #
# **************************************************************************** # # **************************************************************************** #
@ -36,7 +36,7 @@ $(NAME): $(OBJECTS)
# Compilation des fichiers source en fichiers objet # Compilation des fichiers source en fichiers objet
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
@mkdir -p $(OBJ_DIR) @mkdir -p $(OBJ_DIR)
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@ $(CXX) $(CPPFLAGS) $(CXXFLAGS) -g -c $< -o $@
# Commande pour nettoyer le projet (supprimer les fichiers objet et l'exécutable) # Commande pour nettoyer le projet (supprimer les fichiers objet et l'exécutable)
clean: clean:

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -6,7 +6,7 @@
/* By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ */ /* By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/05/09 14:07:00 by fgras-ca #+# #+# */ /* Created: 2024/05/09 14:07:00 by fgras-ca #+# #+# */
/* Updated: 2024/05/11 19:14:26 by fgras-ca ### ########.fr */ /* Updated: 2024/05/13 17:48:53 by fgras-ca ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */

View File

@ -6,21 +6,27 @@
/* By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ */ /* By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/05/09 14:19:30 by fgras-ca #+# #+# */ /* Created: 2024/05/09 14:19:30 by fgras-ca #+# #+# */
/* Updated: 2024/05/12 17:09:20 by fgras-ca ### ########.fr */ /* Updated: 2024/05/12 17:48:14 by fgras-ca ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
#ifndef COMMANDHANDLER_HPP #ifndef COMMANDHANDLER_HPP
#define COMMANDHANDLER_HPP #define COMMANDHANDLER_HPP
#include "Client.hpp" #include <iostream>
#include "Channel.hpp" #include <sstream>
#include "Utilities.hpp" #include <algorithm>
#include <iterator>
#include <map> #include <map>
#include <string> #include <string>
#include <sstream> #include <sstream>
#include <iterator> #include <iterator>
#include "Client.hpp"
#include "Channel.hpp"
#include "Utilities.hpp"
class Client; class Client;
class Channel; class Channel;

View File

@ -6,7 +6,7 @@
/* By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ */ /* By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/05/09 14:01:12 by fgras-ca #+# #+# */ /* Created: 2024/05/09 14:01:12 by fgras-ca #+# #+# */
/* Updated: 2024/05/12 17:14:30 by fgras-ca ### ########.fr */ /* Updated: 2024/05/13 19:00:18 by fgras-ca ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -27,6 +27,9 @@
#include <netinet/in.h> #include <netinet/in.h>
#include <arpa/inet.h> #include <arpa/inet.h>
#include <algorithm> #include <algorithm>
#include <fcntl.h> // Include this for fcntl and O_NONBLOCK
#include <sys/epoll.h>
#include "color.hpp" #include "color.hpp"
#include "Client.hpp" #include "Client.hpp"
@ -51,6 +54,8 @@ private:
bool running; // État d'exécution du serveur bool running; // État d'exécution du serveur
int listener; // Socket d'écoute du serveur int listener; // Socket d'écoute du serveur
int fdmax; int fdmax;
int epoll_fd; // Descripteur pour l'instance epoll
static const int MAX_EVENTS = 10; // Nombre maximal d'événements traités à chaque appel à epoll_wait
fd_set master_set; // Ensemble principal des descripteurs de fichiers pour select fd_set master_set; // Ensemble principal des descripteurs de fichiers pour select
std::map<int, Client*> clients; // Mapping de socket à Client std::map<int, Client*> clients; // Mapping de socket à Client
std::map<int, CommandHandler*> handlers; // CommandHandler pour chaque client std::map<int, CommandHandler*> handlers; // CommandHandler pour chaque client
@ -60,6 +65,8 @@ private:
bool getlineFromClient(Client* client, std::string& line); bool getlineFromClient(Client* client, std::string& line);
void handleIRCMessages(Client* client, CommandHandler& cmdHandler); void handleIRCMessages(Client* client, CommandHandler& cmdHandler);
bool processInitialCommands(Client* client); bool processInitialCommands(Client* client);
void handleNickAndUserCommands(const std::string& line, size_t passEnd, Client* client);
void setNonBlocking(int sockfd);
}; };
#endif // SERVER_HPP #endif // SERVER_HPP

Binary file not shown.

View File

@ -6,7 +6,7 @@
/* By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ */ /* By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/05/09 14:08:13 by fgras-ca #+# #+# */ /* Created: 2024/05/09 14:08:13 by fgras-ca #+# #+# */
/* Updated: 2024/05/09 14:38:23 by fgras-ca ### ########.fr */ /* Updated: 2024/05/12 17:56:26 by fgras-ca ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -16,17 +16,20 @@
Channel::Channel(const std::string& name) : name(name) {} Channel::Channel(const std::string& name) : name(name) {}
void Channel::addClient(Client* client) { void Channel::addClient(Client* client) {
std::cout << "Adding client to channel " << name << std::endl;
clients.push_back(client); clients.push_back(client);
std::cout << "Client added. Total clients: " << clients.size() << std::endl;
} }
void Channel::removeClient(Client* client) { void Channel::removeClient(Client* client) {
clients.erase(std::remove(clients.begin(), clients.end(), client), clients.end()); clients.erase(std::remove(clients.begin(), clients.end(), client), clients.end());
} }
void Channel::broadcastMessage(const std::string& message, Client* sender) { void Channel::broadcastMessage(const std::string& message, Client* sender) {
for (std::vector<Client*>::iterator it = clients.begin(); it != clients.end(); ++it) { std::cout << "Broadcasting message in channel " << name << " from " << sender->getNickname() << std::endl;
if (*it != sender) { // Ensure we don't send the message back to the sender for (size_t i = 0; i < clients.size(); ++i) {
(*it)->sendMessage(message); if (clients[i] != sender) {
std::cout << "Sending message to " << clients[i]->getNickname() << std::endl;
clients[i]->sendMessage(message);
} }
} }
} }

View File

@ -6,7 +6,7 @@
/* By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ */ /* By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/05/09 14:07:27 by fgras-ca #+# #+# */ /* Created: 2024/05/09 14:07:27 by fgras-ca #+# #+# */
/* Updated: 2024/05/11 16:11:10 by fgras-ca ### ########.fr */ /* Updated: 2024/05/13 16:59:32 by fgras-ca ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -33,15 +33,16 @@ std::string Client::receiveMessage() {
std::memset(buffer, 0, sizeof(buffer)); std::memset(buffer, 0, sizeof(buffer));
int len = recv(socket, buffer, sizeof(buffer) - 1, 0); int len = recv(socket, buffer, sizeof(buffer) - 1, 0);
if (len > 0) { if (len > 0) {
buffer[len] = '\0'; // Ensure null termination buffer[len] = '\0';
std::string received(buffer); std::string received(buffer);
// Erase newline and carriage return characters received.erase(std::remove(received.begin(), received.end(), '\r'), received.end());
size_t pos; received.erase(std::remove(received.begin(), received.end(), '\n'), received.end());
while ((pos = received.find_first_of("\r\n")) != std::string::npos) {
received.erase(pos, 1);
}
std::cout << "Received message: [" << received << "]" << std::endl; std::cout << "Received message: [" << received << "]" << std::endl;
return received; return received;
} else if (len == 0) {
std::cout << "Connection closed by the peer." << std::endl;
} else {
std::cerr << "recv error: " << strerror(errno) << std::endl;
} }
return ""; return "";
} }

View File

@ -6,7 +6,7 @@
/* By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ */ /* By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/05/09 14:19:15 by fgras-ca #+# #+# */ /* Created: 2024/05/09 14:19:15 by fgras-ca #+# #+# */
/* Updated: 2024/05/12 17:11:00 by fgras-ca ### ########.fr */ /* Updated: 2024/05/12 18:07:48 by fgras-ca ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -14,60 +14,64 @@
CommandHandler::CommandHandler() {} CommandHandler::CommandHandler() {}
CommandHandler::~CommandHandler() CommandHandler::~CommandHandler() {
{ for (std::map<std::string, Channel*>::iterator it = channels.begin(); it != channels.end(); ++it) {
for (std::map<std::string, Channel*>::iterator it = channels.begin(); it != channels.end(); ++it)
{
delete it->second; delete it->second;
} }
channels.clear(); channels.clear();
} }
void CommandHandler::handleCommand(const std::string& commandLine, Client* client) void CommandHandler::handleCommand(const std::string& commandLine, Client* client) {
{
std::istringstream stream(commandLine); std::istringstream stream(commandLine);
std::string command; std::string command;
stream >> command; stream >> command;
if (command == "JOIN") { if (command == "JOIN") {
std::cout << "Commande Join reconnue" << std::endl;
handleJoin(commandLine, client); handleJoin(commandLine, client);
} else if (command == "PART") { } else if (command == "PART") {
std::cout << "Commande part reconnue" << std::endl;
handlePart(commandLine, client); handlePart(commandLine, client);
} else if (command == "NICK") { } else if (command == "NICK") {
std::cout << "Commande nick reconnue" << std::endl;
handleNick(commandLine, client); handleNick(commandLine, client);
} else if (command == "PRIVMSG") { } else if (command == "PRIVMSG") {
std::cout << "Commande privmsg reconnue" << std::endl;
handlePrivmsg(commandLine, client); handlePrivmsg(commandLine, client);
} /*else if (command == "QUIT") { }
std::cout << "Commande quit reconnue" << std::endl;
handleQuit(client);
}*/
// Ajoutez d'autres commandes IRC ici
} }
void CommandHandler::handleJoin(const std::string& command, Client* client) { void CommandHandler::handleJoin(const std::string& command, Client* client) {
std::cout << "Lancement fonction Join reconnue" << std::endl; std::cout << "Entering handleJoin with command: " << command << std::endl;
std::vector<std::string> tokens = split(command, ' '); std::vector<std::string> tokens = split(command, ' ');
if (tokens.size() > 1) { if (tokens.size() > 1) {
std::string channelName = tokens[1]; std::string channelName = tokens[1];
if (channels.find(channelName) == channels.end()) {
// Log before accessing the map
std::cout << "Checking if channel exists: " << channelName << std::endl;
// Check if channel exists
std::map<std::string, Channel*>::iterator it = channels.find(channelName);
if (it == channels.end()) {
// If not, create a new channel
std::cout << "Creating new channel: " << channelName << std::endl;
channels[channelName] = new Channel(channelName); channels[channelName] = new Channel(channelName);
} else {
std::cout << "Channel already exists: " << channelName << std::endl;
} }
// Add client to channel and send join message
channels[channelName]->addClient(client); channels[channelName]->addClient(client);
channels[channelName]->broadcastMessage("JOIN " + channelName, client); channels[channelName]->broadcastMessage("JOIN " + channelName, client);
} else {
std::cerr << "Invalid JOIN command format." << std::endl;
} }
} }
void CommandHandler::handlePart(const std::string& command, Client* client) { void CommandHandler::handlePart(const std::string& command, Client* client) {
std::vector<std::string> tokens = split(command, ' '); std::vector<std::string> tokens = split(command, ' ');
if (tokens.size() > 1) { if (tokens.size() > 1) {
std::string channelName = tokens[1]; std::string channelName = tokens[1];
if (channels.find(channelName) != channels.end()) { if (channels.find(channelName) != channels.end()) {
channels[channelName]->removeClient(client); channels[channelName]->removeClient(client);
channels[channelName]->broadcastMessage("PART " + channelName, client);
} }
} }
} }
@ -76,34 +80,26 @@ void CommandHandler::handleNick(const std::string& command, Client* client) {
std::vector<std::string> tokens = split(command, ' '); std::vector<std::string> tokens = split(command, ' ');
if (tokens.size() > 1) { if (tokens.size() > 1) {
client->setNickname(tokens[1]); client->setNickname(tokens[1]);
std::cout << "Nickname set to: " << tokens[1] << std::endl; // Afficher et enregistrer l'action
} }
} }
void CommandHandler::handlePrivmsg(const std::string& command, Client* client) { void CommandHandler::handlePrivmsg(const std::string& command, Client* client) {
std::vector<std::string> tokens = split(command, ' '); std::vector<std::string> tokens = split(command, ' ');
if (tokens.size() > 2) { if (tokens.size() > 2) {
std::string target = tokens[1]; std::string target = tokens[1];
std::string message = command.substr(command.find(" :") + 2); std::string message = command.substr(command.find(':') + 1);
if (channels.find(target) != channels.end()) { if (channels.find(target) != channels.end()) {
channels[target]->broadcastMessage("PRIVMSG " + message, client); channels[target]->broadcastMessage("PRIVMSG " + target + " :" + message, client);
} }
} }
} }
/*void CommandHandler::handleQuit(Client* client) {
for (std::map<std::string, Channel*>::iterator it = channels.begin(); it != channels.end(); ++it) {
it->second->removeClient(client);
}
}*/
std::vector<std::string> CommandHandler::split(const std::string& s, char delimiter) { std::vector<std::string> CommandHandler::split(const std::string& s, char delimiter) {
std::vector<std::string> tokens; std::vector<std::string> tokens;
std::stringstream ss(s); std::string token;
std::string item; std::istringstream tokenStream(s);
while (getline(ss, item, delimiter)) { while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(item); tokens.push_back(token);
} }
return tokens; return tokens;
} }

View File

@ -6,7 +6,7 @@
/* By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ */ /* By: fgras-ca <fgras-ca@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/05/09 14:01:34 by fgras-ca #+# #+# */ /* Created: 2024/05/09 14:01:34 by fgras-ca #+# #+# */
/* Updated: 2024/05/12 17:07:02 by fgras-ca ### ########.fr */ /* Updated: 2024/05/13 19:19:46 by fgras-ca ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -79,96 +79,99 @@ bool Server::initialize()
return true; return true;
} }
bool Server::getlineFromClient(Client* client, std::string& line) bool Server::getlineFromClient(Client* client, std::string& line) {
{ char buffer[1024];
char buffer[1024]; while (true) {
memset(buffer, 0, sizeof(buffer)); memset(buffer, 0, sizeof(buffer));
int len = recv(client->getSocket(), buffer, sizeof(buffer) - 1, 0); int len = recv(client->getSocket(), buffer, sizeof(buffer) - 1, 0);
if (len > 0) if (len > 0) {
{ buffer[len] = '\0';
buffer[len] = '\0'; // Ensure null termination line = std::string(buffer);
line = std::string(buffer); line.erase(std::remove(line.begin(), line.end(), '\r'), line.end());
line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); line.erase(std::remove(line.begin(), line.end(), '\n'), line.end());
line.erase(std::remove(line.begin(), line.end(), '\n'), line.end()); std::cout << GREEN << "Received line: " << line << RESET << std::endl;
return true; return true;
} } else if (len == 0) {
else if (len == 0) std::cout << RED << "Client disconnected." << RESET << std::endl;
{ return false;
std::cout << RED << "Client disconnected." << RESET << std::endl; } else {
return false; // Connection is closed if (errno == EWOULDBLOCK || errno == EAGAIN) {
} // Si non-bloquant et aucune donnée n'est disponible, attendez un peu et réessayez
else std::cout << YELLOW << "No data available yet, non-blocking mode." << RESET << std::endl;
{ usleep(100000); // attendre 100 ms
std::cerr << RED << "Error reading from client socket: " << strerror(errno) << RESET << std::endl; continue; // Continuez à essayer de lire
return false; // An error occurred } else {
} std::cerr << RED << "Error reading from client socket: " << strerror(errno) << RESET << std::endl;
return false;
}
}
}
} }
bool Server::processInitialCommands(Client* client)
{
std::string line;
bool isAuthenticated = false; // Pour garder une trace de l'authentification
while (getlineFromClient(client, line) && !line.empty())
{
std::cout << MAGENTA << "Processing line: " << RESET << line << std::endl;
// Extraction et traitement de la commande PASS
size_t passEnd = line.find("NICK");
if (passEnd != std::string::npos)
{
std::string passCommand = line.substr(0, passEnd);
std::istringstream passIss(passCommand);
std::string passToken, extractedPassword;
passIss >> passToken >> extractedPassword;
if (extractedPassword != this->password)
{
client->sendMessage("ERROR :Wrong password\r\n");
std::cout << RED << "Authentication failed for password: " << RESET << extractedPassword << std::endl;
return false;
}
else
{
std::cout << "CLIENT Socket: " << client->getSocket() << GREEN << " :Authentication successful." << RESET << std::endl;
isAuthenticated = true;
}
}
// Traitement des commandes NICK et USER
if (isAuthenticated) bool Server::processInitialCommands(Client* client) {
{ // Seulement si authentifié std::string line;
size_t nickEnd = line.find("USER"); bool isAuthenticated = false;
if (nickEnd != std::string::npos)
{ if (!getlineFromClient(client, line) || line.empty()) {
std::string nickCommand = line.substr(passEnd, nickEnd - passEnd); std::cout << RED << "No initial commands received or connection lost." << RESET << std::endl;
std::istringstream nickIss(nickCommand); return false;
std::string nickToken, nickname; }
nickIss >> nickToken >> nickname;
client->setNickname(nickname); std::cout << MAGENTA << "Processing initial line: " << RESET << line << std::endl;
std::cout << BLUE << "NickName SET: " << RESET << nickname << std::endl;
std::string userCommand = line.substr(nickEnd); // Extrait les parties nécessaires de la ligne
std::istringstream userIss(userCommand); size_t passIndex = line.find("PASS");
std::string userToken, username, realname; size_t nickIndex = line.find("NICK");
userIss >> userToken >> username; size_t userIndex = line.find("USER");
size_t realnameStart = userCommand.find(":");
if (realnameStart != std::string::npos) if (passIndex == std::string::npos || nickIndex == std::string::npos || userIndex == std::string::npos) {
{ std::cerr << "Command format error." << std::endl;
realname = userCommand.substr(realnameStart + 1); return false;
client->setUsername(username); }
client->setRealname(realname);
std::cout << GREEN << "CLIENT: " << "SET NickName: " << nickname << "; UserName: " << username << "; Socket: " << client->getSocket() << RESET << std::endl; // Extraction des données
break; std::string password = line.substr(passIndex + 4, nickIndex - (passIndex + 4));
} std::string nickname = line.substr(nickIndex + 4, userIndex - (nickIndex + 4));
} std::string userAndRealName = line.substr(userIndex + 4); // Contient le username et le realname
} size_t spaceIndex = userAndRealName.find(' ');
} std::string username = userAndRealName.substr(0, spaceIndex);
// Après une authentification réussie, passez à la gestion des messages IRC std::string realname = userAndRealName.substr(spaceIndex + 1);
if (isAuthenticated)
{ // Retire les espaces potentiels autour des informations
handleIRCMessages(client, *new CommandHandler()); // Attention à la gestion de la mémoire ici password.erase(remove(password.begin(), password.end(), ' '), password.end());
} nickname.erase(remove(nickname.begin(), nickname.end(), ' '), nickname.end());
return isAuthenticated; username.erase(remove(username.begin(), username.end(), ' '), username.end());
// Validation du mot de passe
if (password != this->password) {
client->sendMessage("ERROR :Wrong password\r\n");
std::cout << RED << "Authentication failed for password: " << password << RESET << std::endl;
return false;
}
// Set up client details if password is correct
client->setNickname(nickname);
client->setUsername(username);
client->setRealname(realname);
isAuthenticated = true;
std::cout << GREEN << "Authentication successful, client setup complete." << RESET << std::endl;
std::cout << GREEN << "Client details - Nickname: " << nickname << ", Username: " << username << ", Realname: " << realname << RESET << std::endl;
// Proceed to handle IRC messages if authenticated
if (isAuthenticated) {
handleIRCMessages(client, *new CommandHandler());
}
return isAuthenticated;
} }
// Handle IRC commands // Handle IRC commands
void Server::handleIRCMessages(Client* client, CommandHandler& cmdHandler) void Server::handleIRCMessages(Client* client, CommandHandler& cmdHandler)
{ {
@ -243,53 +246,75 @@ void Server::run()
} }
} }
void Server::acceptNewClient() void Server::acceptNewClient() {
{ struct sockaddr_in client_addr;
struct sockaddr_in client_addr; socklen_t addrlen = sizeof(client_addr);
socklen_t addrlen = sizeof(client_addr); std::cout << CYAN << "Prêt à accepter une nouvelle connexion..." << RESET << std::endl;
std::cout << CYAN << "Ready to accept new connection..." << RESET << std::endl; int newfd = accept(listener, (struct sockaddr *)&client_addr, &addrlen);
int newfd = accept(listener, (struct sockaddr *)&client_addr, &addrlen);
if (newfd == -1) if (newfd == -1) {
{ perror("Échec de l'acceptation");
perror("Accept failed"); return;
return; }
}
clients[newfd] = new Client(newfd); int flags = fcntl(newfd, F_GETFL, 0);
FD_SET(newfd, &master_set); if (flags == -1) flags = 0;
if (newfd > fdmax) fcntl(newfd, F_SETFL, flags | O_NONBLOCK);
{
fdmax = newfd;
}
std::cout << GREEN << "Accepted new client: " << inet_ntoa(client_addr.sin_addr) << " on fd: " << newfd << RESET << std::endl; Client* newClient = new Client(newfd);
if (!newClient) {
std::cerr << RED << "Échec de la création d'une nouvelle instance Client." << RESET << std::endl;
close(newfd);
return;
}
CommandHandler* newHandler = new CommandHandler();
if (!newHandler) {
std::cerr << RED << "Échec de la création d'une nouvelle instance de CommandHandler." << RESET << std::endl;
delete newClient;
close(newfd);
return;
}
clients[newfd] = newClient;
handlers[newfd] = newHandler;
FD_SET(newfd, &master_set);
if (newfd > fdmax) {
fdmax = newfd;
}
std::cout << GREEN << "Nouveau client accepté: " << inet_ntoa(client_addr.sin_addr) << " sur fd: " << newfd << RESET << std::endl;
if (!processInitialCommands(newClient)) {
std::cerr << "Échec du traitement des commandes initiales, fermeture de la connexion." << std::endl;
closeClient(newfd);
}
} }
bool Server::handleClientActivity(int sockfd)
{
Client* client = clients[sockfd];
if (!client)
{
std::cerr << RED << "Client not found for socket " << RESET << sockfd << std::endl;
return false;
}
std::string line;
if (getlineFromClient(client, line) && !line.empty())
{ bool Server::handleClientActivity(int sockfd) {
std::cout << GREEN << "Received message: [" << line << "]" << RESET << std::endl; Client* client = clients[sockfd];
CommandHandler* cmdHandler = handlers[sockfd]; CommandHandler* cmdHandler = handlers[sockfd]; // Assurez-vous que cmdHandler est récupéré correctement
cmdHandler->handleCommand(line, client);
return true; if (!client || !cmdHandler) {
} std::cerr << RED << "Client or CommandHandler not found for socket " << RESET << sockfd << std::endl;
else return false;
{ }
std::cerr << RED << "Client disconnected or error on socket: " << RESET << sockfd << std::endl;
return false; std::string line;
} if (getlineFromClient(client, line) && !line.empty()) {
std::cout << GREEN << "Received message: [" << line << "]" << RESET << std::endl;
cmdHandler->handleCommand(line, client);
return true;
} else {
std::cerr << RED << "Client disconnected or error on socket: " << RESET << sockfd << std::endl;
return false;
}
} }
void Server::closeClient(int sockfd) void Server::closeClient(int sockfd)
{ {
std::map<int, Client*>::iterator it = clients.find(sockfd); std::map<int, Client*>::iterator it = clients.find(sockfd);