diff --git a/Additional/Helper_projects/Gorkem_Ahmet/.gitignore b/Additional/Helper_projects/Gorkem_Ahmet/.gitignore deleted file mode 100644 index 3d61984..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.DS_Store -.vscode -*.o \ No newline at end of file diff --git a/Additional/Helper_projects/Gorkem_Ahmet/Makefile b/Additional/Helper_projects/Gorkem_Ahmet/Makefile deleted file mode 100644 index 1556046..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/Makefile +++ /dev/null @@ -1,230 +0,0 @@ -# **************************************************************************** # -# # -# ::: :::::::: # -# Makefile :+: :+: :+: # -# +:+ +:+ +:+ # -# By: gsever you need change with your customize. !!!!!!! -NAME = ircserv -NAME_BOT = ircbot - -# Flags for compile -CC = c++ -FLAGS = -Wall -Werror -Wextra -std=c++98 -Wshadow -O3 \ - $(INCLUDE_FLAGS) $(LIBRARIES) - -# All process use for compiling. -UNAME := $(shell uname -s) -NUMPROC := 8 - -OS := NULL - -# Checking if Brew is installed. -# IF_BREW_INSTALLED := $(shell which brew) -# Checking if Irssi is installed inside Brew. -# IF_IRSSI_INSTALLED := $(shell brew list --versions irssi) -# These 'brew --prefix' command returning brew's installed location. -BREW_PREFIX := $(shell brew --prefix) - -OPENSSL_INC_OS := $(BREW_PREFIX)/Cellar/openssl/*/include -OPENSSL_LIB_OS := $(BREW_PREFIX)/Cellar/openssl/*/lib - -INCLUDE_FLAGS = \ - -I$(HEADERS_DIRECTORY) \ - -I$(HEADERS_DIRECTORY_BOT) \ - # -I$(OPENSSL_INC_OS) - -# Locations Part --> OK -LIBRARIES = \ - # -L$(OPENSSL_LIB_OS) - -# Getting all include and library files. -# BREW_INC_OS := $(shell find $(BREW_PREFIX)/Cellar -type d -name include) -# BREW_LIB_OS := $(shell find $(BREW_PREFIX)/Cellar -type d -name lib) -# Brew's all include and library files. -# BREW_INCLUDE_FLAGS := $(addprefix -I,$(BREW_INC_OS)) -# BREW_LIBRARY_FLAGS := $(addprefix -L,$(BREW_LIB_OS)) - -HEADERS_DIRECTORY = includes -HEADERS = $(wildcard $(HEADERS_DIRECTORY)/*.hpp) - -SOURCES_DIRECTORY = sources -SOURCES = $(wildcard $(SOURCES_DIRECTORY)/*.cpp) # All sources files. -COMMANDS_DIRECTORY = sources/commands -SOURCES += $(wildcard $(COMMANDS_DIRECTORY)/*.cpp) # All sources/commands files. - -HEADERS_DIRECTORY_BOT = includes/bot -BOT_HEADERS = $(wildcard $(HEADERS_DIRECTORY_BOT)/*.hpp) -BOT_DIRECTORY = sources/bot -SOURCES_BOT = $(wildcard $(BOT_DIRECTORY)/*.cpp) # All Bot's file. - -OBJECTS_DIRECTORY = objects -OBJECTS = $(addprefix $(OBJECTS_DIRECTORY)/, $(notdir $(SOURCES:%.cpp=%.o))) -OBJECTS_DIRECTORY_BOT = objects/bot -OBJECTS_BOT += $(addprefix $(OBJECTS_DIRECTORY_BOT)/, $(notdir $(SOURCES_BOT:%.cpp=%.o))) - -# BOT_SRC = $(foreach FILE, $(BOT), $(shell find $(SOURCES_DIR) -name $(FILE))) - -vpath %.cpp $(SOURCES_DIRECTORY):$(COMMANDS_DIRECTORY) # Getting this locations's *.cpp files. -# vpath %.cpp $(BOT_DIRECTORY) # Getting this BOT location's *.cpp files. - -# COLORS --> 🟥 🟩 🟦 -BLACK = \033[0;30m -RED = \033[0;31m -GREEN = \033[0;32m -YELLOW = \033[0;33m -BLUE = \033[0;34m -PURPLE = \033[0;35m -CYAN = \033[0;36m -WHITE = \033[0;37m -END = \033[m -RESET = \033[0m -X = \033[m - -# COLORS BOLD--> B🟥 B🟩 B🟦 -B_CYAN = \033[1;36m -B_BLUE = \033[1;34m -B_YELLOW = \033[1;33m -B_GREEN = \033[1;32m -B_RED = \033[1;31m -B_RESET = \033[1m -#NOTE: \033[ ile derlenince calisiyor \e[ ile derlenince bozuk calisiyor. - -# Compiling with all threads. -ifeq ($(UNAME), Linux) - NUMPROC := $(shell grep -c ^processor /proc/cpuinfo) - OS = "You are connected from -$(CYAN)$(UNAME)$(X)- 🐧 Welcome -$(CYAN)$(USER)$(X)- 😄!" -else ifeq ($(UNAME), Darwin) - NUMPROC := $(shell sysctl -n hw.ncpu) - OS = "You are connected from 42 school's iMac 🖥 ! Welcome $(CYAN)$(USER)$(X)" - ifeq ($(USER), yuandre) - OS = "You are connected from -$(CYAN)MacBook$(X)- 💻 Welcome -$(CYAN)$(USER)$(X)-!" - endif -endif -# You can use --> man sysctl -> shell: sysctl -a | grep "hw.ncpu" - -all: - @$(MAKE) $(NAME) -j $(NUMPROC) --no-print-directory -# @$(MAKE) -s $(NAME) -j $(NUMPROC) - -bonus: - @$(MAKE) $(NAME_BOT) -j $(NUMPROC) --no-print-directory - -# Compiling -# $(OBJECTS_DIRECTORY)/%.o: $(SOURCES_DIRECTORY)/%.cpp | $(OBJECTS_DIRECTORY) -$(OBJECTS_DIRECTORY)/%.o: %.cpp | $(OBJECTS_DIRECTORY) - @$(CC) $(FLAGS) -c $< -o $@ - @printf "%-57b %b" "$(BLUE)COMPILED $(CYAN)$@" "$(GREEN)[✓]$(X)\n" -# NOTE: $@ -> First $() -# NOTE: $< -> Second $() - -$(NAME): $(OBJECTS_DIRECTORY) $(OBJECTS) - @$(CC) $(FLAGS) $(OBJECTS) -o $(NAME) - @printf "%-50b %b" "$(GREEN)CREATED $@" "[FINISHED]$(X)\n" - @echo $(OS) Compiled with $(NUMPROC) cores! - -# $(NAME_BOT): $(OBJECTS_DIRECTORY) $(BOT_DIRECTORY)/*.cpp -# @$(CC) $(FLAGS) $(BOT_DIRECTORY)/*.cpp -o $(NAME_BOT) -$(NAME_BOT): $(OBJECTS_DIRECTORY_BOT) $(OBJECTS_BOT) - @$(CC) $(FLAGS) $(OBJECTS_BOT) -o $(NAME_BOT) - @printf "%-50b %b" "$(GREEN)CREATED $@" "[FINISHED]$(X)\n" - @echo $(OS) Compiled with $(NUMPROC) cores! - -# Objects file creating -$(OBJECTS_DIRECTORY): - @if [ ! -d $@ ]; then \ - mkdir -p $@; \ - echo "$(NAME): $(GREEN)$@ folder was created$(RESET)"; \ - fi -# NOTE: $@ -> @(OBJECTS_DIRECTORY) -# @mkdir -p $(OBJECTS_DIRECTORY); -# @echo "$(NAME): $(GREEN)$(OBJECTS_DIRECTORY) was created$(RESET)"; - -# Objects file creating -$(OBJECTS_DIRECTORY_BOT): - @if [ ! -d $@ ]; then \ - mkdir -p $@; \ - echo "$(NAME): $(GREEN)$@ folder was created$(RESET)"; \ - fi - -clean: - @rm -rf $(OBJECTS_DIRECTORY) - @echo "$(NAME): $(RED)$(OBJECTS) was deleted$(RESET)" - -fclean: clean - @rm -f $(NAME) - @rm -f $(NAME_BOT) - @echo "$(NAME): $(RED)$(NAME) was deleted$(RESET)" - @echo "$(NAME): $(RED)$(NAME_BOT) was deleted$(RESET)" - -re: - @$(MAKE) fclean --no-print-directory - @$(MAKE) all --no-print-directory - -print: - @echo "$(BREW_PREFIX) burada." - @echo "$(BREW_INC_OS) inc burada." - @echo "$(BREW_LIB_OS) inc burada." - @echo "$(FLAGS)" - @grep -q '$(BREW_PREFIX)' ~/.zshrc && echo "Var" || echo "Yok" - -open: - @echo "$(BREW_PREFIX)" - $(BREW_PREFIX)/bin/irssi - -# Checking if brew(For install irssi) and irssi(IRC Client) is installed. -# install_brew: -# ifeq ($(IF_BREW_INSTALLED), ) -# @echo "$(B_BLUE)Brew is not installed, installing 'Brew'...$(RESET)" -# @mkdir -p /goinfre/brew -# @git clone --depth=1 https://github.com/Homebrew/brew /goinfre/brew -# @if ! grep -q '$(BREW_PREFIX)/bin' $(HOME)/.zshrc; then \ -# @echo 'export PATH=/goinfre/$(USER)/brew/bin:$(PATH)' >> $(HOME)/.zshrc; \ -# @fi -# @echo "$(B_GREEN)Brew installed inside '$(BREW_PREFIX)'.$(RESET)" -# else -# @echo "$(B_YELLOW)Brew is already installed at '$(BREW_PREFIX)'.$(RESET)" -# endif -# ifeq ($(IF_IRSSI_INSTALLED), ) -# @echo "$(B_BLUE)Brew is not installed, installing 'Irssi'.$(RESET)" -# brew install irssi -# @echo "$(B_GREEN)Irssi is installed inside '$(shell which irssi)'.$(RESET)" -# else -# @echo "$(B_YELLOW)Irssi is already installed at '$(shell which irssi)'.$(RESET)" -# endif - -IF_BREW_INSTALLED := $(shell command -v brew 2> /dev/null) -IF_IRSSI_INSTALLED := $(shell command -v irssi 2> /dev/null) - -install_brew: - @if [ -z "$(IF_BREW_INSTALLED)" ]; then \ - echo "$(B_BLUE)Brew is not installed, installing 'Brew'...$(RESET)"; \ - mkdir -p $(BREW_PREFIX); \ - git clone --depth=1 https://github.com/Homebrew/brew $(BREW_PREFIX); \ - if ! grep -q '$(BREW_PREFIX)/bin' $(HOME)/.zshrc; then \ - echo 'export PATH=$(BREW_PREFIX)/bin:$$PATH' >> $(HOME)/.zshrc; \ - fi; \ - echo "$(B_GREEN)Brew installed inside '$(BREW_PREFIX)'.$(RESET)"; \ - else \ - echo "$(B_YELLOW)Brew is already installed at '$(BREW_PREFIX)'.$(RESET)"; \ - fi - @if [ -z "$(IF_IRSSI_INSTALLED)" ]; then \ - echo "$(B_BLUE)Irssi is not installed, installing 'Irssi'.$(RESET)"; \ - brew install irssi; \ - echo "$(B_GREEN)Irssi is installed inside '$(shell which irssi)'.$(RESET)"; \ - else \ - echo "$(B_YELLOW)Irssi is already installed at '$(shell which irssi)'.$(RESET)"; \ - fi - -valgrind: - valgrind --leak-check=full ./$(NAME) 1234 abc - -.PHONY: all clean fclean re bonus print open brew_readline \ No newline at end of file diff --git a/Additional/Helper_projects/Gorkem_Ahmet/includes/Channel.hpp b/Additional/Helper_projects/Gorkem_Ahmet/includes/Channel.hpp deleted file mode 100644 index 19d316f..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/includes/Channel.hpp +++ /dev/null @@ -1,61 +0,0 @@ -#ifndef CHANNEL_HPP -# define CHANNEL_HPP - -# include -# include "Client.hpp" -# include "utils.hpp" -# include - -class Client; - -typedef std::vector::iterator itChannelAdmins; -typedef std::vector::iterator itChannelClients; - -class Channel -{ - private: - std::string _name; - int _clientCount; - std::vector _admins; // Birden fazla admin. - std::string _channelTopic; // Channel'e bağlantı kurulduğunda konu başlığının belirlenmesinde yardımcı oluyor. - std::string _channelModes; // Channel'in modlarını tutar. - - std::string _k; // Channel şifresini belirliyor - int _l; // Channel'a bağlanacak max client sayısını temsil ediyor. - - public: - Channel( std::string name, std::string password); - ~Channel( void ); - std::vector _channelClients; - - std::string getName( void ) { return (this->_name); } - Client* getAdmin( std::string nickname ); - std::vector getAdmins( void ) { return (this->_admins); } - std::string getChannelTopic( void ) { return (this->_channelTopic); } - int getClientCount( void ) { return (this->_clientCount); } - std::string getPassword( void ) { return (this->_k); } - int getMaxClient( void ) { return (this->_l); } - std::string getChannelMods( void ) { return (this->_channelModes); } - - void setName( std::string &name ) { this->_name = name; } - void setChannelTopic( std::string topic ) { this->_channelTopic = topic; } - void setAdmins( std::vector admins ) { this->_admins = admins; } - void setPassword( std::string password ) {this->_k = password; } - void setMaxClient( int maxClient ) {this->_l = maxClient; } - void setChannelMods( std::string mod ); - - void addClient( Client* client ); - void addAdmin( Client* admin ); - - void removeClient( Client* client ); - void removeAdmin( Client* admin ); - - void sendMessageBroadcast( std::string message ); - void sendMessageBroadcast( Client* exclude, std::string message ); - void channelUsers(Client* client, Channel* channel, std::string channelName ); // Channel'e girişte kullanıcıların listesini channel'e bastırıyor. - - Client* searchAdmin( Client* client ); - Client* searchClient( Client* client ); -}; - -#endif diff --git a/Additional/Helper_projects/Gorkem_Ahmet/includes/Client.hpp b/Additional/Helper_projects/Gorkem_Ahmet/includes/Client.hpp deleted file mode 100644 index 8cdf4a5..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/includes/Client.hpp +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef CLIENT_HPP -# define CLIENT_HPP - -# include -# include -# include -# include -# include -# include - -# include "colors.hpp" -# include "Channel.hpp" - -class Channel; - -/* - Server'da gelişi güzel kontrol eklemek yerine client'ın hangi aşamalarda olduğunu tutarlı şekilde takip etmek için eklendi. -*/ -enum IRCstatus{ - CONNECTING, // Bu durum, IRC client'ın IRC server'a bağlanmaya çalıştığı durumu temsil eder. - HANDSHAKE, // Bu durum, bağlantının kurulduğu ve IRC client'in IRC server ile bir kimlik oluşturmaya çalıştığı durumu temsil eder. - RENICK, // Bu durum, ilk bağlantıdaki client'ın nick'i aynı ise tekrardan nick isteminde bulunmak için tanımlanmaktadır. - AUTHENTICATED, // Bu durum, IRC client'in IRC server tarafından kimlik doğrulaması yapıldığı durumu temsil eder. - DISCONNECTED, // Bu durum, bağlantının sonlandırıldığı durumu temsil eder. -}; - -class Client -{ - private: - int _fd; - unsigned short _port; - std::string _hostname; - std::string _nickname; - std::string _username; - std::string _realname; - bool _havePassword; // server'a bağlanırken password olmadığından dolayı pass kontrolü yapamıyoruz, server herzaman passwordlü olduğundan dolayı bu şekilde kullanıcı password girmiş mi girmemiş mi kontrol edebiliyoruz. - int _ircstatus; // enum değerlerini tutmak için bulunuyor. - std::vector _registeredChannels; // Kullanıcının kayıtlı olduğu channel'lara erişmek daha kolay olsun diye eklendi. - std::string _clientModes; // Client'in modlarını tutar. - - public: - Client( int fd, unsigned short port, const std::string hostname ); - ~Client(); - - int getIRCstatus( void ) { return (this->_ircstatus); } - int getFd( void ) { return (this->_fd); } - unsigned short getPort( void ) { return (this->_port); } - std::string getHostname( void ) { return (this->_hostname); } - std::string getNickname( void ) { return (this->_nickname); } - std::string getUsername( void ) { return (this->_username); } - std::string getRealname( void ) { return (this->_realname); } - bool getPasswordStatus( void ) { return (this->_havePassword); } - std::string getPrefix() const; - std::string getClientMods( void ) { return (this->_clientModes); } - - void setIRCstatus( int status ) { this->_ircstatus = status; } - void setHostname( std::string name ) { this->_hostname = name; } - void setNickname( std::string name ) { this->_nickname = name; } - void setUsername( std::string name ) { this->_username = name; } - void setRealname( std::string name ) { this->_realname = name; } - void setPasswordStatus( void ) { this->_havePassword = true; } - void setClientMods( std::string mod ); - void sendMessageFd( std::string message ); - void sendWelcomeMessage( std::string message ); - - void registerChannel( Channel* channel ); // Client içinde bulunan _registeredChannels'e Channele eklemek için vardır. - void unregisterChannel( Channel* channel ); // Client içinde bulunan _registeredChannels'den Channele kaldırmak için vardır. - std::vector getRegisteredChannels( void ) { return (this->_registeredChannels); } // Client'tin kayıtlı olduğu clientlerin listesini döndürür. - bool isRegisteredChannel( std::string channelName ); // Client'in o kanala kayıtlı olup olmadığı kontrol eder. - void clearRegisteredChannels( void ) { this->_registeredChannels.clear(); } // Client quit attığı zaman kayıtlı olduğu tüm channelerden çıkarmak için yapıyoruz. -}; - -#endif diff --git a/Additional/Helper_projects/Gorkem_Ahmet/includes/Server.hpp b/Additional/Helper_projects/Gorkem_Ahmet/includes/Server.hpp deleted file mode 100644 index 134880d..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/includes/Server.hpp +++ /dev/null @@ -1,121 +0,0 @@ -#ifndef SERVER_HPP -# define SERVER_HPP - -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include - -# include "colors.hpp" -# include "Client.hpp" -# include "Channel.hpp" - -# define MAX_CONNECTIONS 10 -# define MAX_BUFFER 1024 - -class Client; -class Channel; -class Server; - -typedef std::vector::iterator itPoll; -typedef std::map::iterator itSplit; -typedef std::map::iterator itClients; -typedef std::map::iterator itChannels; - -typedef void (Server::*CmdFunc)( Client*, std::vector ); -typedef std::map::iterator itCmdFunc; - -class Server -{ -/* _________________________ VARIABLES ______________________________________ */ - private: - bool _isCheck; // arguments size is okay. - const unsigned short _port; // server port number. - const std::string _password; // server password. - const std::string _host; // server ip 127.0.0.1 - bool _isRun; // program is running? - int _serverFd; // server's fd number. - std::vector _pollfds; - std::map _clients; // client's with fd numbers. - std::map _channels; // channel's vector. - std::string _serverName; -/* -------------------------------------------------------------------------- */ -/* _________________________ MAIN FUCTIONS __________________________________ */ - private: - Server( void ); // Default Constructor. - public: - Server( int argc, char **argv ); - ~Server( void ); // Destructor. - void start( void ); - void acceptClients( void ); - void commandHandler( Client* at ); - void removeChannel( std::string channelName ); - void removeClient( int clientFd ); - void quitReason( Client* client, std::string message ); - void serverInfo( void ); -/* -------------------------------------------------------------------------- */ -/* _________________________ COMMANDS _______________________________________ */ - private: - std::map t_cmdFunc; - void cap( Client*, std::vector ); - void join( Client*, std::vector ); - void nick( Client*, std::vector ); - void pass( Client*, std::vector ); - void quit( Client*, std::vector ); - void user( Client*, std::vector ); - void privmsg( Client*, std::vector ); - void ping( Client*, std::vector ); - void part( Client*, std::vector ); - void list( Client*, std::vector ); - void whois( Client*, std::vector ); - void who( Client*, std::vector ); - void mode( Client*, std::vector ); - void modeUser( Client* it, std::vector tokenArr ); - void modeChannel( Client* it, std::vector tokenArr ); - void info( Client*, std::vector ); - void kick( Client*, std::vector ); - void topic( Client*, std::vector ); -/* -------------------------------------------------------------------------- */ -/* _________________________ SOCKET FUCTIONS ________________________________ */ - private: - void openSocket( void ); - void createSocketAddress( void ); - void startListening( void ); -/* -------------------------------------------------------------------------- */ -/* _________________________ UTILS __________________________________________ */ - private: - bool check( int argc ); - unsigned short port( std::string argv ); - std::string password( std::string argv ); - void initCommands( void ); - void addToPollfds( int fd, short events, short revents ); - std::map splitMessage( std::string delimeter, std::string message ); - std::vector cmdMessage( std::string message ); - int getClientFdByNickname( std::string name ); //Nickname'ye Client'in fd'sini döndürür. - Client* getClientByNickname( std::string name ); // Nickname'ye Client'in pointerını döndürür. - Client* getClientByFd( int fd ); //Fd'ye client'in pointerini döndürür. - std::string getRegisteredChannels( Client* Client ); // Client'in kayıtlı olduğu channellerin string listesi dönecektir. - std::string combineMessage( size_t i, std::vector vectorMessage ); //splitMessage fonk. tam tersi. - bool isChannelAdmin( Client* client, Channel* channel ); // Client'in belirtilen Channel'in admini mi, kontrol ediliyor. - bool isChannelUser( Client* client, Channel* channel ); // Client'in belirtilen Channel'in kullanıcısı mı kontrol ediliyor. - void leaveAllChannel( Client* client ); - std::string welcomeServer( void ); -/* -------------------------------------------------------------------------- */ -}; - -#endif diff --git a/Additional/Helper_projects/Gorkem_Ahmet/includes/bot/Bot.hpp b/Additional/Helper_projects/Gorkem_Ahmet/includes/bot/Bot.hpp deleted file mode 100644 index 8906563..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/includes/bot/Bot.hpp +++ /dev/null @@ -1,85 +0,0 @@ -#ifndef BOT_HPP -# define BOT_HPP - -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include - -# include "../colors.hpp" -# include "../Channel.hpp" -# include "../Server.hpp" - -# define MAX_BUFFER 1024 - -class Channel; - -class Bot -{ -/* _________________________ VARIABLES ______________________________________ */ - private: - bool _isCheck; - unsigned short _port; // 8888 - const std::string _password; // asdf - bool _isRun; - std::map _channels; - public: - static int _botFd; - static std::string _host; // 127.0.0.1 - static std::string _botNickname; - static std::string _botUsername; - static std::string _botRealname; -/* -------------------------------------------------------------------------- */ -/* _________________________ MAIN FUCTIONS __________________________________ */ - private: - Bot( void ); - public: - Bot( int argc, char **argv ); - ~Bot(); - static std::map _dataBadWords; // Static function'dan ulasabilmemiz icin bu variable'yi de static tanimlamamiz gerekiyor. - void start( void ); - static void* listen( void * ); // POSIX thread's recv() function. -/* -------------------------------------------------------------------------- */ -/* _________________________ SET/GET FUNCTIONS ______________________________ */ - static int getFd( void ) { return (Bot::_botFd); } - static std::string getPrefixBot(); -/* -------------------------------------------------------------------------- */ -/* _________________________ COMMANDS _______________________________________ */ - void authenticate( void ); - static void sendMessageToServer( std::string message ); - void checkChannels( void ); - static std::vector\ - tokenMessage( std::string message ); - void onMessageReceive( std::string buffer ); - static std::map\ - botSplitMessage( std::string delimeter, std::string message ); - static void initBadWords( void ); - static std::string scanNickname( std::string message ); - static std::string toLowerCase( const std::string& str ); -/* -------------------------------------------------------------------------- */ -/* _________________________ SIGNAL FUCTIONS ________________________________ */ - static void sigHandler( int signalNum ); -/* -------------------------------------------------------------------------- */ -/* _________________________ SOCKET FUCTIONS ________________________________ */ - private: - void openSocket( void ); - void connectSocketAddress( void ); -/* -------------------------------------------------------------------------- */ -/* _________________________ UTILS __________________________________________ */ - private: - bool check( int argc ); - unsigned short port( std::string argv ); - std::string password( std::string argv ); -/* -------------------------------------------------------------------------- */ -}; - -#endif diff --git a/Additional/Helper_projects/Gorkem_Ahmet/includes/colors.hpp b/Additional/Helper_projects/Gorkem_Ahmet/includes/colors.hpp deleted file mode 100644 index 4a1119c..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/includes/colors.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef COLORS_HPP -# define COLORS_HPP - -// COLORS --> 🟥 🟩 🟦 -# define BLACK "\033[0;30m" -# define RED "\033[0;31m" -# define GREEN "\033[0;32m" -# define YELLOW "\033[0;33m" -# define BLUE "\033[0;34m" -# define PURPLE "\033[0;35m" -# define CYAN "\033[0;36m" -# define WHITE "\033[0;37m" -# define END "\033[m" -# define RESET "\033[0m" - -// COLORS BOLD--> B🟥 B🟩 B🟦 -# define B_CYAN "\033[1;36m" -# define B_BLUE "\033[1;34m" -# define B_YELLOW "\033[1;33m" -# define B_GREEN "\033[1;32m" -# define B_RED "\033[1;31m" -# define B_RESET "\033[1m" - -#endif // COLORS_HPP \ No newline at end of file diff --git a/Additional/Helper_projects/Gorkem_Ahmet/includes/utils.hpp b/Additional/Helper_projects/Gorkem_Ahmet/includes/utils.hpp deleted file mode 100644 index 16779bb..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/includes/utils.hpp +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef UTILS_HPP -# define UTILS_HPP - -# include "colors.hpp" - -#define ERR_UNKNOWNCOMMAND(source, command) "421 " + source + " " + command + " :Unknown command" -#define ERR_NEEDMOREPARAMS(source, command) "461 " + source + " " + command + " :Not enough parameters" -#define ERR_NOTREGISTERED(source) "451 " + source + " :You have not registered" -#define ERR_ALREADYREGISTERED(source) "462 " + source + " :You may not reregister" -#define ERR_PASSWDMISMATCH(source) "464 " + source + " :Password incorrect" -#define ERR_NONICKNAMEGIVEN(nickname) "431 " + nickname + " :Nickname not given" -#define ERR_NICKNAMEINUSE(nickname) "433 " + nickname + " " + nickname + " :Nickname is already in use" -#define ERR_TOOMANYCHANNELS(source, channel) "405 " + source + " " + channel + " :You have joined too many channels" -#define ERR_NOTONCHANNEL(source, channel) "442 " + source + " " + channel + " :You're not on that channel" -#define ERR_NOSUCHCHANNEL(source, channel) "403 " + source + " " + channel + " :No such channel" -#define ERR_BADCHANNELKEY(source, channel) "475 " + source + " " + channel + " :Cannot join channel (+k)" -#define ERR_NOSUCHNICK(source, nickname) "401 " + source + " " + nickname + " :No such nick/channel" -#define ERR_USERNOTINCHANNEL(source, nickname, channel) "441 " + source + " " + nickname + " " + channel + " :They aren't on that channel" -#define ERR_CHANOPRIVSNEEDED(source, channel) "482 " + source + " " + channel + " :You're not channel operator" -#define ERR_CHANNELISFULL(source, channel) "471 " + source + " " + channel + " :Cannot join channel (+l)" -#define ERR_CANNOTSENDTOCHAN(source, channel) "404 " + source + " " + channel + " :Cannot send to channel" -#define ERR_ERRONEUSNICKNAME(source, nick) "432 " + source + " " + nick + " :Erroneous nickname" -#define ERR_UMODEUNKNOWNFLAG(source, nick) "501 " + source + " " + nick + " :Unknown MODE flag" -#define ERR_USERSDONTMATCH(source) "502 " + source + " :Cannot change mode for other users" - -// NUMERIC REPLIES -#define RPL_WELCOME(source, server) "001 " + source + " :" + B_GREEN + "Welcome " + source + " to the " + server + " server!" + END -#define RPL_NAMREPLY(source, channel, users) "353 " + source + " = " + channel + " :" + users -#define RPL_ENDOFNAMES(source, channel) "366 " + source + " " + channel + " :End of /NAMES list." -#define RPL_WHOISUSER(source, nickname, username, hostname, port, realname) "311 " + source + " " + nickname + " ~" + username + " " + hostname + ":" + port + " * :" + realname -#define RPL_WHOISSERVER(source, server) "312 " + source + " * :" + server -#define RPL_WHOISCHANNELS(source, nickname, channels) "319 " + source + " " + nickname + " :" + channels -#define RPL_ENDOFWHOIS(source, nickname) "318 " + source + " " + nickname + " :End of /WHOIS list" -#define RPL_TOPIC(source, channel, topic) "332 " + source + " " + channel + " :" + topic -#define RPL_WHOREPLY(source, channel, user, host, server, nick, flag, hopcount, realname) "352 " + source + " " + channel + " " + user + " " + host + " " + server + " " + nick + " H" + flag + " :" + hopcount + " " + realname -#define RPL_ENDOFWHO(source, channel) "315 " + source + " " + channel + " :End of WHO list" -#define RPL_LISTSTART(client) "321 " + client + " Channel - Users Count - Channel Topic" -#define RPL_LIST(client, channel, clientCount, topic) "322 " + client + " " + channel + " - " + clientCount + " - :" + topic -#define RPL_LISTEND(client) "323 " + client + " :End of /LIST" -#define RPL_INFO(client, string) "371 " + client + " :" + string -#define RPL_ENDOFINFO(client) "374 " + client + " :End of INFO list" -//410 CAP END bilgini tekrardan istiyor. - -// COMMAND REPLIES -#define RPL_JOIN(source, channel) ":" + source + " JOIN :" + channel -#define RPL_PART(source, channel, message) ":" + source + " PART " + channel + " " + message // :" + message -#define RPL_PING(source, token) ":" + source + " PONG :" + token -#define RPL_PONG(source, token) ":" + source + " PING :" + token -#define RPL_PRIVMSG(source, target, message) ":" + source + " PRIVMSG " + target + " " + message // :" + message -#define RPL_NOTICE(source, target, message) ":" + source + " NOTICE " + target + " :" + message -#define RPL_QUIT(source, message) ":" + source + " QUIT :Quit: " + message -#define RPL_KICK(source, channel, target, reason) ":" + source + " KICK " + channel + " " + target + " " + reason // :" + reason -#define RPL_MODE(source, channel, modes, args) ":" + source + " MODE " + channel + " " + modes + " " + args -#define RPL_NICK(source, nickname) ":" + source + " NICK " + nickname -#define ERROR(source, message) ":" + source + " ERROR " + " :" + message - -#endif diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/Channel.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/Channel.cpp deleted file mode 100644 index 65a791e..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/Channel.cpp +++ /dev/null @@ -1,168 +0,0 @@ -# include "../includes/Channel.hpp" - -Channel::Channel( std::string name, std::string password ) - : _name(name), _clientCount(0), _channelModes(""), _k(password), _l(0) -{ - std::cout << "Channel Created: Name: " << this->getName() << std::endl; -} - -Channel::~Channel( void ) -{ - std::cout << "Channel Deleting: Name: " << this->getName() << std::endl; -} - -Client* Channel::getAdmin( std::string nickname ) -{ - for (size_t i = 0; i < this->_admins.size(); i++) - { - if (this->_admins[i]->getNickname().compare(nickname) == 0) - return (this->_admins[i]); - } - return (NULL); -} - -void Channel::addClient( Client* client ) -{ - this->_channelClients.push_back(client); - this->_clientCount++; - std::cout << this->getName() << ": " << client->getNickname() - << " join the channel." << std::endl; -} - -void Channel::addAdmin( Client* admin ) -{ - if (admin == NULL) - return ; - std::cout << this->getName() << ": " << admin->getNickname() - << " was given the position of admin." << std::endl; - this->_admins.push_back(admin); -} - -void Channel::removeClient( Client* client ) -{ - itChannelClients it = std::find(_channelClients.begin(), - _channelClients.end(), client); - if (it != _channelClients.end()) - { - _channelClients.erase(it); - this->_clientCount--; - std::cout << this->getName() << ": " << client->getNickname() - << " left the channel." << std::endl; - } -} - -void Channel::removeAdmin( Client* admin ) -{ - itChannelAdmins itCA = std::find(this->_admins.begin(), - this->_admins.end(), admin); - if (itCA != this->_admins.end()) - { - this->_admins.erase(itCA); - std::cout << this->getName() << ": " << admin->getNickname() - << "'s admin status has been removed." << std::endl; - } -} - -void Channel::sendMessageBroadcast( std::string message ) -{ - for (itChannelClients itCli = this->_channelClients.begin(); - itCli != this->_channelClients.end(); itCli++) - { - (*itCli)->sendMessageFd(message); - } -} - -/** - * @brief Eger bir Client Channel'e mesaj attiginda burasi calisacak. - * - * Cunku yazdigi mesaji kanaldaki herkese gonderip, kendisine gondermemesi lazim. - * - * @param exclude Mesaji gonderen Client'in kendisi. - * @param message - */ -void Channel::sendMessageBroadcast( Client* exclude, std::string message ) -{ - for (itChannelClients itCli = this->_channelClients.begin(); itCli != this->_channelClients.end(); itCli++) - { - if (*itCli == exclude) - continue; - (*itCli)->sendMessageFd(message); - } -} - -void Channel::channelUsers(Client* client, Channel* channel, std::string channelName ) -{ - for (size_t i = 0; i < channel->_channelClients.size(); ++i) - { - std::string authority = ""; - // if (channel->_channelClients[i]->getNickname().compare(channel->getAdmin()->getNickname()) == 0) - if (channel->searchAdmin(channel->_channelClients[i]) != NULL) - authority = "@"; - client->sendMessageFd(RPL_NAMREPLY(client->getNickname(), channelName, authority + channel->_channelClients[i]->getNickname())); - } - client->sendMessageFd(RPL_ENDOFNAMES(client->getPrefix(), channelName)); -} - -/** - * @brief Disaridan verdigimiz Client, Channel'in Admin'leri arasinda var mi? - * - * @param client - * @return Client* :Eger varsa Channel'deki Admin'i, yoksa NULL dondur. - */ -Client* Channel::searchAdmin( Client* client ) -{ - if (!client) - return (NULL); - for (size_t i = 0; i < this->_admins.size(); i++) // Adminler arasinda disaridan verilen Client araniyor. - { - if (!client->getNickname().compare(this->_admins[i]->getNickname())) - return (this->_admins[i]); - } - return (NULL); -} - - -/** - * @brief Disaridan verdigimiz Client, Channel'in Client'leri arasinda var mi? - * - * @param client - * @return Client* :Eger varsa Channel'deki Client'i, yoksa NULL dondur. - */ -Client* Channel::searchClient( Client* client ) -{ - if (!client) - return (NULL); - for (size_t i = 0; i < this->_channelClients.size(); i++) // Adminler arasinda disaridan verilen Client araniyor. - { - if (!client->getNickname().compare(this->_channelClients[i]->getNickname())) - return (this->_channelClients[i]); - } - return (NULL); -} - -void Channel::setChannelMods( std::string mod ) -{ - if (!mod.empty()) - { - if (mod[0] == '-') - { - for (size_t i = 1; i < mod.size(); ++i) - { - if (_channelModes.find(mod[i]) != std::string::npos) - _channelModes.erase(_channelModes.find(mod[i]), 1); - } - } - else - { - if (mod[0] == '+') - mod.erase(0, 1); - for (size_t i = 0; i < mod.size(); ++i) - { - if (_channelModes.find(mod[i]) == std::string::npos) - _channelModes += mod[i]; - } - } - } - - std::sort(_channelModes.begin(), _channelModes.end()); -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/Client.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/Client.cpp deleted file mode 100644 index 95df405..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/Client.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include "../includes/Client.hpp" - -Client::Client( int fd, unsigned short port, const std::string hostname ) - : _fd(fd), - _port(port), - _hostname(hostname), - _havePassword(false), - _ircstatus(CONNECTING), - _clientModes("H") -{ - this->_nickname = ""; - this->_username = ""; - this->_realname = ""; -} - -Client::~Client() {} - -std::string Client::getPrefix() const -{ - return this->_nickname - + (this->_username.empty() ? "" : "!~" + this->_username) - + (this->_hostname.empty() ? "" : "@" + this->_hostname); -} - -void Client::setClientMods( std::string mod ) -{ - if (!mod.empty()) - { - if (mod[0] == '-') - { - for (size_t i = 1; i < mod.size(); ++i) - { - if (_clientModes.find(mod[i]) != std::string::npos) - _clientModes.erase(_clientModes.find(mod[i]), 1); - } - } - else - { - if (mod[0] == '+') - mod.erase(0, 1); - for (size_t i = 0; i < mod.size(); ++i) - { - if (_clientModes.find(mod[i]) == std::string::npos) - _clientModes += mod[i]; - } - } - } - - std::sort(_clientModes.begin(), _clientModes.end()); -} - -void Client::sendMessageFd( std::string message ) -{ - std::cout << YELLOW << "Response:>" + message << "<" << END << std::endl; - message += "\r\n"; - if (send(this->getFd(), message.c_str(), message.size(), 0) == -1) - std::cout << "Error: sendMessageFd: Failed to send message. Error code: " << errno << std::endl; -} - -void Client::sendWelcomeMessage( std::string message ) -{ - message += "\r\n"; - if (send(this->getFd(), message.c_str(), message.size(), 0) == -1) - std::cerr << "Error: sendMessageFd: Failed to send message. Error code: " << errno << std::endl; -} - -void Client::registerChannel( Channel* channel ) -{ - this->_registeredChannels.push_back(channel); -} - -void Client::unregisterChannel( Channel* channel ) -{ - for (size_t i = 0; i < this->_registeredChannels.size(); ++i) - { - if (this->_registeredChannels[i]->getName().compare(channel->getName()) == 0) - this->_registeredChannels.erase(this->_registeredChannels.begin() + i); - } -} - -bool Client::isRegisteredChannel( std::string channelName ) -{ - for (size_t i = 0; i < this->_registeredChannels.size(); ++i) - { - std::string name = this->_registeredChannels[i]->getName(); - if (name.compare(channelName) == 0 && name.size() == channelName.size()) - return (true); - } - return (false); -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/Server.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/Server.cpp deleted file mode 100644 index b336981..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/Server.cpp +++ /dev/null @@ -1,290 +0,0 @@ -/** - * @file Server.cpp - * @author Görkem SEVER (gsever), Ahmet KARACA (akaraca) - * @brief - * @version 0.1 - * @date 2023-08-27 - * - * @note: How messaging 2 client each other? - * @link http://chi.cs.uchicago.edu/chirc/irc_examples.html - * - * @note: All IRC commands. - * @link http://www.ae.metu.edu.tr/~evren/history/documents/commands.htm - * @link http://www.csun.edu/~webteach/mirc/commands.html - * @link https://www.antionline.com/showthread.php?136933-IRC-flags - * @link https://modern.ircdocs.horse/#irc-concepts - * - * @copyright Copyright (c) 2023 - * - */ -# include "../includes/Server.hpp" - -/** - * @brief Construct a new Server:: Server object. - * - * Creating Server and inits... - * - * @fn Server::check(); Checking parameters. If parameters are okay return 'true'. - * @fn Server::port(); Checking parameters. If port argument is within - * 'unsigned short' range, returning port with unsigned short type. - * @fn Server::pasword(); Checking parameters. If password is okay, - * returning password string. - * @fn Server::openSocket(); Creating(opening) a socket for Server. - * @fn Server::createSocketAddress(); Creating and seting - * socket's address types. For example; Address Family... - * @fn Server::startListening(); Adding waiting list for connections... - * @fn Server::initCommands(); Initializing all IRC commands. - * - * @param argc - * @param argv - */ -Server::Server( int argc, char **argv ) - : _isCheck(check( argc )), - _port(port( argv[1] )), - _password(password( argv[2] )), - _host( "127.0.0.1" ), - _isRun( true ), - _serverName( "ft_irc") -{ - std::cout << "Server Constructor called." << std::endl; - openSocket(); - createSocketAddress(); - startListening(); - initCommands(); - std::cout << GREEN "Socket succesfully configured." END << std::endl; -} - -/** - * @brief Destroy the Server:: Server object - * - * Deleting and terminating Server. - * - * @fn std::map::clear(); Deleting container array. - * @fn close(); Closing opened fd. - */ -Server::~Server( void ) -{ - t_cmdFunc.clear(); - // _channels'ı silme - for (itChannels it = _channels.begin(); it != _channels.end(); ++it) - delete it->second; - _channels.clear(); - // _clients'ı silme - for (itClients it = _clients.begin(); it != _clients.end(); ++it) - delete it->second; - _clients.clear(); // Map'i temizle - for (size_t i = 0; i < _pollfds.size(); ++i) { - close(_pollfds[i].fd); // Kapatılan dosyaları serbest bırakmak (isteğe bağlı) - } - _pollfds.clear(); - close(this->_serverFd); // Closing the server. - std::cout << "Server succesfully closed!" << std::endl; -} - -/** - * @brief Server started. Main loop here. - * - * TR: - * Events değişkeni, poll() fonksiyonuna gönderilen soketlerin - * beklediği olayları temsil eder. - * Revents değişkeni, poll() fonksiyonunun döndürdüğü soketlerin - * gerçekleşen olayları temsil eder. - * poll() fonksiyonu, soketlerden gelen olayları beklemek için kullanılır. - * Fonksiyon, beklediği olayların gerçekleşmesi için bir süre bekler. - * Eğer beklediği olaylar gerçekleşmezse, fonksiyon 0 değeri döndürür. - * Bu durumda, revents değişkeni de 0 olacaktır. - * - * EN: - * The Events variable represents the events expected by sockets - * sent to the poll() function. - * The Revents variable represents the events that occurred on the - * sockets returned by the poll() function. - * The poll() function is used to wait for events from sockets. - * The function waits for a while for the events it expects to occur. - * If the expected events do not occur, the function returns 0. - * In this case, the revents variable will also be 0. - * - * @fn Server::addToPollfds(); - */ -void Server::start( void ) -{ - Server::addToPollfds( this->_serverFd, POLLIN, 0 ); - std::cout << "Server listening on port: " << this->_port << std::endl; - std::cout << "Server password: " << this->_password << std::endl; - while (this->_isRun) - { - if (poll(_pollfds.begin().base(), _pollfds.size(), -1) < 0) - throw std::runtime_error("Error while polling from fd: " + std::string(strerror(errno))); - for (itPoll it = _pollfds.begin(); it != _pollfds.end(); it++) - { - if (it->revents == 0) - continue; - - if (it->revents & POLLHUP) // client'in bağlantısı koptuğunda otomatik olarak buraya girer lakin linuxta değil :/ - { - Client *at = Server::getClientByFd(it->fd); - if (at != NULL) - { - Server::leaveAllChannel(at); - Server::removeClient(it->fd); - _pollfds.erase(it); - Server::serverInfo(); - } - std::cout << "Client disconnected." << std::endl; - break; // Move to the next socket - } - - if (it->revents & POLLIN) - { - if (it->fd == _serverFd) - { - Server::acceptClients(); - break; - } - Client *at = Server::getClientByFd(it->fd); - if (at != NULL) - { - if (at->getIRCstatus() == DISCONNECTED) // linuxta quit komutuna girdikten sonra pollfd POLLHUP olmuyor veya client'le bağlantısı kopunca olmuyor, halen POLLIN durumunda oluyor mecburen koydum. - { - Server::leaveAllChannel(at); - Server::removeClient(it->fd); - std::cout << "Client disconnected." << std::endl; - _pollfds.erase(it); - Server::serverInfo(); - break; - } - else - Server::commandHandler(at); - } - else - _pollfds.erase(it); - } - } - } -} - -void Server::acceptClients( void ) -{ - sockaddr_in clientAddress = {}; - socklen_t clientAddressSize = sizeof(clientAddress); - - int clientFd = accept(this->_serverFd, (sockaddr *) &clientAddress, &clientAddressSize); - if (clientFd < 0) - std::cerr << "Error while accepting client connection: " << strerror(errno) << std::endl; - else if (clientFd == 0) - std::cerr << "Unexpected return value from accept(): 0" << std::endl; // Bu durum normal bir durum değildir ve genellikle hata işleme mantığı içinde değerlendirilmez. - else - { - unsigned short clientPort = ntohs(clientAddress.sin_port); - std::string clientHostname = inet_ntoa(clientAddress.sin_addr); - if (clientPort != 0 && !clientHostname.empty()) - { - Client *client = new Client(clientFd, clientPort, clientHostname); - if (client) - { - this->_clients.insert(std::make_pair(clientFd, client)); - std::cout << "New Client connected." << std::endl; - std::cout << "Client's hostname: " << clientHostname << std::endl; - std::cout << "Client's port: " << clientPort << std::endl; - std::cout << "Client's fd: " << clientFd << std::endl; - Server::addToPollfds(clientFd, POLLIN, 0); - return ; - } - else - std::cerr << "Error creating Client object: " << strerror(errno) << std::endl; - } - else - std::cerr << "Client information is incomplete. Not creating Client object." << std::endl; - } - close(clientFd); -} - -/* -// std::vector tokenArr = splitMessage(buffer); -// MODE gsever akaraca gorkem ahmet -*/ -void Server::commandHandler( Client* at ) -{ - char buffer[MAX_BUFFER]; - - ssize_t bytesRead = recv(at->getFd(), buffer, sizeof(buffer) - 1, 0); - if (bytesRead > 0) - { - buffer[bytesRead] = '\0'; - std::map tokens = splitMessage("\r\n", buffer); - for(itSplit itToken = tokens.begin(); itToken != tokens.end(); ++itToken) - { - std::cout << BLUE << "Message:>" << itToken->first << "-" << itToken->second << "<" << END << std::endl; - for (itCmdFunc itCF = t_cmdFunc.begin(); itCF != t_cmdFunc.end(); ++itCF) - { - if (itToken->first.compare(itCF->first) == 0) - { - try - { - if (at->getIRCstatus() != DISCONNECTED) - { - std::vector cmd = cmdMessage(itToken->second); - cmd.insert(cmd.begin(), itToken->first); - (this->*(itCF->second))(at, cmd); - cmd.clear(); - } - break; - } - catch (std::out_of_range& e) // std::vector::operator[]() tarzında doğrudan index'e erişirken gelen parametre sayısını kontrol etmek zorunda kalıyoruz, bunun yerine at() kullanarak, hatalı argüman girişi varsa trycatch bizim yerimize yakalıyor. - { - at->sendMessageFd(ERR_NEEDMOREPARAMS(at->getPrefix(), itToken->first)); - } - } - } - } - tokens.clear(); - } - else - { - at->setIRCstatus(DISCONNECTED); - // bytesRead <= 0 durumunda POLLHUP otomatik olarak tetiklenir, bu nedenle burada ek bir işlem yapmanıza gerek yok - } -} - -void Server::removeClient(int clientFd) -{ - itClients it = _clients.find(clientFd); - if (it != _clients.end()) - { - close(it->second->getFd()); - delete it->second; // Belleği serbest bırak - _clients.erase(it); - } -} - -void Server::removeChannel( std::string channelName ) -{ - itChannels it = this->_channels.find(channelName); - if (it != _channels.end()) - { - std::cout << it->second->getName() << ": Channel removed." << std::endl; - delete it->second; - _channels.erase(it); - } -} - -void Server::quitReason( Client* client, std::string message ) -{ - std::vector msg; - msg.push_back(message); - Server::quit(client, msg); -} - -void Server::serverInfo( void ) -{ - std::cout << BLUE << "------------POLL.FDS-----------------" << END << std::endl; - for (size_t i = 0; i < this->_pollfds.size(); i++) - std::cout << this->_pollfds[i].fd << " - "; - std::cout << BLUE << "\n------------CLIENTS.FDS--------------" << END << std::endl; - for (itClients it = _clients.begin(); it != _clients.end(); it++) - std::cout << it->first << " - "; - std::cout << BLUE << "\n------------CHANNELS-----------------" << END << std::endl; - for (itChannels it = _channels.begin(); it != _channels.end(); it++) - std::cout << it->first << " - "; - std::cout << BLUE << "\n-------------------------------------" << END << std::endl; -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/bot/Bot.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/bot/Bot.cpp deleted file mode 100644 index 588fa23..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/bot/Bot.cpp +++ /dev/null @@ -1,356 +0,0 @@ -#include "Bot.hpp" - -std::map Bot::Bot::_dataBadWords; - -int Bot::_botFd = -1; -std::string Bot::_host = ""; -std::string Bot::_botNickname = ""; -std::string Bot::_botUsername = ""; -std::string Bot::_botRealname = ""; - -/** - * @brief Construct a new Bot:: Bot object - * - * ./ircbot 127.0.0.1 8888 asdf - * - * @param argc - * @param argv - */ -Bot::Bot( int argc, char **argv ) - : - _isCheck(check( argc )), - _port(port( argv[2] )), - _password(password( argv[3] )), - _isRun( true ) -{ - Bot::_host = argv[1]; - Bot::_botNickname = "ircBot"; - Bot::_botUsername = "Bot"; - Bot::_botRealname = "Poor Bot"; - - std::cout << "Bot Constructor called." << std::endl; - openSocket(); - connectSocketAddress(); - std::cout << GREEN "Bot Socket succesfully configured." END << std::endl; -} - -Bot::~Bot( void ) -{ - std::cout << "Bot succesfully closed!" << std::endl; -} - -void Bot::start( void ) -{ - signal(SIGINT, sigHandler); // ^C signali icin. - authenticate(); // Server'e katiliyoruz. - std::cout << "Bot created succesfully!" << std::endl; - checkChannels(); - sendMessageToServer("QUIT"); -} - -void Bot::sigHandler( int signalNum ) -{ - if (signalNum == SIGINT) - { - std::cout << "Interrupt signal found! Bot terminating..." << std::endl; - Bot::sendMessageToServer("QUIT :Bot exiting sir."); - exit(signalNum); - } -} - -void Bot::authenticate( void ) -{ - sendMessageToServer("CAP END"); - sendMessageToServer("PASS " + this->_password); - sendMessageToServer("NICK " + _botNickname); - // USER : - sendMessageToServer("USER " + _botUsername + " "\ - + _botUsername + " " + _host + " :" + _botRealname); -} - -/** - * @brief Burada Channel'lere bakacak. Eger baglanmadigi - * channel varsa ona baglanacak. - * - * Her baglandiginda da Channel basina thread acacak. - * Her thread bir channel'i tarayacak kontrol edecek. - * - * - * pthread_create: Bu fonksiyon, yeni bir thread oluşturur. - * Fonksiyonun ilk parametresi, oluşturulan thread’in tanımlayıcısını (ID) tutacak bir değişkenin adresini alır. - * İkinci parametresi, thread’in özniteliklerini belirleyen bir yapıyı (attribute) alır. - * Üçüncü parametresi, thread’in çalıştıracağı fonksiyonu belirtir. - * Dördüncü parametresi ise, thread’in çalıştıracağı fonksiyona geçirilecek parametreleri belirtir. - * - * pthread_join: Bu fonksiyon, belirtilen thread’in sonlanmasını bekler ve sonlandığında thread’in dönüş değerini alır. - * Fonksiyonun ilk parametresi, beklenen thread’in tanımlayıcısını (ID) alır. - * İkinci parametresi ise, thread’in dönüş değerini tutacak bir değişkenin adresini alır. - * - * pthread_exit: Bu fonksiyon, çağrıldığı thread’i sonlandırır ve belirtilen dönüş değerini döndürür. - * Fonksiyonun tek parametresi, thread’in dönüş değerini belirtir. - * - * pthread_detach: Bu fonksiyon, belirtilen thread’i ayrılmış (detached) olarak işaretler. - * Bir thread ayrıldığında, bu thread sonlandığında kaynakları otomatik - * olarak sistem tarafından geri alınır ve başka bir thread’in sonlanan - * thread ile birleşmesine (join) gerek kalmaz. - * - * @fn joinChannels(): pthread'in fonksiyonu; void* dondurmeli ve aldigi - * parametre ( void* ) olmali. - */ -void Bot::checkChannels( void ) -{ - // Bakacak # ile baslayan channel varsa; - // o channel'e de baglanmadiysa baglanacak. - - pthread_t botThreadID; - std::string getMessage; - int retResult; // *retResult - - if (pthread_create(&botThreadID, NULL, &listen, this) != 0) // Bir tane thread butun kendisine gelen mesajlari dinlerken. - { - close(this->_botFd); - throw (std::runtime_error("pthread_create: Thread 'create' error!: " + std::string(strerror(errno)))); - } - - // Bizde burada kanallara bakacagiz. Kanala girdigi anda zaten mesaj gelecegi icin listen o kanaldaki mesajlari da tarayip islemis olacak. - while (true) - { - if (getline(std::cin, getMessage)) - sendMessageToServer(getMessage); - } - - // std::to_string(retResult).c_str() - if (pthread_join(botThreadID, (void **)&retResult) != 0) // Eger bu funciton'u acarsak yukaridaki functionun islemini bekler. Yani bu pthread'i acan thread islem yapmaz burada bekler. - { - close(this->_botFd); - throw (std::runtime_error("pthread_join: Thread 'wait' error!: " + std::string(strerror(errno)))); - } - if (pthread_detach(botThreadID) != 0) // Buradaki detach islemi olusturulan thread islemini bitirmeden gerceklesmemeli. - { - close(this->_botFd); - throw (std::runtime_error("pthread_detach: Thread 'detach' error!: " + std::string(strerror(errno)))); - } - -} - - -void Bot::sendMessageToServer( std::string message ) -{ - std::cout << YELLOW << "BotResponse:>" + message << "<" << END << std::endl; - message += "\r\n"; - if (send(Bot::getFd(), message.c_str(), message.size(), 0) == -1) - { - close(Bot::getFd()); - throw (std::runtime_error( "Error: sendMessageToServer: Failed to send message: " + std::string(strerror(errno)) )); - } -} - - -/** - * @brief Bu fonksiyon server tarafindan gelen her mesajda calisacak. - * - * @link https://docs.dal.net/docs/connection.html - * - * @param arg - * @return void* - */ -void* Bot::listen( void* arg ) -{ - Bot *bot; - ssize_t bytesRead; - char buffer[MAX_BUFFER]; - - initBadWords(); - bot = static_cast(arg); - while (bot->_isRun) - { - bytesRead = recv(bot->_botFd, buffer, sizeof(buffer) - 1, 0); - if (bytesRead > 0) - { - buffer[bytesRead] = '\0'; - std::cout << "-->" << buffer << std::endl; - bot->onMessageReceive(buffer); - } - else if (bytesRead == 0) - { - close(bot->_botFd); - std::cerr << RED "Connection lost!" END << std::endl; - exit(10050); // Network is down. - } - else - { - std::cerr << RED "Error: recv(): Socket error!" END << std::endl; - close(bot->_botFd); - exit(-1); // Bu programin tamamini sonlandiracagi icin kapanacak direkt. - pthread_exit((void*)-1); // Burayi silebiliriz, ama yine de kalsin. - } - } - close(bot->_botFd); - pthread_exit(EXIT_SUCCESS); // 0 -} - -/** - * @brief Gelen girdi .tolower() seklinde geldikten sonra - * burada stupid ise ****** olarak return edebilir. - * - */ -void Bot::initBadWords( void ) -{ - Bot::_dataBadWords["stupid"] = "******"; - Bot::_dataBadWords["idiot"] = "*****"; -} - -/** - * @brief - * - * @note BotTokens:>`:gsever!~gsever@127.0.0.1``PRIVMSG``#asdf``:selam`< - * for[0]: :gsever!~gsever@127.0.0.1 -> Mesaji gonderen kisi. - * for[1]: PRIVMSG -> Command - * for[2]: #asdf -> Channel - * for[3]: :selam -> Command arg - * - * 1- [0] Mesaji gonderen kisinin token'ninde kotu soz - * var ise Channel'den kicklenecek. - * 2- [3] Mesajin icerigininin toknen'inde kotu soz - * var ise Channel'den kicklenecek. - * - * @param buffer - */ -void Bot::onMessageReceive( std::string buffer ) -{ - std::vector tokens; - std::string nickname; - std::string badNickname; - - tokens = Bot::tokenMessage(buffer); // Gelen mesajin tamamini tokenlerine ayiriyoruz. - nickname = Bot::scanNickname(tokens[0]); // Ilk tokenimizin icerisindeki :gsever!~gsever@127.0.0.1 icerisinden : ile ! arasindaki nickname'yi aliyoruz. - if (Bot::_dataBadWords.find(Bot::toLowerCase(nickname)) != Bot::_dataBadWords.end()) // Eger Clien'tin Nickname'si 'bad words' ise direkt kickleyecegiz. - { - // :gsever!~gsever@127.0.0.1 NICK idiot - std::cout << B_RED "Bad Words found: " END << nickname << std::endl; - std::cout << B_RED "Inappropriate username: " END << nickname << std::endl; - if (tokens[2][0] == ':') - tokens[2].erase(0, 1); // En basindaki ':'i siliyor. - Bot::sendMessageToServer("PRIVMSG " + nickname + " Change your nickname: [" + nickname + "]"); - Bot::sendMessageToServer("KICK " + tokens[2] + " " + nickname + " Change your nickname: [" + nickname + "]"); - return; - } - badNickname = nickname; // Client ismini degistirmediyse ve mesajin iceriginde 'bad word' varsa kickleyebilmemiz icin. - if (nickname == "") - return ; - if (tokens.size() > 3 && tokens[3][0] == ':') - tokens[3].erase(0, 1); // En basindaki ':'i siliyor. - for (size_t i = 0; i < tokens.size(); i++) - { - if (!tokens[0].compare("QUIT")) - { - Bot::sendMessageToServer("QUIT :Bot exiting sir."); - exit(0); - } - // Bot::sendMessageToServer(RPL_PING(tokens[0], badNickname)); - if (!tokens[i].compare("NICK")) // Eger bir Client ismini bad words'lerden biri yaparsa diye o degistirecegi ismi aliyoruz. - badNickname = tokens[i + 1]; // Bad nickname'yi bulduk sonra bu isimli Client'i kickleyecegiz. - if (!tokens[i].compare("PING")) - Bot::sendMessageToServer(RPL_PING(tokens[0], badNickname)); - if (Bot::_dataBadWords.find(Bot::toLowerCase(tokens[i])) != Bot::_dataBadWords.end()) - { - std::cout << B_RED "Bad Words found: " END << tokens[i] << std::endl; - Bot::sendMessageToServer("KICK " + tokens[2] + " " + badNickname); - } - } -} - -/** - * @brief Disaridan aldigi kelimenin butun karakterlerini - * kucuk harfe ceviriyor. - * - * @param word - * @return std::string - */ -std::string Bot::toLowerCase( const std::string& string ) -{ - std::string result; - result = string; - - std::transform(result.begin(), result.end(), result.begin(), ::tolower); - return result; -} - -std::string Bot::scanNickname( std::string message ) -{ - size_t start; - size_t end; - std::string result; - - start = message.find(":"); - end = message.find("!"); - result = ""; - if (start != std::string::npos && end != std::string::npos) - result = message.substr(start + 1, end - start - 1); - return (result); -} - -std::vector Bot::tokenMessage( std::string message ) -{ - std::stringstream ss(message); - std::string token; - std::vector tokenArr; - - while (ss >> token) - tokenArr.push_back(token); - - // Print tokens. - // std::cout << B_BLUE << "BotTokens:>"; - // for (size_t i = 0; i < tokenArr.size(); i++) - // std::cout << "`" << tokenArr[i] << "`"; - // std::cout << "<" << END << std::endl; - return (tokenArr); -} - -std::map - Bot::botSplitMessage( std::string delimeter, std::string message ) -{ - std::map tokens; - size_t pos = 0; - - // CAP LS\r\nNICK gsever\r\nUSER A B C D E F G asdf\r\n - while ((pos = message.find(delimeter)) != std::string::npos) - { - int posFirst = message.find(' '); - - std::string firstWord = message.substr(0, posFirst); - // \r ve \n karakterlerini temizle // /info yazdığımızda sonunda \n bulunuyor, kaldırmak istiyorum bu yüzden ekledim. - for (size_t i = 0; i < firstWord.size(); ++i) { - if (firstWord[i] == '\r' || firstWord[i] == '\n') { - firstWord.erase(i, 1); - --i; // Karakter silindiği için i'yi azalt - } - } - // Ilk kelimeyi yani komutu büyük harfe çevirir - for (size_t i = 0; i < firstWord.size(); ++i) - firstWord[i] = std::toupper(firstWord[i]); - - // 1. Kısım: USER 2. Kısım: A B C D E F G asdf - //posFirst + 1; CAP'ten sonra gelene boşluğun indexi - //pos - posFirst - 1; "CAP LS\r\n" yapısında LS'i almak için LS'in uzunluğuna bulmaya ihtiyaç var, -1 ise \r'ı almak istemiyoruz. - if (posFirst != -1) - tokens.insert(std::make_pair(firstWord, message.substr(posFirst + 1, pos - posFirst - 1))); - else - tokens.insert(std::make_pair(firstWord, "")); // nc localhost için 'TEK' argüman için kopya durumu söz konusu oluyor, bunu engellemek için eklendi. 'Message:>B-b<' - message.erase(0, pos + delimeter.length()); - } - // mesaj komutsuz olarak geliyor. Kontrol için yapılandırılabilir. - if (!message.empty()) // Bilinmeyen komut ve netcat için parslama işlemini yapıyorum. - { - if (message[message.size() - 1] == '\n') - return (Bot::botSplitMessage("\n", message)); - else - { - message.append("\n"); - return (Bot::botSplitMessage("\n", message)); - //tokens.insert(std::make_pair("UNKNOWN", message)); - } - } - return (tokens); -} - diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/bot/botSocket.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/bot/botSocket.cpp deleted file mode 100644 index 9d097ce..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/bot/botSocket.cpp +++ /dev/null @@ -1,51 +0,0 @@ -#include "Bot.hpp" - -void Bot::openSocket( void ) -{ - // - // AF_INET: Address Family IPv4. Internetwork: UDP, TCP, etc. - // SOCK_STREAM: For TCP. - // '0': Automatically choose the appropriate protocol. - this->_botFd = socket(AF_INET, SOCK_STREAM, 0); - if (this->_botFd < 0) - throw std::runtime_error("Error while opening socket: " + std::string(strerror(errno))); - std::cout << YELLOW "Socket opened." END << std::endl; -} - -void Bot::connectSocketAddress( void ) -{ - struct addrinfo hints, *result; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_INET; // IPv4 - hints.ai_socktype = SOCK_STREAM; // TCP - - std::stringstream ss; - ss << this->_port; - - int status = getaddrinfo(this->_host.c_str(), ss.str().c_str(), &hints, &result); - if (status != 0) - { - close(this->_botFd); - throw std::runtime_error("Error while getting address information: " + std::string(strerror(errno))); - } - - // struct sockaddr_in serverAddress; - - // // Setting 0 &serverAddress's sizeof() bytes. - // memset((char *) &serverAddress, 0, sizeof(serverAddress)); - // std::cout << YELLOW "Socket address created." END << std::endl; - - // serverAddress.sin_family = AF_INET; - // serverAddress.sin_addr = ((struct sockaddr_in *)result->ai_addr)->sin_addr;///inet_addr(inet_ntoa(*(struct in_addr *)serverInfo->h_addr_list[0]));//inet_addr(_host.c_str()); // şeklinde bağlantı kuramayız çünkü host değeri "localhost"'tur yani string'tir - // serverAddress.sin_port = ((struct sockaddr_in *)result->ai_addr)->sin_port;//htons(this->_port); - // freeaddrinfo(result); - // std::cout << YELLOW "Socket address settings set." END << std::endl; - - // if (connect(this->_botFd, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0) - if (connect(this->_botFd, result->ai_addr, result->ai_addrlen) < 0) - { - close(this->_botFd); - throw std::runtime_error("Error while connecting to host: " + std::string(strerror(errno))); - } - std::cout << YELLOW << "Connected to " << this->_host << " on port " << this->_port << END << std::endl; -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/bot/botUtils.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/bot/botUtils.cpp deleted file mode 100644 index bdc21dc..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/bot/botUtils.cpp +++ /dev/null @@ -1,55 +0,0 @@ -#include "Bot.hpp" - -bool Bot::check( int argc ) -{ - std::cout << YELLOW "Checking parameters..." END << std::endl; - if (argc != 4) - throw( std::invalid_argument(RED "Error: Invalid Argument Count\n" - "Usage: './ircbot '" END) ); - return (true); -} - -unsigned short Bot::port( std::string port ) -{ - // for: ' $> ./ircbot "" 1234 ' - // ' $> ./ircbot '' 1234 ' - if (port.empty()) - throw( std::invalid_argument(RED "Error: Invalid Port\n" - "Port cannot be empty." END) ); - - for (size_t i = 0; i < port.length(); ++i){ - if (!isdigit(port[i])){ - throw( std::invalid_argument(RED "Error: Invalid Port\n" - "Port must be a integer." END) ); - } - } - - unsigned short portVal = atoi(port.c_str()); - - // Port numaraları, özel ayrılmış bazı portlar dışında genellikle 0 ile 65535 arasında değer alır. - // Ancak, 0 ile 1023 arasındaki port numaraları "well-known ports" olarak adlandırılır ve genellikle sistem servisleri veya tanınmış protokoller tarafından kullanılır. - // Bu port numaralarının birçoğu belirli bir protokol veya servis tarafından rezerve edilmiştir. - // Bu nedenle, kullanıcı tarafından belirlenecek port numaralarının genellikle 1024'den başlaması tercih edilir. - if (portVal < 1024 || portVal > std::numeric_limits::max()) - throw( std::invalid_argument(RED "Error: Invalid Port\n" - "Port must be between 1024 and 65535." END) ); - return (portVal); -} - -std::string Bot::password( std::string password ) -{ - // for: ' $> ./ircbot 1234 "" ' - // ' $> ./ircbot 1234 '' ' - if (password.empty()) - throw( std::invalid_argument(RED "Error: Invalid Password\n" - "Password cannot be empty." END) ); - std::cout << GREEN "Parameters okay." END << std::endl; - return (password); -} - -std::string Bot::getPrefixBot() -{ - return Bot::_botNickname - + (Bot::_botUsername.empty() ? "" : "!~" + Bot::_botUsername) - + (Bot::_host.empty() ? "" : "@" + Bot::_host); -} \ No newline at end of file diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/bot/main.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/bot/main.cpp deleted file mode 100644 index 4a8c262..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/bot/main.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include "Bot.hpp" - -/** - * @brief - * - * @note: OK: Gelen mesaji parse ile tokenlerine ayir, - * tokenlerinin icerisinde; - * PRIVMSG ve #channel ismi olanlari ele al, - * Kufur token listesi olustur enum ile, - * if (kosulunun icerisine & kufur1 | kufur2 | kufur3 | kufur4) - * gibi olursa bunu kim yazarsa channel'den kickle. - * - * Ekstra; isminde kufur olanlari da kickle, - * - * - * @param argc - * @param argv - * @return int - */ -int main( int argc, char **argv ) -{ - try - { - Bot ircBot(argc, argv); - ircBot.start(); - } - catch (const std::exception& e) - { - std::cerr << RED << e.what() << END << std::endl; - return (EXIT_FAILURE); - } - return (EXIT_SUCCESS); -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/CAP.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/CAP.cpp deleted file mode 100644 index a6c2e0b..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/CAP.cpp +++ /dev/null @@ -1,127 +0,0 @@ -# include "../../includes/Server.hpp" - -/** - * @brief Client's first 'handshake' connection steps. - * ---CAP LS 302-- -IRC client'ten gelen CAP LS 302, IRC serverinin kullanıcılara sunabileceği ek özelliklerin bir listesini içeren bir mesajdır. - CAP, "Capability" kelimesinin kısaltmasıdır. - LS, "List" kelimesinin kısaltmasıdır. - 302, ek özelliklerin bir listesinin sunulduğunu belirtir. - -CAP LS 302 mesajında yer alan ek özellikler, IRC serverinin işlevselliğini artırabilir. - Örneğin, serverin kullanıcılarına özel mesajlaşma, dosya paylaşımı veya oyun oynama gibi özellikler sunabilir. - - ---CAP * LS :multi-prefix sasl-- -CAP * LS :multi-prefix sasl mesajı, IRC client'in desteklediği ek özelliklerin bir listesini içeren bir mesajdır. - -CAP, "Capability" kelimesinin kısaltmasıdır. - *, tüm özelliklerin listelenmesini belirtir. - LS, "List" kelimesinin kısaltmasıdır. - :multi-prefix sasl, desteklenen ek özelliklerdir. - - multi-prefix: IRC client'in birden fazla önek kullanmasına izin verir. - sasl: IRC client'in SASL kimlik doğrulama protokolünü desteklediğini belirtir. - ---CAP REQ :multi-prefix-- -"CAP REQ :multi-prefix" komutu, IRC client'in IRC serverından multi-prefix özelliğini talep ettiğini belirtir. -CAP, "Capability" kelimesinin kısaltmasıdır. - REQ, "Request" kelimesinin kısaltmasıdır. - :multi-prefix, talep edilen özelliktir. - ---CAP * ACK multi-prefix-- -"CAP * ACK multi-prefix" mesajı, IRC serverının sahibi veya yöneticisinin, IRC client'in talep ettiği multi-prefix özelliğini sağladığını belirtir. -CAP, "Capability" kelimesinin kısaltmasıdır. - *, tüm özelliklerin sağlandığını belirtir. - ACK, "Acknowledge" kelimesinin kısaltmasıdır. - :multi-prefix, sağlanan özelliktir. - -IRC client, bu mesajı aldıktan sonra, multi-prefix özelliğini kullanabilir. - ---CAP END-- -"CAP END" mesajı, IRC client'in, IRC kanalıyla olan kapasite müzakerelerini tamamladığını belirtir. - -KISACA: -Örneğin, bir IRC client, IRC serverına katılmak için CAP LS 302 mesajı gönderir. - IRC serverının sahibi veya yöneticisi, CAP * LS :multi-prefix sasl mesajı ileterek, client'in desteklediği ek özelliklerin bir listesini gönderir. - IRC client, CAP REQ :multi-prefix mesajı ileterek, multi-prefix özelliğini talep eder. - IRC serverının sahibi veya yöneticisi, CAP * ACK multi-prefix mesajı ileterek, özelliğin sağlandığını belirtir. - Son olarak, IRC client, CAP END mesajı ileterek, müzakerelerin tamamlandığını belirtir. - ----------------------- - - - * >CAP LS 302< - * An IRC client message that lists the additional features that an IRC server can offer to users. - * • CAP: Short for "Capability". - * • LS: Short for "List". - * • 302: Indicates that a list of additional features is being offered. - * The additional features listed in a CAP LS 302 message can enhance the functionality of an IRC server. - * • For example, a server might offer features such as private messaging, file sharing, or gaming to its users. - * - * >CAP * LS :multi-prefix sasl< - * An IRC client message that lists the additional features that the client supports. - * • CAP: Short for "Capability". - * • *: Indicates that all features should be listed. - * • LS: Short for "List". - * • :multi-prefix sasl: The supported additional features. - * ø multi-prefix: Allows an IRC client to use multiple prefixes. - * ø sasl: Indicates that the IRC client supports the SASL authentication protocol. - * - * >CAP REQ :multi-prefix< - * A command that indicates that an IRC client is requesting the multi-prefix feature from an IRC server. - * • CAP: Short for "Capability". - * • REQ: Short for "Request". - * • :multi-prefix: The requested feature. - * - * >CAP * ACK multi-prefix< - * A message from an IRC server's owner or administrator that indicates that the server is providing the multi-prefix feature that was requested by an IRC client. - * • CAP: Short for "Capability" - * • *: Indicates that all features are being provided - * • ACK: Short for "Acknowledge" - * • :multi-prefix: The provided feature - * After receiving this message, the IRC client can use the multi-prefix feature. - - * >CAP END< - * A message that indicates that an IRC client has completed capacity negotiations with an IRC channel. - * - * IN SUMMARY; - * For example, an IRC client might send a CAP LS 302 message to join an IRC server. - * • The IRC server's owner or administrator might respond with a CAP * LS :multi-prefix sasl message, listing the additional features that the server supports. - * • The IRC client might then send a CAP REQ :multi-prefix message, requesting the multi-prefix feature. - * • The IRC server's owner or administrator might respond with a CAP * ACK multi-prefix message, indicating that the feature is being provided. - * • Finally, the IRC client might send a CAP END message, indicating that the negotiations are complete. - * - * @fn Client::getIRCstatus(); Getting client's register status. - * @fn Client::sendMessageFd(); Sending to client(fd) message. - * @fn Client::getPrefix(); Getting client's full information. - * @fn Client::getNickname(); Getting nickname. - * - * @param it - * @param tokenArr - */ -void Server::cap( Client* it, std::vector tokenArr ) -{ - std::cout << YELLOW << "CAP" << END << std::endl; - - if (it->getIRCstatus() != CONNECTING) - { - it->sendMessageFd(RPL_NOTICE(it->getPrefix(), it->getNickname(), "Client's status is insufficient.")); - return ; - } - if (!tokenArr.at(0).compare("CAP") - && !tokenArr.at(1).compare("LS") - && !tokenArr.at(2).compare("302")) - it->sendMessageFd("CAP * LS :multi-prefix sasl"); - if (!tokenArr.at(0).compare("CAP") - && !tokenArr.at(1).compare("REQ") - && !tokenArr.at(2).compare(":multi-prefix")) - it->sendMessageFd("CAP * ACK multi-prefix"); - if (!tokenArr.at(0).compare("CAP") - && !tokenArr.at(1).compare("END")) - { - it->setIRCstatus(HANDSHAKE); - it->sendMessageFd(RPL_NOTICE(it->getPrefix(), it->getNickname(), "Client status is now: HANDSHAKE.")); - } -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/DCC.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/DCC.cpp deleted file mode 100644 index 3b1b90f..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/DCC.cpp +++ /dev/null @@ -1,337 +0,0 @@ -// /** -// * @file DCC.cpp -// * @author Görkem SEVER (gsever), Ahmet KARACA(akaraca) -// * @brief -// * @version 0.1 -// * @date 2023-09-03 -// * -// * @link: https://github.com/irssi/irssi/tree/master/src/irc/dcc -// * @note: DCC (Direct Client-to-Client) mean; Send file with IRC. -// * -// * @link: https://en.wikipedia.org/wiki/Reserved_IP_addresses -// * @link: http://www.iana.org/numbers -// * -// * @copyright Copyright (c) 2023 -// * -// */ -// #include "../../includes/Server.hpp" - -// /** -// * @brief -// * -// * @note; -// * IRC (Internet Relay Chat) DCC (Direct Client-to-Client) komutları, -// kullanıcıların birbirleriyle doğrudan bağlantı kurmasını sağlar. - -// 1. **DCC CHAT {nick}**: Bu komut, belirtilen takma adla bir sohbet oturumu başlatır. -// Örneğin, "DCC CHAT john" komutu, "john" adlı kullanıcıyla bir sohbet oturumu başlatır. -// Bu hizmet, kullanıcıların bir DCC bağlantısı üzerinden birbirleriyle sohbet etmelerini sağlar. -// Trafik doğrudan kullanıcılar arasında gider ve IRC ağı üzerinden gitmez. -// DCC CHAT genellikle bir CTCP (Client-To-Client Protocol) HANSHAKE(el sıkışması) kullanılarak başlatılır. - -// 2. **DCC SEND {nick} {dosya}**: Bu komut, belirtilen takma ada belirtilen dosyayı gönderir. -// Örneğin, "DCC SEND john image.jpg" komutu, "john" adlı kullanıcıya "image.jpg" dosyasını gönderir. - -// 3. **DCC GET {nick} {dosya}**: Bu komut, belirtilen takma addan belirtilen dosyayı alır. -// Örneğin, "DCC GET john image.jpg" komutu, "john" adlı kullanıcıdan "image.jpg" dosyasını alır. - -// 4. **DCC RESUME {nick} {dosya} {port} {position}**: Bu komut, belirtilen takma adla belirtilen -// dosyanın belirtilen konumdan indirilmesini sürdürür. -// Örneğin, "DCC RESUME john image.jpg 5000 1024" komutu, "john" adlı kullanıcıdan "image.jpg" -// dosyasının 1024. bayttan itibaren indirilmesini sürdürür. - -// 5. **DCC ACCEPT {nick} {dosya} {port} {position}**: Bu komut, belirtilen takma adla belirtilen -// dosyanın belirtilen konumdan indirilmesini kabul eder. -// Örneğin, "DCC ACCEPT john image.jpg 5000 1024" komutu, "john" adlı kullanıcıdan "image.jpg" -// dosyasının 1024. bayttan itibaren indirilmesini kabul eder. - -// Bu komutlar genellikle IRC istemcilerinde bulunur ve doğrudan IRC sunucusu yerine -// kullanıcılar arasında bağlantı kurarlar. -// * -// */ - - -// /* -// DCC (Direct Client-to-Client) protokolü, IRC (Internet Relay Chat) istemcileri arasında doğrudan bağlantılar kurmak için kullanılır¹. DCC bağlantıları, IRC ağı ve sunucularını atlayarak istemciler arasında çeşitli verilerin aktarılmasına olanak sağlar². İşte DCC protokolünün bazı temel komutları ve nasıl çalıştıkları: - -// 1. **DCC CHAT**: Bu hizmet, kullanıcıların bir DCC bağlantısı üzerinden birbirleriyle sohbet etmelerini sağlar¹. Trafik doğrudan kullanıcılar arasında gider ve IRC ağı üzerinden gitmez¹. DCC CHAT genellikle bir CTCP (Client-To-Client Protocol) el sıkışması kullanılarak başlatılır¹. - -// 2. **DCC SEND**: Bu hizmet, bir dosyanın bir kullanıcıdan diğerine gönderilmesini sağlar¹. Dosya transferi genellikle bir CTCP el sıkışması kullanılarak başlatılır¹. - -// 3. **DCC RESUME**: Bu komut, durdurulmuş bir dosya transferini sürdürmek için kullanılır. Örnek: `/DCC RESUME KullaniciAdi dosya.zip` - -// 4. **DCC ACCEPT**: Bu komut, durdurulmuş bir dosya transferinin devam etmesini kabul etmek için kullanılır. Örnek: `/DCC ACCEPT KullaniciAdi dosya.zip` - -// 5. **DCC CLOSE**: Bu komut, bir DCC bağlantısını kapatmak için kullanılır. Örnek: `/DCC CLOSE get KullaniciAdi` - -// Bu komutların her biri, belirli bir DCC işlemi gerçekleştirmek için kullanılır. Her komutun tam olarak nasıl çalıştığını anlamak için, belirli bir IRC istemcisinin belgelerine veya yardım dosyalarına başvurmanız önerilir. - -// Umarım bu bilgiler yardımcı olur! Başka bir sorunuz varsa, lütfen sormaktan çekinmeyin. 😊 - -// Source: Conversation with Bing, 03.09.2023 -// (1) Direct Client-to-Client - Wikipedia. https://en.wikipedia.org/wiki/Direct_Client-to-Client. -// (2) Direct Client-to-Client Protocol (DCC). https://modern.ircdocs.horse/dcc.html. -// (3) List of Internet Relay Chat commands - Wikipedia. https://en.wikipedia.org/wiki/List_of_Internet_Relay_Chat_commands. -// */ - -// // DCC send -// // DCC get -// void Server::dcc( Client* it, std::vector tokenArr ) -// { -// std::cout << YELLOW << "DCC" << END << std::endl; - -// if (it->getIRCstatus() != AUTHENTICATED) -// { -// it->sendMessageFd(RPL_NOTICE(it->getPrefix(), it->getNickname(), "Client's status is insufficient.")); -// return ; -// } - -// if (tokenArr.size() < 4) -// throw( std::out_of_range("") ); - -// if (Server::getClientFdByNickname(tokenArr[2]) == -1) -// { -// it->sendMessageFd(ERR_NOSUCHNICK(it->getPrefix(), tokenArr[2])); -// return ; -// } - -// this->_dccSubVector = std::vector(tokenArr.begin() + 2, tokenArr.end()); -// this->_dccSubVector.insert(this->_dccSubVector.begin(), it->getNickname()); - -// #if defined(__APPLE__) -// pthread_t dccThreadID = NULL; -// #elif defined(linux) -// pthread_t dccThreadID; -// #endif - - -// if (tokenArr[1].compare("SEND") == 0) -// { -// if (pthread_create(&dccThreadID, NULL, &Server::dccSend, this) != 0) -// throw (std::runtime_error("pthread_create: Thread 'create' error!")); -// } -// else if (tokenArr[1].compare("GET") == 0) -// { -// if (pthread_create(&dccThreadID, NULL, &Server::dccGet, this) != 0) -// throw (std::runtime_error("pthread_create: Thread 'create' error!")); -// } -// else -// it->sendMessageFd(ERR_UNKNOWNCOMMAND(it->getPrefix(), tokenArr[0] + " " + tokenArr[1])); - -// if (pthread_detach(dccThreadID) != 0) // threadi beklemek istemiyoruz bu yüzden join kullanmıyoruz bunun yerine sadece detach kullanıyoruz. -// throw (std::runtime_error("pthread_detach: Thread 'detach' error!")); - - -// // Sender dosyayı göndermek için alıyıcıya bilgi göndersin ve alıcıdan mesaj beklesin -// // Eğer alıcı dosya almak işlemini kabul ederse, alıcıda yeni bir socket oluşturulsun ve accept işlemine geçilsin -// // Alıcı yeni port açıp bu bilgiye sender'a bildirmelidir ve bu mesaj işlenmelidir. -// // Sender geri dönüt yanıtına göre socket oluşturup, alıcıya bağlansın ve dosya gönderme işlemini yerine getirsin. -// } - -// // -// void* Server::dccSend( void* arg ) -// { -// std::cout << YELLOW << "DCC-SEND" << END << std::endl; - -// Server* server; -// server = static_cast(arg); - -// std::cout << server->_dccSubVector[0] << std::endl; // sender -// std::cout << server->_dccSubVector[1] << std::endl; // receiver -// std::cout << server->_dccSubVector[2] << std::endl; // file - -// Client* sender = server->getClientByNickname(server->_dccSubVector[0]); -// Client* receiver = server->getClientByNickname(server->_dccSubVector[1]); -// std::string filePath = server->_dccSubVector[2]; - -// std::string hostname = receiver->getHostname(); -// const char* receiverIP = hostname.c_str(); - -// int receiverPort = receiver->getPort(); -// // int receiverPort = 6666; - - - -// // ---------------------------- DOSYA KONTROLU ---------------------------- // -// struct stat info; - -// if (stat(filePath.c_str(), &info) != -1) -// { -// if (!S_ISREG(info.st_mode)) -// { -// sender->sendMessageFd(ERROR(sender->getPrefix(), "DCC-SEND This is not file!")); -// std::cerr << "DCC-SEND This is not file!" << std::endl; -// pthread_exit((void *)EXIT_FAILURE); -// } -// } -// else -// { -// sender->sendMessageFd(ERROR(sender->getPrefix(), "DCC-SEND " + strerror(errno))); -// std::cerr << strerror(errno) << std::endl; -// pthread_exit((void *)EXIT_FAILURE); -// } - -// std::string _buffer; -// char buffer[4096]; -// FILE *fd = fopen(filePath.c_str(), "rb"); - -// while (!feof(fd)) { -// int size = fread(&buffer, 1, 256, fd); -// if (size < 0) -// break; - -// _buffer.append(buffer, size); -// } - -// fclose(fd); - -// // ---------------------------- HEDEFE BILGI GONDERME ---------------------------- // -// std::stringstream Port, Size; -// Port << receiverPort; -// Size << info.st_size; - -// std::size_t last_dot_pos = filePath.find_last_of('/'); -// std::string fileName = filePath.substr(last_dot_pos + 1); - -// std::string message = GREEN "DCC SEND from " + sender->getNickname() + END " [127.0.0.1 port " + Port.str() + "]: " + fileName + " [" + Size.str() + "B]"; -// receiver->sendMessageFd(message); - -// // ---------------------------- SOCKET OLUŞTURMA ---------------------------- // -// //Eğer server, her iki client'in soketlerini kullanmak için yeni bir soket oluşturmazsa, aşağıdaki sorunlarla karşılaşabilir: -// //Dosya aktarımı, başka client'ler tarafından dinlenebilir. -// //Dosya bilgilerinin şifrelenmemesi durumunda, dosyalar güvenli bir şekilde iletilemez. -// //Dosya transferi sırasında bir hata meydana gelirse, dosya transferi tamamlanamaz. -// //Bu nedenle, IRC server'da file transfer için yeni soket oluşturmak her zaman gereklidir. -// int dccSocket = socket(AF_INET, SOCK_STREAM, 0); -// if (dccSocket == -1) { -// sender->sendMessageFd(ERROR(sender->getPrefix(), "DCC-SEND " + strerror(errno))); -// perror("Socket creation failed"); -// pthread_exit((void *)EXIT_FAILURE); -// } - -// int val = 1; -// if (setsockopt(dccSocket, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val))) -// throw std::runtime_error("Error while setting socket options."); - -// // ---------------------------- HEDEF BAGLANTIYI DINLEME ---------------------------- // - -// struct sockaddr_in dccServerAddress = {}; -// int dcc_address_len = sizeof(dccServerAddress); - -// bzero((char *) &dccServerAddress, dcc_address_len); - -// dccServerAddress.sin_family = AF_INET; -// dccServerAddress.sin_addr.s_addr = inet_addr(receiverIP);//INADDR_ANY; -// dccServerAddress.sin_port = htons(receiverPort); - -// if (bind(dccSocket, (struct sockaddr*)&dccServerAddress, sizeof(dccServerAddress)) == -1) { -// perror("Bind failed"); -// close(dccSocket); -// pthread_exit((void*)EXIT_FAILURE); -// } - -// std::cout << ".............1.............." << std::endl; -// if (listen(dccSocket, 1) == -1) { // 1 bağlantıyı kabul etmek için sınırlıyoruz -// perror("Listen failed"); -// close(dccSocket); -// pthread_exit((void*)EXIT_FAILURE); -// } - -// std::cout << ".............2.............." << std::endl; -// // ---------------------------- HEDEF BAGLANTIYA BAGLANMA ---------------------------- // - -// int client_fd = accept(dccSocket, (struct sockaddr *) &dccServerAddress, (socklen_t *) &dcc_address_len); -// if (client_fd < 0) { -// close(dccSocket); -// pthread_exit((void*)EXIT_FAILURE); -// } -// std::cout << "............3..............." << std::endl; - -// // ---------------------------- HEDEFE DOSYAYI GONDERME ---------------------------- // - -// send(client_fd, _buffer.c_str(), _buffer.size(), 0); - -// close(client_fd); -// close(dccSocket); -// _buffer.clear(); - -// pthread_exit(EXIT_SUCCESS); -// } - -// // -// void* Server::dccGet( void* arg ) -// { -// std::cout << YELLOW << "DCC-GET" << END << std::endl; - -// Server* server; -// server = static_cast(arg); - -// std::cout << server->_dccSubVector[0] << std::endl; // receiver -// std::cout << server->_dccSubVector[1] << std::endl; // sender -// std::cout << server->_dccSubVector[2] << std::endl; // file - -// Client* receiver = server->getClientByNickname(server->_dccSubVector[0]); -// Client* sender = server->getClientByNickname(server->_dccSubVector[1]); -// std::string fileName = server->_dccSubVector[2]; - -// std::string hostname = sender->getHostname(); -// const char* senderIP = hostname.c_str(); - -// int receiverPort = receiver->getPort(); -// // int receiverPort = 6666; - -// int dccSocket = socket(AF_INET, SOCK_STREAM, 0); -// if (dccSocket == -1) { -// perror("Socket creation failed"); -// pthread_exit((void *)EXIT_FAILURE); -// } - -// struct sockaddr_in clientAddress = {}; -// int client_address_len = sizeof(clientAddress); - -// bzero((char *) &clientAddress, client_address_len); - -// clientAddress.sin_family = AF_INET; -// clientAddress.sin_addr.s_addr = inet_addr(senderIP); -// clientAddress.sin_port = htons(receiverPort); - -// std::cout << "----------------1------------------" << std::endl; - -// if (connect(dccSocket, (struct sockaddr*)&clientAddress, sizeof(clientAddress)) == -1) { -// perror("Connection failed"); -// close(dccSocket); -// pthread_exit((void *)EXIT_FAILURE); -// } - -// std::cout << "----------------2------------------" << std::endl; - -// // ---------------------------- DOSYAYI ALMA ---------------------------- // - -// // Dosyayı oluştur ve verileri yaz -// std::ofstream outFile(fileName.c_str(), std::ios::binary); -// if (!outFile) { -// std::cerr << "Dosya oluşturma hatası." << std::endl; -// close(dccSocket); -// pthread_exit((void *)EXIT_FAILURE); -// } - -// char buffer[1024]; -// ssize_t bytesRead; -// while ((bytesRead = recv(dccSocket, buffer, sizeof(buffer), 0)) > 0) { -// outFile.write(buffer, bytesRead); -// } - -// if (bytesRead == -1) { -// std::cerr << "Veri alma hatası." << std::endl; -// outFile.close(); -// close(dccSocket); -// pthread_exit((void *)EXIT_FAILURE); -// } - -// // Dosya ve soketleri kapat -// outFile.close(); -// close(dccSocket); -// std::cout << "File received successfully." << std::endl; - -// pthread_exit(EXIT_SUCCESS); -// } diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/INFO.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/INFO.cpp deleted file mode 100644 index d531908..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/INFO.cpp +++ /dev/null @@ -1,22 +0,0 @@ -# include "../../includes/Server.hpp" - -void Server::info( Client* it, std::vector tokenArr ) -{ - std::cout << YELLOW << "INFO" << END << std::endl; - (void)tokenArr; - it->sendMessageFd(RPL_INFO(it->getPrefix(), std::string("This ft_irc project was created by akaraca and gsever."))); - it->sendMessageFd(RPL_INFO(it->getPrefix(), std::string("Server's Users:"))); - for (itClients itC = _clients.begin(); itC != _clients.end(); ++itC) - { - Client *dest = itC->second; - std::stringstream ss; - ss << dest->getPort(); - it->sendMessageFd(RPL_WHOISUSER(it->getPrefix(), dest->getNickname(), dest->getUsername(), dest->getHostname(), ss.str(), dest->getRealname())); // Aranan kullanıcı hakkında bilgiyi yazdırır - // it->sendMessageFd(RPL_WHOISSERVER(it->getPrefix(), this->_serverName)); - if (dest->getRegisteredChannels().size() != 0) - it->sendMessageFd(RPL_WHOISCHANNELS(it->getPrefix(), dest->getNickname(), Server::getRegisteredChannels(dest))); - } - it->sendMessageFd(RPL_ENDOFWHOIS(it->getPrefix(), "")); - - it->sendMessageFd(RPL_ENDOFINFO(it->getPrefix())); -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/JOIN.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/JOIN.cpp deleted file mode 100644 index 3e56f1b..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/JOIN.cpp +++ /dev/null @@ -1,84 +0,0 @@ -# include "../../includes/Server.hpp" - -/* -// https://dd.ircdocs.horse/refs/commands/join -// channel içinde: /name veya /names kullanıcıları listeler. -// Var olan bir channele biri bağlandığında mesaj bastırmalıdır : 'Guest46147 [~AHMET@176.88.10.20] has joined #42Kocaeli' -*/ -void Server::join( Client* it, std::vector tokenArr ) -{ - std::cout << YELLOW << "JOIN" << END << std::endl; - - if (it->getIRCstatus() != AUTHENTICATED) // Kayıt işlemi bitmemiş Client'ler join fonksiyonuna girmesin istiyoruz, irssi client kayıt işlemini bitirmeden JOIN komutu gönderiyor. - { - it->sendMessageFd(RPL_NOTICE(it->getPrefix(), it->getNickname(), "Client's status is insufficient.")); - return ; - } - - if (tokenArr.at(1)[0] != '#') // '/join asdf' şeklinde kanal oluşturmak için isim belirlendiğinde, - tokenArr[1] = "#" + tokenArr[1]; // Girilen ismin sonuna '#' ekleniyor, Bunun nedeni channel isimleri '#' ile başlamaktadır. - - itChannels itChannel = _channels.find(tokenArr[1]); // Aynı isimde channel var mı kontrol ediliyor. - if (itChannel != _channels.end()) // Channel mevcutsa buraya giriyor. - { - if (!itChannel->second->getPassword().empty() &&\ - ((tokenArr.size() != 3 ) || (tokenArr.size() == 3 && itChannel->second->getPassword().compare(tokenArr[2]) != 0))) // eğer channelin şifresi varsa - { - it->sendMessageFd(ERR_PASSWDMISMATCH(it->getPrefix())); // Channela girerken şifresi yanlışsa - it->sendMessageFd(RPL_KICK(it->getPrefix(), tokenArr[1], tokenArr[1], "Password is incorrect!")); // Irc client channel oluşturuyor lakin boş gözüküyor, bu yüzden kicklemeliyiz. - return ; - } - - if (itChannel->second->getMaxClient() != 0 &&\ - itChannel->second->getMaxClient() < itChannel->second->getClientCount() + 1) - { - it->sendMessageFd(ERR_CHANNELISFULL(it->getPrefix(), tokenArr[1])); - return ; - } - - itChannel->second->sendMessageBroadcast(it, RPL_JOIN(it->getPrefix(), tokenArr[1])); // Channel'da bulunan diğer Client'lara yeni katılan Client'ın katıldı bilgisi gönderiliyor. - itChannel->second->addClient(it); // Channel'e bağlı olan client'lar listesi güncelleniyor. - it->registerChannel(itChannel->second); // Client içinde bulunan, kayıtlı kullanıcıların olduğu listeye channel ekleniyor. - it->sendMessageFd(RPL_JOIN(it->getPrefix(), tokenArr[1])); // Kullanıcı kanal olsada, olmasada hertürlü o kanala katılacağından dolayı RPL yanıtını gönderiyoruz. - itChannel->second->channelUsers(it, itChannel->second, tokenArr[1]); // Client, channel'e bağlandığı zaman, channel'deki kullanıcılar listeleniyor. - it->sendMessageFd(RPL_TOPIC(it->getPrefix(), tokenArr[1], itChannel->second->getChannelTopic())); // var olan bir Channel'e kullanıcı katıldığı zaman göreceği channel başlığı bilgisi gönderiliyor. - } - else // Channel mevcut değilse, yeni channel oluşturulup, ayarlamalar gerçekleştiriliyor. - { - Channel *channel = new Channel(tokenArr[1], "\0"); // Channel oluşturulur ve admini belirlenir. Channel şifresi için henüz bir şey yoktur. - if (channel) - { - channel->addClient(it); // Channel'ı oluşturan kişiyi _channelClient'ına ekliyor. - channel->addAdmin(it); - // channel->setChannelMods("nt"); - if (this->getClientByNickname("ircBot") != NULL // Bu Channel'i Bot kendisi olusturursa 2 kere Botu eklemeyi engellemek icin. - && it->getNickname().compare("ircBot")) // Gercekten de Bot mu? - { - channel->addClient(this->getClientByNickname("ircBot")); // Ikinci Client olarak Bot'u ekle. - channel->addAdmin(this->getClientByNickname("ircBot")); - this->getClientByNickname("ircBot")->registerChannel(channel); - } - this->_channels.insert(std::make_pair(tokenArr[1], channel)); // Server'a channel'ı ekliyor. - channel->setChannelTopic("What day is it today?"); // Channel başlığı belirleniyor. - it->registerChannel(channel); // Client içinde bulunan, kayıtlı kullanıcıların olduğu listeye channel ekleniyor. - it->sendMessageFd(RPL_JOIN(it->getPrefix(), tokenArr[1])); // Kullanıcı kanal olsada, olmasada hertürlü o kanala katılacağından dolayı RPL yanıtını gönderiyoruz. - channel->channelUsers(it, channel, tokenArr[1]); // Client, channel'e bağlandığı zaman, channel'deki kullanıcılar listeleniyor. - it->sendMessageFd(RPL_TOPIC(it->getPrefix(), tokenArr[1], channel->getChannelTopic())); // Client kanala katıldığı zaman channel başlığı gönderiliyor. - // it->sendMessageFd(RPL_MODE(it->getNickname(), tokenArr[1], "+o" + channel->getChannelMods(), "")); // Channel'in modları atanıyor - } - else - std::cerr << "Error creating Channel object: " << strerror(errno) << std::endl; - } -} - -/* -+o: Op (Operator) modu, kullanıcının kanalda yönetici veya moderatör olmasını sağlar. Yani, kullanıcı kanalı yönetme yetkisine sahip olur. - -+v: Voice modu, kullanıcının kanalda sesli konuşma yetkisine sahip olmasını sağlar. Diğer kullanıcılar, sesi olan kullanıcıları daha iyi duyar. - -+n: No External Messages modu, kanala katılan kullanıcıların özel mesajlarına kısıtlamalar getirir, böylece yalnızca kanalda açıkça konuşulan mesajları görebilirler. - -+t: Topic (Konu) modu, sadece kanal operatörlerinin kanalın konusunu (topic) değiştirmesine izin verir. - -+m: Moderated modu, sadece kanal operatörleri veya sesi olan kullanıcıların mesaj göndermesine izin verir. -*/ diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/KICK.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/KICK.cpp deleted file mode 100644 index 7af5e46..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/KICK.cpp +++ /dev/null @@ -1,58 +0,0 @@ -# include "../../includes/Server.hpp" - -/* - 'KICK #channel nickname :message' - 'KICK #TEST akaraca :Get of my channel' - '/kick akaraca Get of my channel' - or - '/kick #42 akaraca Get of my channel' -*/ -void Server::kick( Client* it, std::vector tokenArr ) -{ - std::cout << YELLOW << "KICK" << END << std::endl; - - if (it->getIRCstatus() != AUTHENTICATED) - { - it->sendMessageFd(RPL_NOTICE(it->getPrefix(), it->getNickname(), "Client's status is insufficient.")); - return ; - } - - itChannels itChan = _channels.find(tokenArr.at(1)); - if (itChan != _channels.end()) // Belirtilen channel var mıdır? - { - if (isChannelAdmin(it, itChan->second)) // /kick komutunu kullanan kişi o channelin admini mi? (channel'de user mi diye kontrol etmeye gerek yok, zaten admin kontrolü ile sağlanmış olunuyor.) - { - Client* user = getClientByNickname(tokenArr.at(2)); - if (user != NULL) - { - if (isChannelUser(user, itChan->second)) // Channel'dan atılmak istenen kişi var mıdır? - { - if (user == it) - it->sendMessageFd(RPL_NOTICE(it->getPrefix(), tokenArr[2], "You cannot kick yourself.")); - else - { - itChan->second->sendMessageBroadcast(RPL_KICK(it->getPrefix(), tokenArr[1], tokenArr[2], combineMessage(3, tokenArr))); // kicklenen kişinin tüm channel'le duyurulması için ve kickleyen kişide işe yaraması için - itChan->second->removeClient(user); // Channel'a kayıtlı kullanıcılardan client'i kaldırıyorum. - itChan->second->removeAdmin(user); // Channel'dan atılan kişinin adminliği varsa kaldırılıyor. - user->unregisterChannel(itChan->second); // Client'a ait kayıtlı olunan channeler'dan, channel'ı kaldırıyorum. - if ((itChan->second->getClientCount() == 1 && itChan->second->searchClient(this->getClientByNickname("ircBot")) != NULL)) // Channel'da kullanıcı kalmadıysa silinmelidir - { - Client *bot = Server::getClientByNickname("ircBot"); - bot->sendMessageFd(RPL_PART(bot->getPrefix(), tokenArr[1], std::string("I can't stand being alone!"))); - bot->unregisterChannel(itChan->second); - Server::removeChannel(itChan->second->getName()); - } - } - } - else - it->sendMessageFd(ERR_USERNOTINCHANNEL(it->getPrefix(), tokenArr[2], tokenArr[1])); // Channel'de atılacak kişi yoksa hata döndürülür. - } - else - it->sendMessageFd(ERR_NOSUCHNICK(it->getPrefix(), tokenArr[2])); // Atılacak kullanıcı yoksa hata döndürülür. - } - else - it->sendMessageFd(ERR_CHANOPRIVSNEEDED(it->getPrefix(), tokenArr[1])); - } - else - it->sendMessageFd(ERR_NOSUCHCHANNEL(it->getPrefix(), tokenArr[1])); // Channel yoksa hata döndürülür. -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/LIST.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/LIST.cpp deleted file mode 100644 index 739b968..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/LIST.cpp +++ /dev/null @@ -1,52 +0,0 @@ -# include "../../includes/Server.hpp" - -/* - "/list -y" yazınca tüm kanalları listeleyecek. - - #42kocaeli - #BEn - #VoidChannel - ... - -*/ -void Server::list( Client* it, std::vector tokenArr ) -{ - std::cout << YELLOW << "LIST" << END << std::endl; - if (it->getIRCstatus() != AUTHENTICATED) - { - it->sendMessageFd(RPL_NOTICE(it->getPrefix(), it->getNickname(), "Client's status is insufficient.")); - return ; - } - it->sendMessageFd(RPL_LISTSTART(it->getPrefix())); - - size_t i = tokenArr.size(); - std::stringstream ss; - itChannels itChan; - if (i == 1) // '/list -y' yani tüm channelleri listelemek için - { - for (itChan = this->_channels.begin(); itChan != this->_channels.end(); ++itChan) - { - ss.str(""); - ss << itChan->second->getClientCount(); - it->sendMessageFd(RPL_LIST(it->getPrefix(), itChan->second->getName(), ss.str(), itChan->second->getChannelTopic())); - } - } - else // '/list a #b c d #x x f' yani belirli channelleri listelemek için - { - for (size_t l = 1; l < i; ++l) - { - ss.str(""); - if (tokenArr[l][0] != '#') - tokenArr[l] = "#" + tokenArr[l]; - itChan = _channels.find(tokenArr[l]); - if (itChan != _channels.end()) - { - ss << itChan->second->getClientCount(); - it->sendMessageFd(RPL_LIST(it->getPrefix(), itChan->second->getName(), ss.str(), itChan->second->getChannelTopic())); - } - else - it->sendMessageFd(ERR_NOSUCHCHANNEL(it->getPrefix(), tokenArr[l])); - } - } - it->sendMessageFd(RPL_LISTEND(it->getPrefix())); -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/MODE.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/MODE.cpp deleted file mode 100644 index 5f94fea..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/MODE.cpp +++ /dev/null @@ -1,217 +0,0 @@ -# include "../../includes/Server.hpp" - -/** - * @brief - * - * @link https://www.antionline.com/showthread.php?136933-IRC-flags - * @link https://datatracker.ietf.org/doc/html/rfc2812#section-3.1.5 - * @link https://irssi.org/documentation/help/mode/ - * - * PRIVMSG -Message:>MODE-naber< -Message:>naber< -Tokens:>`naber`< -MODE -Message:>MODE-#naber< -Message:>#naber< -Tokens:>`#naber`< -MODE -Message:>MODE-naber asdf< -Message:>naber asdf< -Tokens:>`naber``asdf`< -MODE -Message:>MODE-#naber +asdf< -Message:>#naber +asdf< -Tokens:>`#naber``+asdf`< -MODE -Message:>MODE-#naber +asdf< -Message:>#naber +asdf< -Tokens:>`#naber``+asdf`< -MODE -Message:>MODE-#naber -asdf< -Message:>#naber -asdf< -Tokens:>`#naber``-asdf`< -MODE -Message:>MODE-naber -asdf< -Message:>naber -asdf< -Tokens:>`naber``-asdf`< -MODE -Message:>MODE-naber -asdf asdf asdf< -Message:>naber -asdf asdf asdf< -Tokens:>`naber``-asdf``asdf``asdf`< -MODE -Message:>MODE-#naber -asdfasdfasdf< -Message:>#naber -asdfasdfasdf< -Tokens:>`#naber``-asdfasdfasdf`< -MODE -Message:>MODE-#naber +asdfasdfasdfasdfasfasdf< -Message:>#naber +asdfasdfasdfasdfasfasdf< -Tokens:>`#naber``+asdfasdfasdfasdfasfasdf`< -MODE -^C - * - * @param message - * - * - * - * - * MODE message: - * ->User mode: Bu modlar, kullanıcıların kendilerinin veya diğer kullanıcıların nasıl görüneceğini veya hangi ekstra mesajları alacaklarını değiştirmek için kullanılır. - * '/mode -i' -> 'Can't change mode for other users' hata alırsın çünkü başka birinin mode ayarlarını değiştiremezsin. Yetki yeterli değildir. - * '/mode -i' -> 'Mode change [-i] for user akaraca2' kendi mode ayarlarını değiştirebilirsin. - * - * Mode change [+i] for user akaraca2 - * Mode change [+H] for user akaraca2 - * Mode change [+s] for user akaraca2 - * Mode change [+w] for user akaraca2 - * -> Bu yapıların '-'li durumları kullanımına izin var(dalnet) - * - * ->Channel mode - * '/mode #42kocaeli +o ' -> kişiye adminlik veriliyor. Bizim yapıda 1 adet adminlik olduğundan dolayı, admin takası gerçekleşecek bu durumda. - * '/mode #42kocaeli +k test' -> şeklinde channel'e şifre koyulursa: - * sadece '/join 42kocaeli' girdisi sonucunda şu hatayı alacaktır -> 'Cannot join to channel #42kocaeli (Bad channel key)' - * girebilmesi için : '/join 42kocaeli test' yazmlıdır. - * '/mode #42kocaeli +l 3' -> Channel'daki kullanıcı sınırını belirliyor - * eğer 4.kişi girmeye çalışırsa -> 'Cannot join to channel #42kocaeli (Channel is full)' hatası ile karşılaşıyor 4.client - * '/mode #42kocaeli -l' ile limit kaldırılıyor. - * - */ -void Server::mode( Client* it, std::vector tokenArr ) -{ - std::cout << YELLOW << "MODE" << END << std::endl; - if (it->getIRCstatus() != AUTHENTICATED) - { - it->sendMessageFd(RPL_NOTICE(it->getPrefix(), it->getNickname(), "Client's status is insufficient.")); - return ; - } - - if (tokenArr.at(1)[0] != '#') - Server::modeUser(it, tokenArr); - else - Server::modeChannel(it, tokenArr); -} - -void Server::modeUser( Client* it, std::vector tokenArr ) -{ - int fd = Server::getClientFdByNickname(tokenArr[1]); - if (fd == -1) // kişi yoksa - it->sendMessageFd(ERR_NOSUCHNICK(it->getPrefix(), tokenArr[1])); - else if (fd != it->getFd()) //başka birisinin modunu değiştirmek istendiğinde - it->sendMessageFd(ERR_USERSDONTMATCH(it->getPrefix())); - else // Kendi modunu değiştirmek isterse - { - bool isAdded = (tokenArr.at(2)[0] == '+' ? true : false); - char c = tokenArr[2][1]; - switch (c) - { - case 'H': - { - it->sendMessageFd(RPL_MODE(it->getPrefix(), tokenArr[1], (isAdded ? "+H" : "-H"), "")); - it->setClientMods( isAdded ? "+H" : "-H"); - break; - } - - default: - { - it->sendMessageFd(ERR_UMODEUNKNOWNFLAG(it->getPrefix(), tokenArr[2])); - break; - } - } - } -} - -void Server::modeChannel( Client* it, std::vector tokenArr ) -{ - itChannels itChan = _channels.find(tokenArr[1]); - if (itChan == _channels.end()) - { - it->sendMessageFd(ERR_NOSUCHCHANNEL(it->getPrefix(), tokenArr[1])); - return ; - } - - if (tokenArr.size() == 2) // client channel'e bağlandıktan sonra mod bilgisi almaktadır belli aralıklarla (MODE ), yetkisiz giriş vermek istemiyorum. - { - std::string args = ""; - args += "Key: " + itChan->second->getPassword(); - std::stringstream maxClient; - maxClient << itChan->second->getMaxClient(); - args += " Max Client: " + maxClient.str(); - it->sendMessageFd(RPL_MODE(it->getPrefix(), tokenArr[1], "+" + itChan->second->getChannelMods(), args)); //Channel mod infosu gidiyor. - return ; - } - - if (!isChannelAdmin(it, itChan->second)) - { - it->sendMessageFd(ERR_CHANOPRIVSNEEDED(it->getPrefix(), tokenArr[1])); - return ; - } - - bool isAdded = (tokenArr.at(2)[0] == '+' ? true : false); - char c = tokenArr[2][1]; - switch (c) - { - case 'k': - { - itChan->second->setPassword( isAdded ? tokenArr.at(3) : "\0" ); - itChan->second->sendMessageBroadcast(RPL_MODE(it->getPrefix(), tokenArr[1], (isAdded ? "+k" : "-k"), (isAdded ? tokenArr[3] : "\0"))); - itChan->second->setChannelMods( isAdded ? "+k" : "-k" ); - break; - } - - case 'l': - { - if (tokenArr.size() == 4 && atoi(tokenArr.at(3).c_str()) < itChan->second->getMaxClient()) // Channel'de kişi miktarından daha düşük bir değere atama yapmamak için konuldu - break ; - - itChan->second->setMaxClient(isAdded ? atoi(tokenArr.at(3).c_str()) : 0); - itChan->second->sendMessageBroadcast(RPL_MODE(it->getPrefix(), tokenArr[1], (isAdded ? "+l" : "-l"), (isAdded ? tokenArr[3] : ""))); - itChan->second->setChannelMods( isAdded ? "+l" : "-l" ); - break; - } - - case 'o': - { - Client* user = getClientByNickname(tokenArr.at(3)); - if (user != NULL) - { - if (isChannelUser(user, itChan->second)) - { - if (isAdded == true) - itChan->second->addAdmin(isAdded ? user : NULL); - else - itChan->second->removeAdmin(user); - itChan->second->sendMessageBroadcast(RPL_MODE(it->getPrefix(), tokenArr[1], (isAdded ? "+o" : "-o"), (isAdded ? tokenArr[3] : ""))); - } - else - it->sendMessageFd(ERR_USERNOTINCHANNEL(it->getPrefix(), tokenArr[3], tokenArr[1])); - } - else - it->sendMessageFd(ERR_NOSUCHNICK(it->getPrefix(), tokenArr[3])); - break; - } - - default: - { - it->sendMessageFd(ERR_UMODEUNKNOWNFLAG(it->getPrefix(), tokenArr[2])); - break; - } - } - -} - -// ************************************** -// IRC (Internet Relay Chat), internet üzerinden gerçek zamanlı metin tabanlı iletişim için bir protokoldür. IRC sunucuları, sunucunun ve kanallarının farklı yönlerini kontrol etmek ve yönetmek için çeşitli komut bayrakları kullanır. Bu komut bayrakları genellikle '/mode' komutuyla birlikte kullanılır ve bayrağın ayarlandığını veya ayarlanmadığını belirtmek için önünde bir artı ('+') veya eksi ('-') işareti bulunur. - -// Aşağıda bazı yaygın IRC sunucusu komut bayraklarının bir listesi verilmiştir: - -// - `+b` ve `-b`: Bu bayraklar, bir kullanıcı veya ana makine maskesine yasak koymak veya kaldırmak, böylece onların bir kanala katılmasını engellemek için kullanılır. -// - `+e` ve `-e`: Bu bayraklar, bir yasağın istisnasını ayarlamak veya kaldırmak için kullanılır ve bir kullanıcının veya ana bilgisayar maskesinin yasaklanmış olsa bile bir kanala katılmasına olanak tanır. -// - `+I` ve `-I`: Bu bayraklar, bir kanalın davet listesine bir kullanıcıyı veya ana bilgisayar maskesini eklemek veya kaldırmak için kullanılır; bu, yalnızca davetle olarak ayarlanmış olsa bile bu kişilerin kanala katılmasına olanak tanır. -// - `+k` ve `-k`: Bu bayraklar, kullanıcıların kanala katılabilmeleri için sağlamaları gereken kanal anahtarını (şifre) ayarlamak veya kaldırmak için kullanılır. -// - `+l` ve `-l`: Bu bayraklar bir kanalda kullanıcı limiti ayarlamak veya kaldırmak için kullanılır ve kanala katılabilecek maksimum kullanıcı sayısını kontrol eder. -// - `+m` ve `-m`: Bu bayraklar bir kanalda denetlenen modu ayarlamak veya kaldırmak için kullanılır; bu, yalnızca ses veya operatör ayrıcalıklarına sahip kullanıcıların kanala mesaj gönderebileceği anlamına gelir. -// - `+n` ve `-n`: Bu bayraklar bir kanalda harici mesaj yok modunu ayarlamak veya kaldırmak için kullanılır; bu, kanala yalnızca kanalda bulunan kullanıcıların mesaj gönderebileceği anlamına gelir. -// - `+o` ve `-o`: Bu bayraklar, bir kanaldaki kullanıcıya operatör ayrıcalıkları vermek veya bu ayrıcalıkları almak için kullanılır. -// - `+p` ve `-p`: Bu bayraklar bir kanalda özel modu ayarlamak veya kaldırmak için kullanılır; bu, kanalın sunucunun kanal listesinde gösterilmeyeceği anlamına gelir. -// - `+s` ve `-s`: Bu bayraklar bir kanalda gizli modu ayarlamak veya kaldırmak için kullanılır; bu, kanalın sunucunun kanal listesinde gösterilmeyeceği ve kullanıcıların kimlerin kanalda olduğunu göremeyeceği anlamına gelir. onlar da içinde olmadığı sürece kanal. -// - `+t` ve `-t`: Bu bayraklar bir kanalda konu kilitleme modunu ayarlamak veya kaldırmak için kullanılır; bu, yalnızca operatör ayrıcalıklarına sahip kullanıcıların kanalın konusunu değiştirebileceği anlamına gelir. diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/NICK.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/NICK.cpp deleted file mode 100644 index c125657..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/NICK.cpp +++ /dev/null @@ -1,62 +0,0 @@ -# include "../../includes/Server.hpp" - -/* - // `NICK``yuandre``USER``yuandre``yuandre``localhost``:Görkem``Sever` -*/ -void Server::nick( Client* it, std::vector tokenArr ) -{ - std::cout << YELLOW << "NICK" << END << std::endl; - - if (it->getIRCstatus() == HANDSHAKE) - { - if (tokenArr.size() == 2) - it->setNickname(tokenArr[1]); - else - Server::quitReason(it, "Erroneous nickname"); - return ; - } - - if (it->getIRCstatus() != AUTHENTICATED && it->getIRCstatus() != RENICK) - { - it->sendMessageFd(RPL_NOTICE(it->getPrefix(), it->getNickname(), "Client's status is insufficient.")); - return; - } - - std::string name = tokenArr.at(1); - for (size_t i = 0; i < name.size(); ++i) - { - if (!isprint(name[i])) - { - it->sendMessageFd(ERR_ERRONEUSNICKNAME(it->getPrefix(), name)); - return ; - } - } - - if (name[0] == '#' || name.size() > 16) // saçma bir nick girme işlemi gerçekleşirse önlemek için. // kullanıcı adının başında # olamaz. - it->sendMessageFd(ERR_ERRONEUSNICKNAME(it->getPrefix(), name)); // Client'e uygun olmayan kullanıcı adına sahip olduğu bilgisini gönderiyoruz. Kayıtlı kullanıcıları ise sadece uyarmak için vardır. - else if (Server::getClientFdByNickname(name) != -1 && Server::getClientFdByNickname(name) != it->getFd()) // Aynı isme sahip bir client yoksa -1 döndürür. - it->sendMessageFd(ERR_NICKNAMEINUSE(name)); // Client, server'a kayıtlı aynı nick'e sahip bir kullanıcı varsa, bu ismi alamayacağını belirtmek için vardır. - else - { - if (it->getIRCstatus() == AUTHENTICATED) // Sadece kayıtlı kullancıların erişebileceği, nick değiştirme yeridir. - { - it->sendMessageFd(RPL_NICK(it->getPrefix(), name)); // Client'e kullanıcı adının değiştiği bilgisi verilir. - for (size_t i = 0; i < it->getRegisteredChannels().size(); ++i) - it->getRegisteredChannels()[i]->sendMessageBroadcast(it, RPL_NICK(it->getPrefix(), name)); // Bağlı olduğu tüm channelere isminin değiştiği bilgisi gidecek. - it->setNickname(name); // RPL_NICK kısmında eski kullanıcı adına ihtiyaç olduğundan dolayı (hangi kullanıcın adı, ne oldu?) en sona client'in nick'ini belirleme eklendi. - } - else if (it->getIRCstatus() == RENICK)// ilk bağlantıdaki client'ın adı aynı ise buraya girer. - { - std::stringstream ss; - ss << it->getPort(); - it->setNickname(name); - it->setIRCstatus(AUTHENTICATED); // Ilk bağlantı ile güvenli bir şekilde nick belirlendiyse kullanıcının kimlik doğrulaması ok sayılır. - if (it->getNickname().compare("ircBot") != 0) - it->sendWelcomeMessage(Server::welcomeServer()); // ilk bağlantı olduğundan dolayı, emoji mesajıdır - it->sendMessageFd(RPL_WELCOME(name, _serverName)); // ilk bağlantı olduğundan dolayı, selamlama mesajıdır - it->sendMessageFd(RPL_NOTICE(it->getPrefix() + ":" + ss.str() , it->getNickname(), "Client status is now: AUTHENTICATED.")); - it->sendMessageFd(RPL_NICK(it->getPrefix(), name)); // Client'e kullanıcı adının değiştiği bilgisi verilir. - it->sendMessageFd(RPL_MODE(it->getPrefix(), it->getNickname(), it->getClientMods(), "")); - } - } -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/PART.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/PART.cpp deleted file mode 100644 index 0ebaa00..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/PART.cpp +++ /dev/null @@ -1,58 +0,0 @@ -# include "../../includes/Server.hpp" - -/** - * @brief - * - * Irssi -> IRC Server - * Eger part komutu Irssi tarafindan ana dizindeyse; - * /part -> 12:03 -!- Irssi: Not enough parameters given - * /part asdf -> Message:>PART-asdf< - * Eger part komutunu Channel'in icerisinde yazarsak; - * /part -> Message:>PART-#asdf< - * /part See ya -> Message:>PART-#asdf :See ya< - * - * Response Example>:WiZ!jto@tolsun.oulu.fi PART #playzone :I lost< - * - * // Message:>PART-#asdf :Lorem ipsum naber ehe.< - * @param it - * @param tokenArr - */ -void Server::part( Client* it, std::vector tokenArr ) -{ - std::cout << YELLOW << "PART" << END << std::endl; - - if (it->getIRCstatus() != AUTHENTICATED && it->getIRCstatus() != DISCONNECTED) // DC neden var: irssi kendisi aktif değilken otomatik çıkıyor, yani part komutunu kullanıyor - { - it->sendMessageFd(RPL_NOTICE(it->getPrefix(), it->getNickname(), "Client's status is insufficient.")); - return ; - } - - if (it->isRegisteredChannel(tokenArr.at(1)) == true) // Client tarafından belirlenen channel ismi var mı kontrol ediliyor, '/part #asdf' - { - Channel *chan = _channels[tokenArr[1]]; // Ayrılış gerçekleştirdiği channel'ın pointer'ı tutuluyor. - std::string msg = ""; - if (tokenArr.size() > 2) // Client, Channel'den ayrılırken, Channel'e kullancının ayrıldığı bilgisi gönderildiği için ve bu mesajda ayrılış nedenide olduğundan dolayı bu kısımda 'ayrılma nedeni' kontrol edilmektedir. - msg = Server::combineMessage(2, tokenArr); // Gelen mesajlar splitlendiğinden dolayı birleştirilmek zorundadır. - // it->sendMessageFd(RPL_PART(it->getPrefix(), tokenArr[1], msg)); // Client'tın kanaldan ayrılması için eklenmiştir. - chan->sendMessageBroadcast(RPL_PART(it->getPrefix(), tokenArr[1], msg)); // Client, kanaldan ayrılırken channel'daki herkese ayrılış mesajı göndermelidir 'BEN_ [~AHMET@176.88.10.20] has left #42kocaeli []' - chan->removeClient(it); // Client, channel'dan ayrıldığından dolayı, channel'den o kullanıcı bilgisi kaldırılmalıdır. - chan->removeAdmin(it); // Client, channel'dan ayrıldığı zaman adminlik yetkisi varsa kaybediyor. - it->unregisterChannel(chan); // Client'ta bulunan channel bilgisinden channel kaldırılmalıdır. - if (chan->getClientCount() == 0) // Eğerki channel'daki son kişi ise, channel silinmelidir. - Server::removeChannel(chan->getName()); - else if (chan->getClientCount() == 1 && chan->searchClient(this->getClientByNickname("ircBot")) != NULL) // Channel'da 1 kişi kaldıysa ve bot ise silinmelidir. - { - Client *bot = Server::getClientByNickname("ircBot"); - bot->sendMessageFd(RPL_PART(bot->getPrefix(), tokenArr[1], std::string("I can't stand being alone!"))); - bot->unregisterChannel(chan); - Server::removeChannel(chan->getName()); - } - else if (Server::isChannelAdmin(it, chan) == true) // Eğerki channel'dan ayrılan kişi admin ise, - { - chan->addAdmin(chan->_channelClients[0]); // Adminlik channele kayıtlı olan bir sonraki kişiye verilir. - chan->sendMessageBroadcast(RPL_MODE(it->getPrefix(), tokenArr[1], "+o", chan->_channelClients[0]->getNickname())); - } - } - else // Eğer o isme sahip bir channel yoksa hata döndürülüyor. - it->sendMessageFd(ERR_NOSUCHCHANNEL(it->getPrefix(), tokenArr[1])); -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/PASS.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/PASS.cpp deleted file mode 100644 index 1465d7c..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/PASS.cpp +++ /dev/null @@ -1,23 +0,0 @@ -# include "../../includes/Server.hpp" - -/* - // `PASS``asdf``NICK``yuandre``USER``yuandre``yuandre``localhost``:Görkem``Sever` -*/ -void Server::pass( Client* it, std::vector tokenArr ) -{ - std::cout << YELLOW << "PASS" << END << std::endl; - - if (it->getIRCstatus() != HANDSHAKE) - { - it->sendMessageFd(RPL_NOTICE(it->getPrefix(), it->getNickname(), "Client's status is insufficient.")); - return ; - } - - if (!tokenArr.empty() && !tokenArr.at(0).compare("PASS")) - if (!tokenArr.at(1).compare(this->_password)) - it->setPasswordStatus(); - else - Server::quitReason(it, "Password is wrong!"); - else - Server::quitReason(it, "Password is empty!"); -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/PING.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/PING.cpp deleted file mode 100644 index 0fa465b..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/PING.cpp +++ /dev/null @@ -1,9 +0,0 @@ -# include "../../includes/Server.hpp" - -void Server::ping( Client* it, std::vector tokenArr ) // OK -{ - if (!tokenArr.at(1).compare(it->getNickname()) - || !tokenArr[1].compare(this->_host)) - it->sendMessageFd(ERR_NEEDMOREPARAMS(it->getNickname(), "PING")); - it->sendMessageFd(RPL_PING(it->getNickname(), tokenArr[1])); -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/PRIVMSG.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/PRIVMSG.cpp deleted file mode 100644 index 8d1caf9..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/PRIVMSG.cpp +++ /dev/null @@ -1,52 +0,0 @@ -# include "../../includes/Server.hpp" - -/* -// in the channel: Message:>PRIVMSG-#ASDF :Ben deli değilim.< - tokenArr[0] -> Command Name -> "PRIVMSG" - tokenArr[1] -> Channel Name -> #ASDF - tokenArr[2] -> First Message -> :Ben - tokenArr[3] -> Second Message -> deli - tokenArr[4] -> Third Message -> değilim. --> Channel dışında, "/msg #ASDF Ben deli değilim." şeklindeki kullanımı, channel'e mesaj gönderecektir. - -// out the channel: Message:>PRIVMSG-akaraca :Ben deli değilim.< - tokenArr[0] -> Command Name -> "PRIVMSG" - tokenArr[1] -> Nick Name -> akaraca - tokenArr[2] -> First Message -> :Ben - tokenArr[3] -> Second Message -> deli - tokenArr[4] -> Third Message -> değilim. - -// Örnek: ":John!john@example.com PRIVMSG #channel :Merhaba, nasılsınız?" - -*/ -void Server::privmsg( Client* it, std::vector tokenArr ) -{ - std::cout << YELLOW << "PRIVMSG" << END << std::endl; - - if (it->getIRCstatus() != AUTHENTICATED) - { - it->sendMessageFd(RPL_NOTICE(it->getPrefix(), it->getNickname(), "Client's status is insufficient.")); - return ; - } - - std::string msg = Server::combineMessage(2, tokenArr); - if (tokenArr.at(1)[0] == '#') // Channel içinde gönderilen mesajı temsil ediyor. - { - if (it->isRegisteredChannel(tokenArr[1]) == true) // belirtilen isimde channel varsa, - this->_channels[tokenArr[1]]->sendMessageBroadcast(it, RPL_PRIVMSG(it->getPrefix(), tokenArr[1], msg)); - else // belirtilen isimde channel yoksa hata döndürmeliyiz. - it->sendMessageFd(ERR_NOSUCHCHANNEL(it->getPrefix(), tokenArr[1])); - } - else //Channel dışında doğrudan kullanıcıya atılan mesajı temsil ediyor. - { - Client *destClient = Server::getClientByNickname(tokenArr[1]); - if (destClient != NULL) - { - destClient->sendMessageFd(RPL_PRIVMSG(it->getPrefix(), tokenArr[1], msg)); - // Mesaj göndereceğimiz client'tı bulup onun client'ında sendMessageFd'yi çalıştırıyoruz. - // Eğer kendi mesajı gönderenin clien'tinden yaparsak, 2 mesaj kendisine göndermiş olacak, çünkü IRC client zaten komutu girdiğimiz anda kendisinide yazmaktadır. - } - else // kişi yoksa hata döndürmelidir. - it->sendMessageFd(ERR_NOSUCHNICK(it->getPrefix(), tokenArr[1])); - } -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/QUIT.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/QUIT.cpp deleted file mode 100644 index 04abddc..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/QUIT.cpp +++ /dev/null @@ -1,29 +0,0 @@ -# include "../../includes/Server.hpp" - -/* - // :syrk!kalt@millennium.stealth.net QUIT :Gone to have lunch -*/ -void Server::quit( Client* it, std::vector tokenArr ) -{ - std::cout << YELLOW << "QUIT" << END << std::endl; - Server::serverInfo(); - Server::leaveAllChannel(it); - std::cout << "Connection closed by client " << it->getHostname() << ":" << it->getPort() << std::endl; - it->setIRCstatus(DISCONNECTED); - it->sendMessageFd(RPL_QUIT(it->getPrefix(), tokenArr.at(0))); - it->sendMessageFd(RPL_PONG(it->getPrefix(), it->getHostname())); - - // for (size_t i = 0; i < _pollfds.size(); i++) - // { - // if (it->getFd() == _pollfds[i].fd) - // { - // it->sendMessageFd(RPL_QUIT(it->getPrefix(), tokenArr[0])); - // close(it->getFd()); - // Server::removeClient(it->getFd()); - // close(_pollfds[i].fd); - // _pollfds.erase(_pollfds.begin() + i); - // break; - // } - // } - // Server::serverInfo(); -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/TOPIC.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/TOPIC.cpp deleted file mode 100644 index 53b5035..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/TOPIC.cpp +++ /dev/null @@ -1,32 +0,0 @@ -# include "../../includes/Server.hpp" - -/* - /topic #channel :Damnn, moon is shining -*/ -void Server::topic( Client* it, std::vector tokenArr ) -{ - std::cout << YELLOW << "TOPIC" << END << std::endl; - if (it->getIRCstatus() != AUTHENTICATED) - { - it->sendMessageFd(RPL_NOTICE(it->getPrefix(), it->getNickname(), "Client's status is insufficient.")); - return ; - } - - if (tokenArr.at(1)[0] != '#') - tokenArr[1] = "#" + tokenArr[1]; - - itChannels itChannel = _channels.find(tokenArr[1]); - if (itChannel != _channels.end()) - { - if (Server::isChannelAdmin(it, itChannel->second)) - { - if (tokenArr.at(2)[0] == ':') - tokenArr[2].erase(0, 1); - itChannel->second->sendMessageBroadcast(RPL_TOPIC(it->getPrefix(), tokenArr[1], Server::combineMessage(2, tokenArr))); - } - else - it->sendMessageFd(ERR_CHANOPRIVSNEEDED(it->getPrefix(), tokenArr[1])); - } - else - it->sendMessageFd(ERR_NOSUCHCHANNEL(it->getPrefix(), tokenArr[1])); // Channel yoksa hata döndürülür. -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/USER.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/USER.cpp deleted file mode 100644 index ef2c47b..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/USER.cpp +++ /dev/null @@ -1,56 +0,0 @@ -# include "../../includes/Server.hpp" - -/* -//"USER akaraca akaraca localhost :Ahmet Karaca" komutu aşağıdaki anlamı taşır: -//Kullanıcı Adı (Username): "akaraca" -//Nick Adı (Nickname): "akaraca" -//Host Adı (Hostname): "localhost" (genellikle boş bırakılır) -//Gerçek İsim (Realname): "Ahmet Karaca" -// /set nick ... -// /set user_name ... -// /set hostname ... -// /set real_name ... -*/ -void Server::user(Client* it, std::vector tokenArr ) -{ - std::cout << YELLOW << "USER" << END << std::endl; - - if (it->getIRCstatus() != HANDSHAKE) // User komutu sadece tanışma kısmında kullanılmalıdır - { - it->sendMessageFd(RPL_NOTICE(it->getPrefix(), it->getNickname(), "Client's status is insufficient.")); - // Server::quitReason(it, "Client's status is insufficient!"); - return ; - } - - if (tokenArr.size() < 5) // bağlanan kullanıcının yeterli USER verisi yoksa server'dan atılır. - { - Server::quitReason(it, "Not enough parameters for USER command."); - return ; - } - - if (it->getPasswordStatus() == false) - { - Server::pass(it, std::vector()); - return; - } - - it->setUsername(tokenArr[1]); - std::cout << "Username:>" << it->getUsername() << std::endl; - - std::cout << "Nickname:>" << it->getNickname() << std::endl; - - std::cout << "Hostname:>" << it->getHostname() << std::endl; // '/set hostname' ile değiştirilse bile client'in ilk bağlantısında hostname atanmış oluyor. - - if (tokenArr[4][0] == ':') - tokenArr[4].erase(0, 1); // token[4] token4'un basindaki : kaldırır - for (size_t i = 5; i < tokenArr.size(); i++) - tokenArr[4].append(" " + tokenArr[i]); // realname boş olabilir veya birden fazla argümana sahip olabilir deneyin: /set real_name A B C D E F - it->setRealname(tokenArr[4]); - std::cout << "Realname:>" << it->getRealname() << std::endl; - - it->setIRCstatus(RENICK); - std::vector arr; - arr.push_back("NICK"); - arr.push_back((it->getNickname().empty() ? tokenArr[1] : it->getNickname())); - Server::nick(it, arr); -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/WHO.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/WHO.cpp deleted file mode 100644 index 2fa988b..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/WHO.cpp +++ /dev/null @@ -1,72 +0,0 @@ -# include "../../includes/Server.hpp" - -/* - //Channel içindeyken /who yazınca bu çıktıyı veriyor, ana sayfaya. - - "/who asdf" yazarsan, asdf'nin başında # olmadığı içni ele alma. - "/who #asdf" ise, asdf channelini ara ve kullancıların bilgilerini bastır. - "/who #A #B #C" şeklindeki bir yapıda sadece #A ele alınacaktır. - 17:13 -!- #42kocaeli akaraca H 0 - ~akaraca@2d6b-1b29-411f-5a9-8db6.88.176.ip - [k2m15s08.42kocaeli.com.tr] - 17:13 -!- #42kocaeli gsever H@ 4 - ~gsever@2d6b-1b29-411f-5a9-8db6.88.176.ip [Gorkem - Sever] - 17:13 -!- End of /WHO list - - --> ERR_NOSUCHCHANNEL - --> RPL_WHOREPLY - --> RPL_ENDOFWHO - -*/ -void Server::who( Client* it, std::vector tokenArr ) -{ - std::cout << YELLOW << "WHO" << END << std::endl; - - if (it->getIRCstatus() != AUTHENTICATED) - { - it->sendMessageFd(RPL_NOTICE(it->getPrefix(), it->getNickname(), "Client's status is insufficient.")); - return ; - } - - if (tokenArr.at(1)[0] == '#') //kanal aramak için - { - itChannels itC = _channels.find(tokenArr[1]); // channeli bul. - if (itC != _channels.end()) // eğer channel varsa - { - Channel* itChanel = itC->second; - for (size_t i = 0; i < itChanel->_channelClients.size(); i++) - { - Client* client = itChanel->_channelClients[i]; - std::string isAdmin = ""; - if (itChanel->searchAdmin(client) != NULL) - isAdmin = "@"; - it->sendMessageFd(RPL_WHOREPLY(it->getPrefix(), tokenArr[1], "~" + client->getUsername(), client->getHostname(), _serverName, client->getNickname(), isAdmin, "0", client->getRealname())); - // @ -> kullanıcının operator olduğunu temsil ediyor. - // "0" ise kullanıcının o anki sunucu üzerinden mesajlaştığını ifade eder. - - // * abc H 3 - // "H 3" ifadesi, kullanıcının "abc" takma adına sahip olduğunu ve sunucu ile arasında 3 "hop" olduğunu belirtir. Yani, bu kullanıcı ile mesajlar üç aracı sunucu aracılığıyla iletilmiştir. - } - it->sendMessageFd(RPL_ENDOFWHO(it->getPrefix(), tokenArr[1])); - } - else // channel yoksa hata döndür. - it->sendMessageFd(ERR_NOSUCHCHANNEL(it->getPrefix(), tokenArr[1])); // #x: No such channel - } - else // Burada sadece serverda arama yaptığımız için admin işaretine gerek yok?? - { - // Server'da kullanıcıyı aramak için yapılıyor. - // Channel bilgisi "*" şeklinde gözüküyor. - // Aradağı kişi yoksa herhangi bir çıktı vermiyor sadece End of /WHO list çıktısı bulunuyor. - // 09:56 -!- * akaraca H 3 ~akaraca@bbdb-4a67-88a1-bfa9-1d6d.190.78.ip [ahmet karaca] - // 09:56 -!- End of /WHO list - // "/who akaraca X Ben" şeklinde bir girdi olsada sadece akaraca hakkında bilgi veriliyor. - int fd = Server::getClientFdByNickname(tokenArr[1]); - if (fd != -1) - { - Client *client = _clients.at(fd); - it->sendMessageFd(RPL_WHOREPLY(it->getPrefix(), "*", "~" + client->getUsername(), client->getHostname(), _serverName, client->getNickname(), "","0", client->getRealname())); - } - it->sendMessageFd(RPL_ENDOFWHO(it->getPrefix(), "*")); - } -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/WHOIS.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/WHOIS.cpp deleted file mode 100644 index bd35d75..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/commands/WHOIS.cpp +++ /dev/null @@ -1,42 +0,0 @@ -# include "../../includes/Server.hpp" - -/* - - 311 RPL_WHOISUSER - " * :" - 312 RPL_WHOISSERVER - " :" - 313 RPL_WHOISOPERATOR - " :is an IRC operator" - 317 RPL_WHOISIDLE - " :seconds idle" - 318 RPL_ENDOFWHOIS - " :End of /WHOIS list" - - BUNLARIN HEPSİ BURADA GÖNDERİLMELİ -*/ -void Server::whois( Client* it, std::vector tokenArr ) -{ - std::cout << YELLOW << "WHOIS" << END << std::endl; - - if (it->getIRCstatus() != AUTHENTICATED) - { - it->sendMessageFd(RPL_NOTICE(it->getPrefix(), it->getNickname(), "Client's status is insufficient.")); - return ; - } - - int fd = Server::getClientFdByNickname(tokenArr.at(1)); - if (fd != -1) - { - Client *dest = _clients.at(fd); - std::stringstream ss; - ss << dest->getPort(); - it->sendMessageFd(RPL_WHOISUSER(it->getPrefix(), dest->getNickname(), dest->getUsername(), dest->getHostname(), ss.str(), dest->getRealname())); // Aranan kullanıcı hakkında bilgiyi yazdırır - it->sendMessageFd(RPL_WHOISSERVER(it->getPrefix(), this->_serverName)); - if (dest->getRegisteredChannels().size() != 0) - it->sendMessageFd(RPL_WHOISCHANNELS(it->getPrefix(), dest->getNickname(), Server::getRegisteredChannels(dest))); - it->sendMessageFd(RPL_ENDOFWHOIS(it->getPrefix(), dest->getNickname())); // Arama işleminin bittiğini ifade eder. - } - else - it->sendMessageFd(ERR_NOSUCHNICK(it->getPrefix(), tokenArr[1])); // bu hata mesajı sonrasında whowas döndürüyor //ekrana herhangi bir çıktı vermiyor, whowas döndürdüğünden dolayı sanırım -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/main.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/main.cpp deleted file mode 100644 index 2aa3a20..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/main.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/** - * @file main.cpp - * @author Ahmet KARACA (akaraca), Görkem SEVER (gsever) - * @brief - * @version 0.1 - * @date 2023-09-16 - * - * @copyright Copyright (c) 2023 - * - * @link https://docs.racket-lang.org/irc/index.html#%28def._%28%28lib._irc%2Fmain..rkt%29._irc-set-nick%29%29 - * @link https://www.irchelp.org/protocol/rfc/chapter6.html - * @link https://modern.ircdocs.horse/#rplliststart-321 - * @link https://www.rfc-editor.org/rfc/rfc2812#section-3.2.6 - * @link https://ircv3.net/specs/extensions/capability-negotiation.html - * @link https://dd.ircdocs.horse/refs/commands/part - * @link https://datatracker.ietf.org/doc/html/rfc2812#section-3.1.5 - * @link https://www.alien.net.au/irc/irc2numerics.html - * @link https://irssi.org/documentation/help/dcc/ - * @link https://www.youtube.com/watch?v=JpLwB14L2Rk&ab_channel=TallPaulTech - * @link https://www.youtube.com/watch?v=njKv66miR80&list=PL5tDlMcZytRqvYbDWLoayxAkUcHsOxX_p&index=9 - * @link https://beej.us/guide/bgnet/html/split/ - */ -#include "../includes/Server.hpp" - -/** - * @brief Main function. :D - * - * Server sample: ./ircserv - * Client sample: irssi -> /connect localhost 8888 asdf - * telnet localhost 8080 - * nc localhost 8080 - * localhost:8080 - * - * If you watch (MacOs): nettop -m tcp - * - * If you connect with 'nc' or 'telnet', you have to write in this order. - * $> CAP END - * $> PASS 1 - * $> NICK AHMET - * $> USER AHMET akaraca localhost :Ahmet Karaca - * - * If you want to transfer file, you must use 'irssi' client; - * For send; - * /dcc send TEST_ ./Desktop/1.txt - * For get; - * /dcc get TEST 1.txt /home/akaraca/Desktop - * - * @fn start(): Starting the all server. - * @fn what(): Writes the meaning of the exception. - * - * @param argc: Server port number. - * @param argv: Server password. - * @return int - */ -int main( int argc, char **argv ) -{ - try - { - Server Server(argc, argv); - Server.start(); - } - catch (std::exception &e) - { - std::cerr << e.what() << std::endl; - return (EXIT_SUCCESS); - } -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/serverSocket.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/serverSocket.cpp deleted file mode 100644 index 0c66cc5..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/serverSocket.cpp +++ /dev/null @@ -1,95 +0,0 @@ -#include "../includes/Server.hpp" - -/** - * @brief Opening a socket for Server. - * - * @fn socket(); Socket for - * LIBRARY: - * PARAM: AF_INET: Address Family IPv4. Internetwork: UDP, TCP, etc. - * PARAM: SOCK_STREAM: For TCP. - * PARAM: '0': Automatically choose the appropriate protocol. - * @fn strerror(); Returns a pointer to an error message string. - * It searches an internal array for the error number errnum and - * returns a pointer to the corresponding error message string. - */ -void Server::openSocket( void ) -{ - this->_serverFd = socket(AF_INET, SOCK_STREAM, 0); - if (this->_serverFd < 0) - throw std::runtime_error("Error while opening socket: " + std::string(strerror(errno))); - std::cout << YELLOW "Socket opened." END << std::endl; -} - -/** - * @brief Creating socket's address-family. - * - * TR: - * Bind(), bir soketi belirtilen yerel adrese bağlamak için kullanılır. - * Listen(), bir soketin bağlantıları kabul etmeye hazır olduğunu - * belirtmek için kullanılır. - * - * EN: - * Bind() is used to bind a socket to the specified local address. - * - * PARAM: INADDR_ANY: Bind all interfaces. - * If you wish to bind your socket to localhost only, the syntax would be - * my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1");. - * - * @fn htons(): Converts the unsigned short integer this->_port - * from host byte order to network byte order. - * @fn memset(); Allocating memory for serverAddress. - * Setting 0 &serverAddress's sizeof() bytes. - * @fn bind(); Assigns &serverAddress to sockfd address. - * @fn close(); Closing server's fd. - * @fn strerror(); Returns a pointer to an error message string. - * It searches an internal array for the error number errnum and - * returns a pointer to the corresponding error message string. - */ -void Server::createSocketAddress( void ) -{ - struct sockaddr_in serverAddress; - - memset((char *) &serverAddress, 0, sizeof(serverAddress)); - std::cout << YELLOW "Socket address created." END << std::endl; - - serverAddress.sin_family = AF_INET; - serverAddress.sin_addr.s_addr = INADDR_ANY; - serverAddress.sin_port = htons(this->_port); - std::cout << YELLOW "Socket address settings set." END << std::endl; - - if (bind(this->_serverFd, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0) - { - close(this->_serverFd); - throw std::runtime_error("Error while binding socket: " + std::string(strerror(errno))); - } - std::cout << YELLOW "Socket address bound." END << std::endl; -} - -/** - * @brief Joining queue limit. - * - * EN: - * Listen() is used to indicate that a socket is ready to accept connections. - * - * TR: - * Listen(), bir soketin bağlantıları kabul etmeye hazır olduğunu - * belirtmek için kullanılır. - * - * @fn listen(); - * PARAM: Accepting incoming connection request; - * PARAM: MAX_CONNECTIONS, maximum length of the queue of pending connections. - * @fn close(); Closing server's fd. - * @fn strerror(); Returns a pointer to an error message string. - * It searches an internal array for the error number errnum and - * returns a pointer to the corresponding error message string. - * - */ -void Server::startListening( void ) -{ - if (listen(this->_serverFd, MAX_CONNECTIONS) < 0) - { - close(this->_serverFd); - throw std::runtime_error("Error while listening on socket: " + std::string(strerror(errno))); - } - std::cout << YELLOW "Socket listening with a pending queue." END << std::endl; -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/sources/utils.cpp b/Additional/Helper_projects/Gorkem_Ahmet/sources/utils.cpp deleted file mode 100644 index 5830225..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/sources/utils.cpp +++ /dev/null @@ -1,294 +0,0 @@ -#include "../includes/Server.hpp" - -bool Server::check( int argc ) -{ - std::cout << YELLOW "Checking parameters..." END << std::endl; - if (argc != 3) - throw( std::invalid_argument(RED "Error: Invalid Argument Count\n" - "Usage: './ircserv '" END) ); - return (true); -} - -unsigned short Server::port( std::string port ) -{ - // for: ' $> ./ircserv "" 1234 ' - // ' $> ./ircserv '' 1234 ' - if (port.empty()) - throw( std::invalid_argument(RED "Error: Invalid Port\n" - "Port cannot be empty." END) ); - - for (size_t i = 0; i < port.length(); ++i){ - if (!isdigit(port[i])){ - throw( std::invalid_argument(RED "Error: Invalid Port\n" - "Port must be a integer." END) ); - } - } - - unsigned short portVal = atoi(port.c_str()); - - // Port numaraları, özel ayrılmış bazı portlar dışında genellikle 0 ile 65535 arasında değer alır. - // Ancak, 0 ile 1023 arasındaki port numaraları "well-known ports" olarak adlandırılır ve genellikle sistem servisleri veya tanınmış protokoller tarafından kullanılır. - // Bu port numaralarının birçoğu belirli bir protokol veya servis tarafından rezerve edilmiştir. - // Bu nedenle, kullanıcı tarafından belirlenecek port numaralarının genellikle 1024'den başlaması tercih edilir. - if (portVal < 1024 || portVal > std::numeric_limits::max()) - throw( std::invalid_argument(RED "Error: Invalid Port\n" - "Port must be between 1024 and 65535." END) ); - return (portVal); -} - -std::string Server::password( std::string password ) -{ - // for: ' $> ./ircserv 1234 "" ' - // ' $> ./ircserv 1234 '' ' - if (password.empty()) - throw( std::invalid_argument(RED "Error: Invalid Password\n" - "Password cannot be empty." END) ); - std::cout << GREEN "Parameters okay." END << std::endl; - return (password); -} - -void Server::initCommands( void ) -{ - t_cmdFunc["CAP"] = &Server::cap; - t_cmdFunc["JOIN"] = &Server::join; - t_cmdFunc["NICK"] = &Server::nick; - t_cmdFunc["PASS"] = &Server::pass; - t_cmdFunc["QUIT"] = &Server::quit; - t_cmdFunc["USER"] = &Server::user; - t_cmdFunc["PRIVMSG"] = &Server::privmsg; - t_cmdFunc["PING"] = &Server::ping; - t_cmdFunc["PART"] = &Server::part; - t_cmdFunc["MODE"] = &Server::mode; - t_cmdFunc["LIST"] = &Server::list; - t_cmdFunc["INFO"] = &Server::info; - t_cmdFunc["WHO"] = &Server::who; - t_cmdFunc["WHOIS"] = &Server::whois; - t_cmdFunc["KICK"] = &Server::kick; - t_cmdFunc["TOPIC"] = &Server::topic; -} - -/** - * @brief Adds a new pollfd object to the Server class. - * - * @fn std::vector::push_back(); Adds a new pollfd in container array. - * - * @param fd The file descriptor to be added. - * @param events The events to be added. - * @param revents The events that occurred. - */ -void Server::addToPollfds( int fd, short events, short revents ) -{ - pollfd newPoll; - - newPoll.fd = fd; - newPoll.events = events; - newPoll.revents = revents; - this->_pollfds.push_back(newPoll); -} - -/** - * @brief Splits a message into tokens based on a given delimiter(\\r\\n) - * and stores them in a std::map. - * - * @fn std::string::find(); If find this delimeter; return first - * delimeter index. If not find this delimeter; return std::npos; - * @fn std::string::substr(); Getting start location to length. - * Example -> "helloo" -> .substr(2, 3); -> "llo". - * @fn std::string::size(); Returns the length of the string, - * in terms of bytes. - * @fn std::string::erase(); Erases part of the string, - * reducing its length. - * @fn std::toupper(); Converting a character to uppercase. - * @fn std::string::insert(); Inserts additional characters into - * the string right before the character indicated by pos (or p). - * @fn std::make_pair - * - * @param delimeter The delimiter used to split the message. - * @param message The message to be split. - * @return std::map A map containing the tokens as key-value pairs. - */ -std::map\ - Server::splitMessage(std::string delimeter, std::string message ) -{ - std::map tokens; - size_t pos = 0; - - // CAP LS\r\nNICK gsever\r\nUSER A B C D E F G asdf\r\n - while ((pos = message.find(delimeter)) != std::string::npos) - { - int posFirst = message.find(' '); - - std::string firstWord = message.substr(0, posFirst); - // If we write 'INFO' last index have '\n' so remove '\r' and '\n' characters from the first word. - for (size_t i = 0; i < firstWord.size(); ++i) - { - if (firstWord[i] == '\r' || firstWord[i] == '\n') - { - firstWord.erase(i, 1); - --i; // Decrement i since a character is erased. - } - } - // Convert the first word (command) to uppercase. - for (size_t i = 0; i < firstWord.size(); ++i) - firstWord[i] = std::toupper(firstWord[i]); - - // Split the message into command and arguments - // 1. Kısım: USER 2. Kısım: A B C D E F G asdf - //posFirst + 1; CAP'ten sonra gelene boşluğun indexi - //pos - posFirst - 1; "CAP LS\r\n" yapısında LS'i almak için LS'in uzunluğuna bulmaya ihtiyaç var, -1 ise \r'ı almak istemiyoruz. - if (posFirst != -1) - tokens.insert(std::make_pair(firstWord, message.substr(posFirst + 1, pos - posFirst - 1))); - else - tokens.insert(std::make_pair(firstWord, "")); // nc localhost için 'TEK' argüman için kopya durumu söz konusu oluyor, bunu engellemek için eklendi. 'Message:>B-b<' - message.erase(0, pos + delimeter.length()); - } - // Handle the case where the message comes without a command - if (!message.empty()) // Parsing unkown command anda netcat. - { - if (message[message.size() - 1] == '\n') - return (Server::splitMessage("\n", message)); - else - { - message.append("\n"); - return (Server::splitMessage("\n", message)); - //tokens.insert(std::make_pair("UNKNOWN", message)); - } - } - return (tokens); -} - -std::vector Server::cmdMessage( std::string message ) -{ - std::stringstream ss(message); - std::string token; - std::vector tokenArr; - - while (ss >> token) - tokenArr.push_back(token); - - // Print tokens. - std::cout << B_BLUE << "Tokens:>"; - for (size_t i = 0; i < tokenArr.size(); i++) - std::cout << "`" << tokenArr[i] << "`"; - std::cout << "<" << END << std::endl; - return (tokenArr); -} - -int Server::getClientFdByNickname( std::string name ) -{ - for (itClients it = this->_clients.begin(); it != _clients.end(); it++) - { - if (it->second->getNickname().compare(name) == 0 && it->second->getNickname().size() == name.size()) - return (it->second->getFd()); - } - return (-1); -} - -Client* Server::getClientByNickname( std::string name ) -{ - for (itClients it = this->_clients.begin(); it != _clients.end(); it++) - { - if (it->second->getNickname().compare(name) == 0 && it->second->getNickname().size() == name.size()) - return (it->second); - } - return (NULL); -} - -Client* Server::getClientByFd( int fd ) -{ - for (itClients it = this->_clients.begin(); it != this->_clients.end(); ++it) - { - if (it->second->getFd() == fd) - return (it->second); - } - return (NULL); -} - -std::string Server::getRegisteredChannels( Client* Client ) -{ - std::string channelString = ""; - - for (itChannels itC = this->_channels.begin(); itC != this->_channels.end(); ++itC) - { - if (this->isChannelAdmin(Client, itC->second)) - channelString += "@"; - if (this->isChannelUser(Client, itC->second)) - channelString += itC->second->getName(); - channelString += " "; - } - return (channelString); -} - -std::string Server::combineMessage( size_t i, std::vector vectorMessage ) -{ - std::string msg; - size_t size = vectorMessage.size(); - for (; i < size; i++) - { - if (i + 1 < size) - msg += vectorMessage[i] + " "; - else - msg += vectorMessage[i]; - } - return (msg); -} - -bool Server::isChannelAdmin(Client* client, Channel* channel) -{ - if (channel->searchAdmin(client) == NULL) - return (false); - return (true); -} - -bool Server::isChannelUser(Client* client, Channel* channel) -{ - if (channel->searchClient(client) == NULL) - return (false); - return (true); -} - -void Server::leaveAllChannel( Client* client ) -{ - size_t size = client->getRegisteredChannels().size(); - for (size_t i = size; i > 0; --i) // Quit ile ayrılan channel, kayıtlı olduğu channel'lardan ayrılmalıdır. - { - std::vector leaveChannel; - leaveChannel.push_back("PART"); - leaveChannel.push_back(client->getRegisteredChannels()[i - 1]->getName()); - leaveChannel.push_back(":QUIT"); - Server::part(client, leaveChannel); - } - client->clearRegisteredChannels(); -} - -std::string Server::welcomeServer( void ) -{ - std::string msg; - - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡠⠖⠚⠉⠉⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⣶⠟⠋⠒⢦⡀⠀⠻⣄⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡼⢻⠃⠀\033[0;31m⣶⠆\033[m ⣷⠖⠒⠢⣌⠉⠉⠒⠒⠂⢤⣄⠀⠀⠀⠀⠀⠀⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡾⠁⠈⢧⠀⠀⠀⢸ \033[0;31m⣶⡄\033[m ⠀⢳⡀⡀⠀⢀⡼⠃⠀⠀⠀⠀⠀⠀⠀\n"; - msg += " ⠀⠀⠀⠀⢠⡶⣦⠀⠀⠀⠀⠀⠀⢸⠁⠀⠀⠀⠙⠒⣶⣾⡄ ⠀⠀⢨⡇⣷⣴⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"; - msg += " ⠀⣴⢻⣻⠿⠗⠛⠛⠉⠉⠉⠓⠒⠦⢤⣀⠀⠀⠠⠴⢿⡄⠙⠦⣤⣤⠤⠊⠐⠁⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"; - msg += " ⣼⣿⣿⡹⡄⣀⡤⠤⠤⠤⠤⢤⣀⡀⠀⠈⣿⣦⡀⠀⠀⠁⠀⠀⠀⠀⠀⠀⠀⠀⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"; - msg += " ⠹⣿⠈⠻⣏⠀⠀⠀⠀⠀⠀⠀⠀⠉⠓⢤⣿⢙⣷⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"; - msg += " ⠀⠹⣆⠀⠀⠙⠲⠦⢤⣤⣀⣀⣀⣀⣠⣼⠛⣿⢹⡇⠀⠀⠀⠀⠀⡀⠀⠀⠀⠀⢸⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"; - msg += " ⠀⠀⠙⢷⣄⠀⠀⠀⠀⠀⠀⠀⣴⡞⠓⠛⠀⠘⢿⣄⡀⠀⢀⣠⡾⠃⠀⠀⠀⠀⠈⣷⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"; - msg += " ⠀⠀⠀⠀⠉⠓⠦⣤⣀⣀⠀⠀⣨⣷⠀⠀⠀⠀⠀⠈⠉⠉⠉⠁⠀⠀⠀⠀⠀⠀⠀⢹⡄⠀⠀⠀⠀⠀⠀⠀⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠉⠉⣿⠛⠿⣤⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⠀⠀⠀⠀⠈⣷⠀⠀⠀⠀⠀⠀⠀⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⠀⠀⠀⠉⠛⠦⣄⣀⣀⣀⣠⠴⠚⠁⠀⠀⠀⠀⠀⢹⡇⠀⠀⠀⠀⠀⠀⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⡶⣿⠀⠀⠀⠀⠀⠀⠀⠀⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⢿⡄⠀⠀⠀⠀⠀⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢾⠀⢿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣴⠞⠛⠛⠷⠀⠀⠀⠀⠈⣿⠀⠀⠀⠀⠀⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣧⣸⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡃⠀⠀⠀⠀⠀⠀⠀⠀⠀⢻⡇⠀⠀⠀⠀⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⣾⢋⠉⠛⠛⢷⡀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣧⡀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠻⢶⣄⡀⠀⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠻⣿⡇⠀⠀⠀⠙⣦⣀⠀⠀⠀⠀⢀⣤⠤⠼⠿⣦⡄⠀⠀⠀⠀⠀⣶⣦⠀⠀⠉⢻⣄⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠳⢤⣤⡶⢿⣿⣬⡓⠶⠤⣤⣾⣥⠆⠀⠀⠀⠀⠀⠀⠀⢀⣴⠏⢸⡇⠀⠀⠀⣿⡀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠑⢦⡉⠻⠟⠳⡾⠛⠛⠿⣤⣇⣀⣀⣀⣤⠴⠞⠋⣁⣤⠞⠁⠀⠀⢀⣿⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣇⠀⠀⠀⠀⠉⠛⠛⠛⠛⠛⠛⠋⠉⠀⠀⠀⠀⠀⣼⠏⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠻⣆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣤⡾⠋⠀⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠓⠦⣤⣄⣀⣀⣀⣀⣀⣤⣤⣤⡶⠾⠛⠉⠀⠀⠀⠀\n"; - msg += " ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠉⠉⠉⠉⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n"; - return (msg); -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/.Makefile.high-resolution-process-bar b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/.Makefile.high-resolution-process-bar deleted file mode 100644 index dd31253..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/.Makefile.high-resolution-process-bar +++ /dev/null @@ -1,121 +0,0 @@ -# **************************************************************************** # -# # -# ::: :::::::: # -# Makefile :+: :+: :+: # -# +:+ +:+ +:+ # -# By: gsever you need change with your customize. !!!!!!! -NAME = ircserv - -# Flags for compile -CC = c++ -FLAGS = -Wall -Werror -Wextra -std=c++98 -Wshadow -O3 - -# All process use for compiling. -UNAME := $(shell uname -s) -NUMPROC := 8 - -OS := NULL - -INCLUDES_DIRECTORY = includes -INCLUDES = $(wildcard $(INCLUDES_DIRECTORY)/*.hpp) -SOURCES_DIRECTORY = sources -SOURCES = $(wildcard $(SOURCES_DIRECTORY)/*.cpp) -OBJECTS_DIRECTORY = objects -OBJECTS = $(addprefix $(OBJECTS_DIRECTORY)/, $(notdir $(SOURCES:%.cpp=%.o))) - -TOTAL_FILES := $(words $(SOURCES)) -CURRENT_FILES = 0 - -BLOCKS = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"] -PROGRESS_WIDTH = 50 - -define update_progress - CURRENT_FILES=$(shell echo $(($(CURRENT_FILES)+1))) - CURRENT_PROGRESS=$(shell echo $((($(CURRENT_FILES) * $(PROGRESS_WIDTH) * 8) / $(TOTAL_FILES)))) - FULL_BLOCKS=$(shell echo $(($(CURRENT_PROGRESS) / 8))) - PARTIAL_BLOCK=$(shell echo $(($(CURRENT_PROGRESS) % 8))) - printf "\r\033[K" - printf "$(GREEN)Compiled files:$(RESET) %d/%d [" $(CURRENT_FILES) $(TOTAL_FILES) - printf "%0.s█" $(shell seq 1 $(FULL_BLOCKS)) - printf "%s" "$(shell echo ${BLOCKS[$(PARTIAL_BLOCK)]})" - printf "%0.s " $(shell seq 1 $$(($(PROGRESS_WIDTH) - $(FULL_BLOCKS) - 1))) - printf "]" -endef - -define progress_done - printf "\n$(GREEN)Done!$(RESET)\n" -endef - -# COLORS --> 🟥 🟩 🟦 -BLACK = \033[0;30m -RED = \033[0;31m -GREEN = \033[0;32m -YELLOW = \033[0;33m -BLUE = \033[0;34m -PURPLE = \033[0;35m -CYAN = \033[0;36m -WHITE = \033[0;37m -END = \033[m -RESET = \033[0m -X = \033[m - -# COLORS BOLD--> B🟥 B🟩 B🟦 -B_CYAN = \033[1;36m -B_BLUE = \033[1;34m -B_YELLOW = \033[1;33m -B_GREEN = \033[1;32m -B_RED = \033[1;31m -B_RESET = \033[1m - -ifeq ($(UNAME), Linux) - NUMPROC := $(shell grep -c ^processor /proc/cpuinfo) - OS = "You are connected from -$(CYAN)$(UNAME)$(X)- 🐧 Welcome -$(CYAN)$(USER)$(X)- 😄!" -else ifeq ($(UNAME), Darwin) - NUMPROC := $(shell sysctl -n hw.ncpu) - OS = "You are connected from 42 school's iMac 🖥 ! Welcome $(CYAN)$(USER)$(X)" - ifeq ($(USER), yuandre) - OS = "You are connected from -$(CYAN)MacBook$(X)- 💻 Welcome -$(CYAN)$(USER)$(X)-!" - endif -endif - -.PHONY: all clean fclean re - -all: - @$(MAKE) $(NAME) -j $(NUMPROC) --no-print-directory -# @$(MAKE) $(NAME) - -# Compiling -$(OBJECTS_DIRECTORY)/%.o: $(SOURCES_DIRECTORY)/%.cpp | $(OBJECTS_DIRECTORY) - @$(CC) $(FLAGS) -c $< -o $@ - @$(call update_progress) - -$(NAME): $(OBJECTS) - @$(CC) $(FLAGS) $(OBJECTS) -o $(NAME) - @printf "\r\033[K" - @printf "%-50b %b" "$(GREEN)CREATED $(NAME)" "[FINISHED]$(X)\n" - @echo $(OS) Compiled with $(NUMPROC) cores! - @$(call progress_done) - -# Objects file creating -$(OBJECTS_DIRECTORY): - @mkdir -p $@ - @echo "$(NAME): $(GREEN)$@ was created$(RESET)" - -clean: - @rm -rf $(OBJECTS_DIRECTORY) - @echo "$(NAME): $(RED)$(OBJECTS_DIRECTORY) was deleted$(RESET)" - -fclean: clean - @rm -f $(NAME) - @echo "$(NAME): $(RED)$(NAME) was deleted$(RESET)" - -re: - @$(MAKE) fclean --no-print-directory - @$(MAKE) all --no-print-directory diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/.Makefile.process-bar b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/.Makefile.process-bar deleted file mode 100644 index c2368af..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/.Makefile.process-bar +++ /dev/null @@ -1,119 +0,0 @@ -# **************************************************************************** # -# # -# ::: :::::::: # -# Makefile :+: :+: :+: # -# +:+ +:+ +:+ # -# By: gsever you need change with your customize. !!!!!!! -NAME = ircserv - -# Flags for compile -CC = c++ -FLAGS = -Wall -Werror -Wextra -std=c++98 -Wshadow -O3 - -# All process use for compiling. -UNAME := $(shell uname -s) -NUMPROC := 8 - -OS := NULL - -INCLUDES_DIRECTORY = includes -INCLUDES = $(wildcard $(INCLUDES_DIRECTORY)/*.hpp) -SOURCES_DIRECTORY = sources -SOURCES = $(wildcard $(SOURCES_DIRECTORY)/*.cpp) -OBJECTS_DIRECTORY = objects -OBJECTS = $(addprefix $(OBJECTS_DIRECTORY)/, $(notdir $(SOURCES:%.cpp=%.o))) - -TOTAL_FILES := $(words $(SOURCES)) -CURRENT_FILES = 0 - -PROGRESS_CHAR = "▓" -EMPTY_CHAR = "░" -PROGRESS_WIDTH = 50 - -define update_progress - CURRENT_FILES=$(shell echo $$(($(CURRENT_FILES)+1))) - CURRENT_PROGRESS=$(shell echo $$((($(CURRENT_FILES) * $(PROGRESS_WIDTH)) / $(TOTAL_FILES)))) - printf "\r\033[K" - printf "$(GREEN)Compiled files:$(RESET) %d/%d [" $(CURRENT_FILES) $(TOTAL_FILES) - printf "%0.s$(PROGRESS_CHAR)" $(shell seq 1 $(CURRENT_PROGRESS)) - printf "%0.s$(EMPTY_CHAR)" $(shell seq 1 $$(($(PROGRESS_WIDTH) - $(CURRENT_PROGRESS)))) - printf "]" -endef - -define progress_done - printf "\n$(GREEN)Done!$(RESET)\n" -endef - -# COLORS --> 🟥 🟩 🟦 -BLACK = \033[0;30m -RED = \033[0;31m -GREEN = \033[0;32m -YELLOW = \033[0;33m -BLUE = \033[0;34m -PURPLE = \033[0;35m -CYAN = \033[0;36m -WHITE = \033[0;37m -END = \033[m -RESET = \033[0m -X = \033[m - -# COLORS BOLD--> B🟥 B🟩 B🟦 -B_CYAN = \033[1;36m -B_BLUE = \033[1;34m -B_YELLOW = \033[1;33m -B_GREEN = \033[1;32m -B_RED = \033[1;31m -B_RESET = \033[1m - -ifeq ($(UNAME), Linux) - NUMPROC := $(shell grep -c ^processor /proc/cpuinfo) - OS = "You are connected from -$(CYAN)$(UNAME)$(X)- 🐧 Welcome -$(CYAN)$(USER)$(X)- 😄!" -else ifeq ($(UNAME), Darwin) - NUMPROC := $(shell sysctl -n hw.ncpu) - OS = "You are connected from 42 school's iMac 🖥 ! Welcome $(CYAN)$(USER)$(X)" - ifeq ($(USER), yuandre) - OS = "You are connected from -$(CYAN)MacBook$(X)- 💻 Welcome -$(CYAN)$(USER)$(X)-!" - endif -endif - -.PHONY: all clean fclean re - -all: -# @$(MAKE) $(NAME) - @$(MAKE) $(NAME) -j $(NUMPROC) --no-print-directory - -# Compiling -$(OBJECTS_DIRECTORY)/%.o: $(SOURCES_DIRECTORY)/%.cpp | $(OBJECTS_DIRECTORY) - @$(CC) $(FLAGS) -c $< -o $@ - @$(call update_progress) - -$(NAME): $(OBJECTS) - @$(CC) $(FLAGS) $(OBJECTS) -o $(NAME) - @printf "\r\033[K" - @printf "%-50b %b" "$(GREEN)CREATED $(NAME)" "[FINISHED]$(X)\n" - @echo $(OS) Compiled with $(NUMPROC) cores! - @$(call progress_done) - -# Objects file creating -$(OBJECTS_DIRECTORY): - @mkdir -p $@ - @echo "$(NAME): $(GREEN)$@ was created$(RESET)" - -clean: - @rm -rf $(OBJECTS_DIRECTORY) - @echo "$(NAME): $(RED)$(OBJECTS_DIRECTORY) was deleted$(RESET)" - -fclean: clean - @rm -f $(NAME) - @echo "$(NAME): $(RED)$(NAME) was deleted$(RESET)" - -re: - @$(MAKE) fclean --no-print-directory - @$(MAKE) all --no-print-directory diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/State_diagram_for_server_and_client_model.png b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/State_diagram_for_server_and_client_model.png deleted file mode 100644 index 92474b3..0000000 Binary files a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/State_diagram_for_server_and_client_model.png and /dev/null differ diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/bot/bot.cpp b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/bot/bot.cpp deleted file mode 100644 index 52839a8..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/bot/bot.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include -#include -#include -#include -#include -#include - -int main() { - const char* server = "localhost"; - const int port = 1234; - - int sock = socket(AF_INET, SOCK_STREAM, 0); - if (sock == -1) { - std::cerr << "Socket creation failed." << std::endl; - return 1; - } - - struct hostent* server_info = gethostbyname(server); - if (!server_info) { - std::cerr << "Host lookup failed." << std::endl; - close(sock); - return 1; - } - - struct sockaddr_in server_address; - memset(&server_address, 0, sizeof(server_address)); - server_address.sin_family = AF_INET; - server_address.sin_port = htons(port); - memcpy(&server_address.sin_addr.s_addr, server_info->h_addr, server_info->h_length); - - if (connect(sock, (struct sockaddr*)&server_address, sizeof(server_address)) == -1) { - std::cerr << "Connection failed." << std::endl; - close(sock); - return 1; - } - - std::cout << "Connected to " << server << " on port " << port << std::endl; - - // Burada IRC sunucusuna mesaj gönderme ve mesajları alma işlemlerini ekleyebilirsiniz. - - close(sock); - return 0; -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/filetransfer/example.txt b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/filetransfer/example.txt deleted file mode 100644 index 552086f..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/filetransfer/example.txt +++ /dev/null @@ -1,5 +0,0 @@ -TEST - - -TEST 1234 -END diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/filetransfer/receiver.cpp b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/filetransfer/receiver.cpp deleted file mode 100644 index f2014a6..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/filetransfer/receiver.cpp +++ /dev/null @@ -1,84 +0,0 @@ -#include -#include -#include -#include -#include - -// c++ receiver.cpp && ./a.out -int main() { - const int port = 12345; // Alıcı port numarasını belirtin - - // Socket oluşturma - int sockfd = socket(AF_INET, SOCK_STREAM, 0); - if (sockfd == -1) { - std::cerr << "Socket oluşturma hatası." << std::endl; - return 1; - } - - // Bağlantı ayarları - struct sockaddr_in serverAddr; - serverAddr.sin_family = AF_INET; - serverAddr.sin_port = htons(port); - serverAddr.sin_addr.s_addr = INADDR_ANY; - - // Soketi bağlama - if (bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) { - std::cerr << "Soketi bağlama hatası." << std::endl; - close(sockfd); - return 1; - } - - // Bağlantı bekleniyor - if (listen(sockfd, 1) == -1) { - std::cerr << "Bağlantı bekleniyor hatası." << std::endl; - close(sockfd); - return 1; - } - - std::cout << "Alıcı hazır, bağlantı bekleniyor..." << std::endl; - - // Bağlantı kabul etme - struct sockaddr_in clientAddr; - socklen_t clientAddrLen = sizeof(clientAddr); - int clientSock = accept(sockfd, (struct sockaddr*)&clientAddr, &clientAddrLen); - if (clientSock == -1) { - std::cerr << "Bağlantı kabul etme hatası." << std::endl; - close(sockfd); - return 1; - } - - // Alınacak dosyanın adı - std::string fileName = "received_file.txt"; - - // Dosyayı oluştur ve verileri yaz - std::ofstream outFile(fileName, std::ios::binary); - if (!outFile) { - std::cerr << "Dosya oluşturma hatası." << std::endl; - close(clientSock); - close(sockfd); - return 1; - } - - char buffer[1024]; - ssize_t bytesRead; - while ((bytesRead = recv(clientSock, buffer, sizeof(buffer), 0)) > 0) { - outFile.write(buffer, bytesRead); - } - - if (bytesRead == -1) { - std::cerr << "Veri alma hatası." << std::endl; - outFile.close(); - close(clientSock); - close(sockfd); - return 1; - } - - // Dosya ve soketleri kapat - outFile.close(); - close(clientSock); - close(sockfd); - - std::cout << "Dosya alındı: " << fileName << std::endl; - - return 0; -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/filetransfer/sender.cpp b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/filetransfer/sender.cpp deleted file mode 100644 index 930484a..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/filetransfer/sender.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include -#include -#include -#include -#include - -// example.txt dosyası oluşturmayı unutmayın. -// c++ sender.cpp && ./a.out -int main() { - // Alıcı IP adresi ve port numarası - const char* receiverIP = "127.0.0.1"; // Alıcı IP adresini belirtin - const int receiverPort = 12345; // Alıcı port numarasını belirtin - - // Gönderilecek dosyanın adı - std::string fileName = "example.txt"; - - // Dosya açma - std::ifstream file(fileName, std::ios::binary); - if (!file) { - std::cerr << "Dosya açma hatası." << std::endl; - return 1; - } - - // Socket oluşturma - int sockfd = socket(AF_INET, SOCK_STREAM, 0); - if (sockfd == -1) { - std::cerr << "Socket oluşturma hatası." << std::endl; - return 1; - } - - // Bağlantı ayarları - struct sockaddr_in destAddr; - destAddr.sin_family = AF_INET; - destAddr.sin_port = htons(receiverPort); - inet_pton(AF_INET, receiverIP, &(destAddr.sin_addr)); - - // Alıcıya bağlanma - if (connect(sockfd, (struct sockaddr*)&destAddr, sizeof(destAddr)) == -1) { - std::cerr << "Alıcıya bağlanma hatası." << std::endl; - close(sockfd); - return 1; - } - - // Dosyayı oku ve gönder - char buffer[1024]; - while (!file.eof()) { - file.read(buffer, sizeof(buffer)); - ssize_t bytesRead = file.gcount(); - if (bytesRead <= 0) { - break; - } - ssize_t bytesSent = send(sockfd, buffer, bytesRead, 0); - if (bytesSent == -1) { - std::cerr << "Dosya gönderme hatası." << std::endl; - break; - } - } - - // Soket ve dosyayı kapat - close(sockfd); - file.close(); - - std::cout << "Dosya gönderildi." << std::endl; - - return 0; -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/gethostbyname/main.cpp b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/gethostbyname/main.cpp deleted file mode 100644 index 07239ce..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/gethostbyname/main.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include -#include -#include - -int main() { - //const char* host_name = "www.google.com"; - const char* host_name = "127.0.0.1"; - hostent* host_info = gethostbyname(host_name); - - if (host_info) { - in_addr** addr_list = reinterpret_cast(host_info->h_addr_list); - for (int i = 0; addr_list[i] != NULL; ++i) { - std::cout << "IP Address " << i + 1 << ": " << inet_ntoa(*addr_list[i]) << std::endl; - } -std::cout << "Client hostname: " << host_info->h_name << std::endl; - - } else { - std::cerr << "Couldn't resolve the hostname." << std::endl; - } - - return 0; -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/ip/ip.cpp b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/ip/ip.cpp deleted file mode 100644 index 84f02f0..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/ip/ip.cpp +++ /dev/null @@ -1,133 +0,0 @@ -// #include -// #include - -// int main() -// { -// int ipAddress; - -// ipAddress = system("ipconfig getifaddr en0"); -// std::cout << "ip:>" << ipAddress << "<" << std::flush; - -// // std::cout << system("ipconfig getifaddr en0") << "<" << std::endl << std::flush; -// return (0); -// } - - -// ************ IKINCI KISIM ************************************************************************ -// #include -// #include -// #include -// #include - -// int main() { -// char buffer[128]; -// std::string localIP; -// std::string publicIP; - -// #ifdef _WIN32 -// // Windows için ipconfig komutunu kullanarak local IP al -// std::system("ipconfig | findstr /R \"Ethernet adapter.*IPv4\""); -// #else -// // Unix/Linux için ifconfig komutunu kullanarak local IP al -// std::system("ifconfig | grep 'inet ' | awk '{print $2}'"); -// #endif - -// // httpbin.org servisini kullanarak public IP al -// std::system("curl ifconfig.me"); - -// return 0; -// } - -// ************* UCUNCU KISIM ****************************************************************** - -// #include -// #include -// #include -// #include - -// int main() { -// char buffer[128]; -// std::string localIP; -// std::string publicIP; - -// #ifdef _WIN32 -// // Windows için ipconfig komutunu kullanarak local IP al -// FILE* pipe = _popen("ipconfig | findstr /R \"Ethernet adapter.*IPv4\"", "r"); -// #else -// // Unix/Linux için ifconfig komutunu kullanarak local IP al -// FILE* pipe = popen("ifconfig | grep 'inet ' | awk '{print $2}'", "r"); -// #endif - -// if (!pipe) { -// std::cerr << "Hata: Komut çalıştırılamadı!" << std::endl; -// return -1; -// } - -// while (fgets(buffer, sizeof(buffer), pipe) != NULL) { -// localIP += buffer; -// } - -// #ifdef _WIN32 -// _pclose(pipe); -// #else -// pclose(pipe); -// #endif - -// // httpbin.org servisini kullanarak public IP al -// pipe = popen("curl ifconfig.me", "r"); - -// if (!pipe) { -// std::cerr << "Hata: Komut çalıştırılamadı!" << std::endl; -// return -1; -// } - -// while (fgets(buffer, sizeof(buffer), pipe) != NULL) { -// publicIP += buffer; -// } - -// #ifdef _WIN32 -// _pclose(pipe); -// #else -// pclose(pipe); -// #endif - -// std::cout << "Local IP: " << localIP << std::endl; -// std::cout << "Public IP: " << publicIP << std::endl; - -// return 0; -// } - -// ****************** DORDUNCU KISIM *********************************************** -#include -#include // For popen -#include // For fgets -#include - -std::string exec(const char* cmd) -{ - char buffer[128]; - std::string result = ""; - FILE* pipe = popen(cmd, "r"); - if (!pipe) { - throw std::runtime_error("popen() failed!"); - } - while (fgets(buffer, sizeof(buffer), pipe) != NULL) { - result += buffer; - } - pclose(pipe); - return result; -} - -int main() { - // const char* cmd = "ipconfig getifaddr en0"; // "en0" interface for Wi-Fi, "en1" for Ethernet - // std::string localIp = exec("ipconfig getifaddr en0"); - // std::string publicIp = exec("curl ifconfig.me"); - - char command[100] = "ipconfig getifaddr en0"; - execl("/bin/sh", "sh", "-c", command, (char *)0); - - // std::cout << "Local IP Address: " << localIp; - // std::cout << "Public IP Address: " << publicIp; - - return 0; -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/pollTimeTest/poll.cpp b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/pollTimeTest/poll.cpp deleted file mode 100644 index f879c2c..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/pollTimeTest/poll.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -int main() { - // Soket oluşturma - int serverSocket = socket(AF_INET, SOCK_STREAM, 0); - if (serverSocket < 0) { - std::cerr << "Error creating socket." << std::endl; - return 1; - } - - // Soket adresini ayarlama - struct sockaddr_in serverAddress; - memset(&serverAddress, 0, sizeof(serverAddress)); - serverAddress.sin_family = AF_INET; - serverAddress.sin_addr.s_addr = INADDR_ANY; - serverAddress.sin_port = htons(8080); - - // Soketi bağlama - if (bind(serverSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) < 0) { - std::cerr << "Error binding socket." << std::endl; - close(serverSocket); - return 1; - } - - // Soketi dinleme moduna geçirme - if (listen(serverSocket, 5) < 0) { - std::cerr << "Error listening on socket." << std::endl; - close(serverSocket); - return 1; - } - - std::cout << "Server is listening on port 8080..." << std::endl; - - // pollfd yapısı oluşturma - struct pollfd pollFds[1]; - pollFds[0].fd = serverSocket; - pollFds[0].events = POLLIN; - - //while (true) { - // poll işlemi (timeout süresi 1 saniye) - int pollResult = poll(pollFds, 1, -1); // 1000 ms (1 saniye) bekler - if (pollResult < 0) { - std::cerr << "Error in poll." << std::endl; - //break; - } - std::cout << ".."; - if (pollResult > 0) { - if (pollFds[0].revents & POLLIN) { - // Soketten gelen veriyi oku ve ekrana yazdır - char buffer[1024]; - int bytesRead = recv(serverSocket, buffer, sizeof(buffer), 0); - if (bytesRead < 0) { - std::cerr << "Error reading from socket." << std::endl; - //break; - } else if (bytesRead == 0) { - // Bağlantı kapandı - std::cout << "Client disconnected." << std::endl; - //break; - } else { - std::cout << "Received data: " << std::string(buffer, bytesRead) << std::endl; - } - } - } - //} - - // Soketi kapat - close(serverSocket); - - return 0; -} \ No newline at end of file diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/pthread/a.out b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/pthread/a.out deleted file mode 100755 index 64f379e..0000000 Binary files a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/pthread/a.out and /dev/null differ diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/pthread/thread.cpp b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/pthread/thread.cpp deleted file mode 100644 index dcce04c..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/pthread/thread.cpp +++ /dev/null @@ -1,51 +0,0 @@ -#include -#include -#include - -void* thread_function(void* arg) { - int thread_id = *(int*)arg; // Argümanı al - for (int i = 1; i <= 5; ++i) { - std::cout << "İş Parçacığı " << thread_id << " çalışıyor... Adım " << i << std::endl; - sleep(1); - } - std::cout << "İş Parçacığı " << thread_id << " tamamlandı." << std::endl; - return NULL; -} - -int main() { - const int num_threads = 3; - pthread_t threads[num_threads]; - - for (int i = 0; i < num_threads; ++i) { - int thread_id = i + 1; - int result = pthread_create(&threads[i], NULL, thread_function, &thread_id); - if (result != 0) { - std::cerr << "İş parçacığı oluşturma hatası" << std::endl; - return 1; - } - - // result = pthread_join(threads[i], NULL); - // if (result != 0) { - // std::cerr << "İş bekletme hatası" << std::endl; - // return 1; - // } - - result = pthread_detach(threads[i]); - if (result != 0) { - std::cerr << "İş parçacığını ayırma hatası" << std::endl; - return 1; - } - } - - // Ana iş parçacığı devam ediyor - // ... - - sleep(6); // Ana iş parçacığının bitmeden önce beklemesi için - - return 0; -} - -// pthread_create: Bu fonksiyon, yeni bir thread oluşturur. Fonksiyonun ilk parametresi, oluşturulan thread’in tanımlayıcısını (ID) tutacak bir değişkenin adresini alır. İkinci parametresi, thread’in özniteliklerini belirleyen bir yapıyı (attribute) alır. Üçüncü parametresi, thread’in çalıştıracağı fonksiyonu belirtir. Dördüncü parametresi ise, thread’in çalıştıracağı fonksiyona geçirilecek parametreleri belirtir1. -// pthread_join: Bu fonksiyon, belirtilen thread’in sonlanmasını bekler ve sonlandığında thread’in dönüş değerini alır. Fonksiyonun ilk parametresi, beklenen thread’in tanımlayıcısını (ID) alır. İkinci parametresi ise, thread’in dönüş değerini tutacak bir değişkenin adresini alır1. -// pthread_exit: Bu fonksiyon, çağrıldığı thread’i sonlandırır ve belirtilen dönüş değerini döndürür. Fonksiyonun tek parametresi, thread’in dönüş değerini belirtir1. -// pthread_detach: Bu fonksiyon, belirtilen thread’i ayrılmış (detached) olarak işaretler. Bir thread ayrıldığında, bu thread sonlandığında kaynakları otomatik olarak sistem tarafından geri alınır ve başka bir thread’in sonlanan thread ile birleşmesine (join) gerek kalmaz1. \ No newline at end of file diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/socket/main.c b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/socket/main.c deleted file mode 100644 index 15d199a..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/socket/main.c +++ /dev/null @@ -1,117 +0,0 @@ -# include -# include -# include -# include -# include -# include -# define PORT 8080 -// server'a bağlantı kurmak için: $> telnet 127.0.0.1 8080 -// bir server oluşturmak için gerekli olan fonksiyonlar: socket(), bind(), listen() ve accept() -int main() -{ - int server_fd, new_socket, valread; // dosya tanımlayıcıları ve veri uzunluğunu saklamak için kullanılacak değişkenlerdir. - struct sockaddr_in address; // IPv4 adresini ve port numarasını depolamak için kullanılan yapıdır. - int opt = 1; // soket seçeneklerini yapılandırmak için kullanılan bir değişkendir. - int addrlen = sizeof(address); // soket adresinin boyutunu tutar. - char buffer[1024] = { 0 }; // veri alışverişi için kullanılacak bir tampon dizisidir. - char* hello = "Hello from server\n"; // istemcilere gönderilecek mesajını içeren bir karakter dizisidir. - - // socket(); fonksiyonu bir socket oluşturur. - // 'AF_INET' adres ailesi olarak IPv4'ü belirtir. - // 'SOCK_STREAM' soket türü olarak TCP'yi belirtir. - // Oluşturulan soketin tanımlayıcısı server_fd değişkenine atanır. - // Eğer soket oluşturulamazsa, hata mesajı yazdırılır ve program EXIT_FAILURE ile sonlandırılır. - // socket()'in 3.parametresi fonksiyonun default olarak kullanıldığını belirtir. - if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { - perror("socket failed"); - exit(EXIT_FAILURE); - } - else - printf("%s fd:%d\n", "socket fd succesfuly created", server_fd); - - // Bu bölüm, oluşturulan soketin yapılandırılmasını ve bağlantı için gerekli adres bilgilerini ayarlamayı içerir. - // "SO_REUSEADDR" ve "SO_REUSEPORT" seçenekleri, sunucu soketinin zaten kullanımda olsa bile yeniden kullanılmasını sağlar. - // Bu, bağlantıları kaybetmeden yeniden başlatılabilen sunucular için kullanışlıdır. - // "SO_REUSEADDR" seçeneği, bir soketin zaten kullanımda olsa bile yeniden kullanılmasını sağlar. - // Bu, bağlantıları kaybetmeden yeniden başlatılabilen sunucular için kullanışlıdır. - // "SO_REUSEPORT" seçeneği, birden fazla soketin aynı bağlantı noktasında dinlemesini sağlar. - // Bu, yük dengeleyiciler ve diğer, trafiği birden çok sunucu arasında dağıtmak zorunda olan uygulamalar için kullanışlıdır. - // SOL_SOCKET seçeneği, soketlerle ilgili genel ayarları değiştirmek için kullanılır. - // &opt ve sizeof(opt) parametreleri, soket seçeneği değerini belirtmek için kullanılır. - if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { - perror("setsockopt"); - exit(EXIT_FAILURE); - } - else - printf("%s\n", "socket settings changed"); - - address.sin_family = AF_INET; // adres yapısının aile türünü (AF_INET, yani IPv4) belirtir. - address.sin_addr.s_addr = INADDR_ANY; // sunucunun herhangi bir ağ arabirimine bağlanabileceğini belirtir. Bu, sunucunun tüm ağ arabirimlerini dinlemesini sağlar. - address.sin_port = htons(PORT); // port numarasını yapılandırır. htons işlevi, "host byte order"ı (endianness) "network byte order"a dönüştürmek için kullanılır. Bu, port numarasının doğru şekilde iletilmesini sağlar. - - // Bu bölüm, oluşturulan soketi belirli bir adres ve port numarasına bağlamayı amaçlar. - // bind() işlemi, sunucunun belirli bir adresi ve portu dinlemeye başlamasını sağlar. - // İlk parametre, bağlamak istediğimiz soketin dosya tanımlayıcısı olan server_fd'yi içerir. - // İkinci parametre, bir struct sockaddr türüne dönüştürülen adres yapısını içerir. - // Üçüncü parametre, adres yapısının boyutunu belirtir. - // Eğer bu işlem başarılı bir şekilde gerçekleşmezse, sunucu gelen bağlantıları kabul edemeyeceği için çalışmaz. - if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) { - perror("bind failed"); - exit(EXIT_FAILURE); - } - else - printf("%s\n", "server is connecting"); - - // Bu bölüm, sunucunun gelen bağlantıları dinlemeye başlamasını sağlar. - // listen işlemi, sunucunun belirli bir soketi kullanarak gelen bağlantıları kabul edebilmesi için gerekli olan altyapıyı oluşturur. - // İlk parametre, dinlemek istediğimiz soketin dosya tanımlayıcısı olan server_fd'yi içerir. - // İkinci parametre, aynı anda kaç bağlantının sıraya girebileceğini belirten bir tam sayıdır. - // Bu değer genellikle backlog olarak adlandırılır ve sistem tarafından desteklenen maksimum değere sınırlanabilir. - if (listen(server_fd, 3) < 0) { - perror("listen"); - exit(EXIT_FAILURE); - } - else - printf("%s\n", "server is listening"); - - // Bu bölüm, sunucunun gelen bağlantıları kabul etmeyi ve yeni bir soket tanımlayıcısı oluşturarak bu bağlantıyı yönetmeyi amaçlar. - // accept işlemi, sunucunun bekleyen bağlantıları alarak bu bağlantılara yeni bir soket atar ve bu soketi kullanarak iletişim kurmasını sağlar. - // İlk parametre, dinlemekte olan soketin dosya tanımlayıcısı olan server_fd'yi içerir. - // İkinci parametre, bağlantıyı sağlayan istemcinin adres bilgisini almak için kullanılır. - // Üçüncü parametre, struct sockaddr türünde bir adres yapısının boyutunu tutar. - // Eğer accept işlemi başarılı bir şekilde gerçekleşirse, yeni bir soket tanımlayıcısı olan new_socket döner. - // Bu yeni soket, sunucunun gelen bağlantıyı yönetmesi için kullanılır. - // Eğer bir hata oluşursa, -1 döner. - if ((new_socket = accept(server_fd, (struct sockaddr*)&address, (socklen_t*)&addrlen)) < 0) { - perror("accept"); - exit(EXIT_FAILURE); - } - else - printf("%s\n", "server is accepting"); - - // Kabul edilen new_socket soketi üzerinden istemciden gelen veriyi buffer adlı karakter dizisine okur. - // 1024 burada okunacak maksimum bayt sayısını belirtir. - // Okunan bayt sayısı valread değişkenine atanır. - valread = read(new_socket, buffer, 1024); - - // buffer karakter dizisindeki okunan veriyi ekrana yazdırır. - // Yani, istemciden gelen veriyi sunucu ekranına basar. - printf("%s\n", buffer); - - // new_socket soketi üzerinden istemciye hello adlı karakter dizisini gönderir. - // strlen(hello) ifadesi, "Merhaba" mesajının uzunluğunu belirtir. - // 0 ise iletim sırasında kullanılan ek seçeneklerdir. - send(new_socket, hello, strlen(hello), 0); - - // Bu satır, "Merhaba" mesajının istemciye başarıyla gönderildiğini ekrana yazdırır. - printf("Hello message sent\n"); - - // Kabul edilen istemci soketini kapatır. - close(new_socket); - - // Sunucu soketinin hızlı ve düzgün bir şekilde kapatılmasını sağlar. - // server_fd soketi, dinleme yapısından çıkmak ve sunucuyu kapatmak için shutdown fonksiyonuyla işaretlenmelidir. - // SHUT_RDWR parametresi, hem okuma hem de yazma yollarının kapatılmasını belirtir. - shutdown(server_fd, SHUT_RDWR); - return 0; -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/socket_2/main.cpp b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/socket_2/main.cpp deleted file mode 100644 index 80fd610..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/socket_2/main.cpp +++ /dev/null @@ -1,80 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#define PORT 55555 -#define MAX_CONNECTIONS 5 -#define MAX_BUFFER 1024 - -int main() { - int serverSocket, clientSocket; - struct sockaddr_in serverAddr, clientAddr; - socklen_t clientAddrSize = sizeof(clientAddr); - char buffer[MAX_BUFFER]; - - // Create socket - serverSocket = socket(AF_INET, SOCK_STREAM, 0); - if (serverSocket == -1) { - perror("Error creating socket"); - return 1; - } - - // Bind - serverAddr.sin_family = AF_INET; - serverAddr.sin_port = htons(PORT); - serverAddr.sin_addr.s_addr = INADDR_ANY; - if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) { - perror("Error binding"); - close(serverSocket); - return 1; - } - - // Listen - if (listen(serverSocket, MAX_CONNECTIONS) == -1) { - perror("Error listening"); - close(serverSocket); - return 1; - } - - std::cout << "Server listening on port " << PORT << std::endl; - - while (true) { - // Accept connection - clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrSize); - if (clientSocket == -1) { - perror("Error accepting connection"); - close(serverSocket); - return 1; - } - - std::cout << "Accepted connection from " << inet_ntoa(clientAddr.sin_addr) << std::endl; - - while (true) { - // Receive data from client - int bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0); - if (bytesRead <= 0) { - break; - } - - buffer[bytesRead] = '\0'; - std::cout << "Received from client: " << buffer << std::endl; - - // Process received data if needed - // ... - - // Send response back to client - send(clientSocket, buffer, strlen(buffer), 0); - } - - close(clientSocket); - std::cout << "Connection closed" << std::endl; - } - - close(serverSocket); - - return 0; -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/socket_3/main.cpp b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/socket_3/main.cpp deleted file mode 100644 index 9eb2e85..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/socket_3/main.cpp +++ /dev/null @@ -1,137 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define PORT 8080 -#define MAX_CONNECTIONS 5 -#define MAX_BUFFER 1024 - -void handleClient(int clientSocket); - -int main() { - int serverSocket, clientSockets[MAX_CONNECTIONS], maxClients = 0; - struct sockaddr_in serverAddr, clientAddr; - socklen_t clientAddrSize = sizeof(clientAddr); - - for (int i = 0; i < MAX_CONNECTIONS; ++i) { - clientSockets[i] = -1; - } - - // Create socket - serverSocket = socket(AF_INET, SOCK_STREAM, 0); - if (serverSocket == -1) { - perror("Error creating socket"); - return 1; - } - - // Bind - serverAddr.sin_family = AF_INET; - serverAddr.sin_port = htons(PORT); - serverAddr.sin_addr.s_addr = INADDR_ANY; - if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) { - perror("Error binding"); - close(serverSocket); - return 1; - } - - // Listen - if (listen(serverSocket, MAX_CONNECTIONS) == -1) { - perror("Error listening"); - close(serverSocket); - return 1; - } - - std::cout << "Server listening on port " << PORT << std::endl; - - while (true) { - struct pollfd fds[MAX_CONNECTIONS + 1]; - memset(fds, 0, sizeof(fds)); - fds[0].fd = serverSocket; - fds[0].events = POLLIN; - - int currentClients = 1; - for (int i = 0; i < MAX_CONNECTIONS; ++i) { - int socket = clientSockets[i]; - if (socket != -1) { - fds[currentClients].fd = socket; - fds[currentClients].events = POLLIN; - ++currentClients; - } - } - - int activity = poll(fds, currentClients, -1); - - if (activity < 0) { - perror("Error in poll"); - close(serverSocket); - return 1; - } - - if (fds[0].revents & POLLIN) { - int clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrSize); - if (clientSocket == -1) { - perror("Error accepting connection"); - close(serverSocket); - return 1; - } - - if (maxClients < MAX_CONNECTIONS) { - for (int i = 0; i < MAX_CONNECTIONS; ++i) { - if (clientSockets[i] == -1) { - clientSockets[i] = clientSocket; - ++maxClients; - break; - } - } - } else { - std::cout << "Too many clients. Connection refused." << std::endl; - close(clientSocket); - } - - std::cout << "Accepted connection from " << inet_ntoa(clientAddr.sin_addr) << std::endl; - } - - for (int i = 1; i < currentClients; ++i) { - int socket = fds[i].fd; - if (socket != -1 && fds[i].revents & POLLIN) { - handleClient(socket); - } - } - } - - close(serverSocket); - - return 0; -} - -void handleClient(int clientSocket) { - char buffer[MAX_BUFFER]; - int bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0); - - if (bytesRead <= 0) { - struct sockaddr_in clientAddr; - socklen_t clientAddrSize = sizeof(clientAddr); - getpeername(clientSocket, (struct sockaddr*)&clientAddr, &clientAddrSize); - std::cout << "Connection closed by client " << inet_ntoa(clientAddr.sin_addr) << std::endl; - close(clientSocket); - return; - } - - buffer[bytesRead] = '\0'; - std::cout << "Received from client: " << buffer << std::endl; - send(clientSocket, buffer, strlen(buffer), 0); - - // Handle client message here -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/tryCatchForArgSize/main.cpp b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/tryCatchForArgSize/main.cpp deleted file mode 100644 index f08d04f..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/caseStudies/tryCatchForArgSize/main.cpp +++ /dev/null @@ -1,23 +0,0 @@ - -#include -#include - - -int main() -{ - std::vector TEST; - - TEST.push_back("MODE"); - TEST.push_back("#channel"); - TEST.push_back("+k"); - TEST.push_back("444"); - try - { - std::cout << TEST.at(5) << std::endl; - } - catch (const std::out_of_range &e) - { - std::cerr << "Hata: " << e.what() << std::endl; - } - return 0; -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/ft_irc_en.subject.pdf b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/ft_irc_en.subject.pdf deleted file mode 100644 index 9756c50..0000000 Binary files a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/ft_irc_en.subject.pdf and /dev/null differ diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/ft_irc_tr.subject.txt b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/ft_irc_tr.subject.txt deleted file mode 100644 index 272af66..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/ft_irc_tr.subject.txt +++ /dev/null @@ -1,124 +0,0 @@ -/* - --->💬 ft_irc v6 <--- - ---> Internet Relay Chat / İnternet Aktarmalı Sohbet <--- - Özet: Bu proje kendi IRC sunucunuzu yaratmakla ilgilidir. - Sunucunuza bağlanmak ve test etmek için gerçek bir IRC istemcisi kullanacaksınız. - İnternet, bağlı bilgisayarların birbirleriyle etkileşime girmesine izin veren katı standartlar protokolleri tarafından yönetilir. - - ---> 𝐈. Introduction / Giriş <--- - Internet Relay Chat veya IRC, Internet üzerinde metin tabanlı bir iletişim protokolüdür. - Herkese açık veya özel olabilen gerçek zamanlı mesajlaşma sunar. - Kullanıcılar doğrudan mesaj alışverişinde bulunabilir ve grup kanallarına katılabilir. - - IRC istemcileri, kanallara katılmak için IRC sunucularına bağlanır. - IRC sunucuları bir ağ oluşturmak için birbirine bağlanır. - - ---> 𝐈𝐈. General Rules / Genel Kurallar <--- - • Programınız hiçbir koşulda (bellek tükendiğinde bile) çökmemeli ve beklenmedik bir şekilde kapanmamalıdır. - Böyle bir durumda projeniz işlevsiz kabul edilecek ve notunuz 0 olacaktır. - • Kaynak dosyalarınızı derleyecek bir Makefile teslim etmelisiniz. - Yeniden derlenmemelidir(relink). - • Makefile dosyanız en azından şu kuralları içermelidir: - '$(NAME)', 'all', 'clean', 'fclean' ve 're' - • Kodunuzu 'c++' ve '-Wall -Wextra -Werror' bayraklarıyla(flags) derleyin. - • Kodunuz C++ 98 standardına uygun olmalıdır. - Ardından, '-std=c++98' bayrağını(flag) eklerseniz derlenmesi gerekir. - • Her zaman yapabileceğiniz en fazla C++ özelliğini kullanarak geliştirmeye çalışın (örneğin, yerine 'i seçin). - C işlevlerini kullanmanıza izin verilir, ancak mümkünse her zaman C++ sürümlerini tercih edin. - • Herhangi bir 'harici kitaplık' ve 'Boost kitaplığı' YASAKTIR. - - ---> 𝐈𝐈𝐈. Mandatory Part / Zorunlu Kısım <--- ------------------------------------------------------------------------------------------------------------------------------ -| -> Program adı: ircserv | -| -> Teslim edilecek dosyalar: Makefile, *.{h, hpp}, *.cpp, *.tpp, *.ipp, isteğe bağlı bir yapılandırma dosyası | -| -> Makefile: NAME, all, clean, fclean, re | -| -> Argümanlar: port: The listening port / dinleme bağlantı noktası | -| password: The connection password / bağlantı şifresi | -| -> Harici fonksiyonlar: C++ 98'deki her yapı, | -| socket, close, setsockopt, getsockname, getprotobyname, gethostbyname, getaddrinfo, | -| freeaddrinfo, bind, connect, listen, accept, htons, htonl, ntohs, inet_addr, inet_ntoa, | -| send, recv, signal, lseek, fstat, fcntl, poll (ya da aynı işleve sahip bir fonksiyon) | -| -> Libft yetkisi: yok | -| -> Tanım: C++ 98'de bir IRC sunucusu | ------------------------------------------------------------------------------------------------------------------------------ - C++ 98'de bir IRC sunucusu geliştirmelisiniz. - Bir istemci(client) OLUŞTURMAMALISINIZ!. - Sunucudan(server) sunucuya iletişimi ele ALMAMALISINIZ!. - - Yürütülebilir dosyanız aşağıdaki gibi çalıştırılacaktır: - './ircserv ' - - • port: IRC sunucunuzun gelen IRC bağlantılarını dinleyeceği port numarası. - • password: Bağlantı şifresi. - Sunucunuza bağlanmaya çalışan herhangi bir IRC istemcisi tarafından gerekli olacaktır. - - ℹ️ Konuda ve değerlendirme ölçeğinde poll()'den bahsedilse bile, select(), kqueue() veya epoll() gibi herhangi bir eşdeğeri kullanabilirsiniz. - - ---> 𝐈𝐈𝐈. ⓵ Requirements / Gereksinimler <--- - • Sunucu aynı anda birden fazla istemciyi yönetebilmeli ve asla askıda kalmamalıdır. - • Fork oluşturma izni verilmez. - Tüm Input/Output işlemleri blokesiz olmalıdır. - • Tüm bu işlemleri (okuma(read), yazma(write), aynı zamanda dinleme(listen) vb.) işlemek için yalnızca 1 poll() (veya eşdeğeri) kullanılabilir. - - 🚨 Çünkü bloke olmayan dosya tanımlayıcıları kullanmanız gerektiğinde, read/recv veya write/send fonksiyonlarını poll() (veya eşdeğer işlevler) olmadan kullanmanız mümkündür ve sunucunuz bloklanmaz. - 🚨 Ancak daha fazla sistem kaynağı tüketir. - 🚨 Bu nedenle, poll() (veya eşdeğeri) kullanmadan herhangi bir dosya tanıtıcıda read/recv veya write/send çalışırsanız, notunuz 0 olacaktır. - - • Birkaç IRC istemcisi mevcuttur. - Bunlardan birini referans olarak seçmelisiniz. - Referans olarak aldığınız istemciniz değerlendirme sürecinde kullanılacaktır. - • Referans istemciniz herhangi bir hata ile karşılaşmadan sunucunuza bağlanabilmelidir. - • İstemci ve sunucu arasındaki iletişim TCP/IP (v4 veya v6) aracılığıyla yapılmalıdır. - • Referans istemcinizi sunucunuzla kullanmak, onu herhangi bir resmi IRC sunucusuyla kullanmaya benzer olmalıdır. - Ancak, yalnızca aşağıdaki özellikleri uygulamanız gerekir: - ◦ Referans istemcinizi kullanarak kimlik doğrulaması yapabilmeniz, bir takma ad, bir kullanıcı adı belirleyebilmeniz, bir kanala katılabilmeniz, özel mesajlar gönderebilmeniz ve alabilmeniz gerekir. - ◦ Bir istemciden bir kanala gönderilen tüm mesajların, kanala katılan diğer tüm istemcilere iletilmesi gerekir. - ◦ Operatörler ve düzenli(uygun) kullanıcılarınızın olması gerekmektedir. - ◦ Ardından, operatörlere özgü komutları uygulamanız gerekir. - • Elbette sizden temiz bir kod yazmanız bekleniyor. - - ---> 𝐈𝐈𝐈. ⓶ For MacOS only / Yalnızca MacOS için <--- - - ℹ️ MacOS, write()'ı diğer Unix OS'lerle aynı şekilde uygulamadığından, fcntl()'yi kullanmanıza izin verilir. - ℹ️ Diğer Unix işletim sistemlerindekine benzer bir davranış elde etmek için dosya tanıtıcıları(fd) engellemesiz(non-blocking) modda kullanmalısınız. - - 🚨 Ancak, fcntl() işlevini yalnızca aşağıdaki şekilde kullanmanıza izin verilir: - 'fcntl(fd, F_SETFL, O_NONBLOCK);' - 🚨 Başka herhangi bir bayrak yasaktır. - - ---> 𝐈𝐈𝐈. ⓷ Test example / Test örneği <--- - - Olası her hatayı ve sorunu (kısmi veri alma(receiving partial data), düşük bant genişliği(low bandwidth) vb.) kesinlikle doğrulayın. - - Sunucunuzun kendisine gönderdiğiniz her şeyi doğru bir şekilde işlemesini sağlamak için nc kullanarak aşağıdaki basit test yapılabilir: - ----------------------------- - | \$> nc 127.0.0.1 6667 | - | com^Dman^Dd | - | \$> | - ----------------------------- - - Komutu birkaç parça halinde göndermek için ctrl+D tuşlarını kullanın: 'com', sonra 'man', ardından 'd\n'. - Bir komutu işlemek için, yeniden oluşturmak üzere önce alınan paketleri toplamanız gerekir. - - ---> 𝐈𝐕. Bonus part / Bonus kısım <--- - - İşte IRC sunucunuza ekleyebileceğiniz ekstra özellikler, böylece daha da gerçek bir IRC sunucusu gibi görünür: - • Dosya aktarımını yönetin. - • Bir bot ekleyin. - - 🚨 Bonus kısım, yalnızca zorunlu kısım MÜKEMMEL ise değerlendirilecektir. - 🚨 Kusursuz demek, zorunlu olan kısım bütün olarak yapılmış ve arızasız çalışıyor demektir. - 🚨 TÜM zorunlu gereksinimleri geçmediyseniz, bonus bölümünüz hiç değerlendirilmeyecektir. - - ---> 𝐕. Submission and peer-evaluation / Sunum ve akran değerlendirmesi <--- - - Git deponuzdaki ödevinizi her zamanki gibi teslim edin. - Savunma sırasında yalnızca deponuzdaki çalışma değerlendirilecektir. - Doğru olduklarından emin olmak için dosyalarınızın adlarını iki kez kontrol etmekten çekinmeyin. - - Teslim edilmeyecek ve notlandırılmayacak olsalar bile, projeniz için test programları oluşturmanız önerilir. - Bu testler, sunucunuzu savunma sırasında test etmek için özellikle yararlı olabilir, ancak aynı zamanda bir gün başka bir ft_irc'i değerlendirmek zorunda kalırsanız, meslektaşınızınkini de test edebilir. - Gerçekten de, değerlendirme sürecinde ihtiyacınız olan testleri kullanmakta özgürsünüz. - - ℹ️ Değerlendirme sürecinde referans istemciniz(client) kullanılacaktır. -*/ \ No newline at end of file diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/info_external_functs.txt b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/info_external_functs.txt deleted file mode 100644 index faabc23..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/info_external_functs.txt +++ /dev/null @@ -1,297 +0,0 @@ -################################ ft_irc External functs / Harici fonksiyonlar ################################ - -->> socket <<------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/2/socket -Kütüphane: - #include - #include -Fonksiyon: - int socket(int domain, int type, int protocol); -Tanım: - socket() işlevi, socket programlamada kullanılan ve iletişim kurmak için bir soket (socket) oluşturmayı sağlar. - -->> close <<-------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/2/close -Kütüphane: - #include -Fonksiyon: - int close(int fd); -Tanım: - close() işlevi, açılmış bir dosya tanıtıcısını veya soketi kapatmak için kullanılır. - -->> setsockopt <<--------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/3/setsockopt -Kütüphane: - #include -Fonksiyon: - int setsockopt(int socket, int level, int option_name, const void *option_value, socklen_t option_len); -Tanım: - setsockopt() işlevi, bir soketin seçeneklerini ayarlamak için kullanılır. - Bağlantı zaman aşımı süresini, tampon boyutlarını, soket seçeneklerini vb. ayarlamak için kullanılabilir. - -->> getsockname <<-------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/2/getsockname - https://linux.die.net/man/3/getsockname -Kütüphane: - #include -Fonksiyon: - int getsockname(int sockfd, struct sockaddr *addrsocklen_t *" addrlen ); - int getsockname(int socket, struct sockaddr *restrict address, socklen_t *restrict address_len); -Tanım: - getsockname(), bir soketin yerel adres bilgisini almak için kullanılan bir işlevdir. - Yani, bir soketin hangi yerel IP adresi ve bağlantı noktasına bağlı olduğunu belirlemek için kullanılır. - -->> getprotobyname <<----------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/3/getprotobyname -Kütüphane: - #include -Fonksiyon: - struct protoent *getprotobyname(const char *name); -Tanım: - getprotobyname(), bir protokol ismi verildiğinde, ilgili protokolün numarasını elde etmek için kullanılan bir işlevdir. - -->> gethostbyname <<------------------------------------------------------------------------------------------ -URL: - https://linux.die.net/man/3/gethostbyname -Kütüphane: - #include -Fonksiyon: - struct hostent *gethostbyname(const char *name); -Tanım: - gethostbyname(), bir host adı veya IP adresi verildiğinde, ilgili ağ adresi bilgilerini çözümlemek için kullanılan bir işlevdir. - -->> getaddrinfo <<-------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/3/getaddrinfo -Kütüphane: - #include - #include - #include -Fonksiyon: - int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res); -Tanım: - getaddrinfo() işlevi, ağ adresi çözümü ve hazırlanması sürecini basitleştirir ve IP adresleri, bağlantı noktaları gibi ağ parametrelerini elde etmek için kullanışlı bir yol sağlar. - Bu işlevin dönüş değeri başarılı olup olmadığını belirtir. - Eğer başarılı olursa, dönüş değeri 0 olacaktır - -->> freeaddrinfo <<------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/3/freeaddrinfo -Kütüphane: - #include - #include - #include -Fonksiyon: - void freeaddrinfo(struct addrinfo *res); -Tanım: - freeaddrinfo() işlevi, dinamik olarak ayrılmış bağlantılı liste res için ayrılan belleği serbest bırakır. - -->> bind <<--------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/2/bind -Kütüphane: - #include - #include -Fonksiyon: - int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen); -Tanım: - bind(), bir soketi belirli bir IP adresi ve bağlantı noktasına bağlamak için kullanılan bir işlevdir. - Bu işlem, sunucu tarafında kullanılarak belirli bir IP adresi ve portu dinlemek amacıyla soketi yapılandırmayı sağlar. - -->> connect <<------------------------------------------------------------------------------------------------ -URL: - https://linux.die.net/man/3/connect -Kütüphane: - #include -Fonksiyon: - int connect(int socket, const struct sockaddr *address, socklen_t address_len); -Tanım: - connect(), istemci tarafında kullanılarak sunucu soketine bağlanmayı başlatmak için kullanılan bir işlevdir. - Bu işlem, istemci uygulamalarının sunucu ile iletişim kurabilmek için soketi kullanmaya başlaması anlamına gelir. - -->> listen <<------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/2/listen -Kütüphane: - #include - #include -Fonksiyon: - int listen(int sockfd, int backlog); -Tanım: - listen(), sunucu tarafında kullanılarak belirli bir soketi bağlama işleminden sonra gelen bağlantıları dinlemeyi başlatmak için kullanılan bir işlevdir. - Bu işlem, sunucunun gelen bağlantıları kabul etmeye hazır hale gelmesini sağlar. - -->> accept <<------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/3/accept -Kütüphane: - #include -Fonksiyon: - int accept(int socket, struct sockaddr *restrict address, socklen_t *restrict address_len); -Tanım: - accept(), sunucu tarafında kullanılarak gelen bir bağlantı isteğini kabul etmek ve yeni bir soket oluşturarak istemci ile iletişim kurmak için kullanılan bir işlevdir. - -->> htons <<-------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/3/htons -Kütüphane: - #include -Fonksiyon: - uint16_t htons(uint16_t hostshort); -Tanım: - htons(), "host to network short" ifadesinin kısaltmasıdır ve bilgisayarın belleğinde temsil edilen sayıları ağ baytlarına dönüştürmek için kullanılır. - Özellikle ağ iletişimi sırasında büyük ve küçük byte sırası/düzeni (endianness) farklılıklarından kaynaklanan sorunları çözmek için kullanılır. - -->> htonl <<-------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/3/htonl -Kütüphane: - #include -Fonksiyon: - uint32_t htonl(uint32_t hostlong); -Tanım: - htonl(), "host to network long" ifadesinin kısaltmasıdır ve bilgisayarın belleğinde temsil edilen uzun (4 byte) tam sayıları ağ baytlarına dönüştürmek için kullanılır. - Özellikle ağ iletişimi sırasında büyük ve küçük byte sırası/düzeni (endianness) farklılıklarından kaynaklanan sorunları çözmek için kullanılır. - -->> ntohs <<-------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/3/ntohs -Kütüphane: - #include -Fonksiyon: - uint16_t ntohs(uint16_t netshort); -Tanım: - ntohs(), "network to host short" ifadesinin kısaltmasıdır ve ağ baytlarında temsil edilen kısa (2 byte) tam sayıları, bilgisayarın belleğinde temsil edilen forma dönüştürmek için kullanılır. - Özellikle ağ iletişimi sırasında büyük ve küçük byte sırası/düzeni (endianness) farklılıklarından kaynaklanan sorunları çözmek için kullanılır. - -->> inet_addr <<---------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/3/inet_addr -Kütüphane: - #include - #include - #include -Fonksiyon: - in_addr_t inet_addr(const char *cp); -Tanım: - inet_addr(), bir IPv4 adresini (dört noktalı notasyonla verilen adres) ondalık sayı tabanından 32-bitlik bir ikili formata çevirmek için kullanılır. - Bu işlev, ağ iletişiminde IP adreslerini manipüle etmek veya karşılaştırmak amacıyla kullanılır. - -->> inet_ntoa <<---------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/3/inet_ntoa -Kütüphane: - #include - #include - #include -Fonksiyon: - char *inet_ntoa(struct in_addr in); -Tanım: - inet_ntoa(), 32-bitlik bir ikili IP adresini dört noktalı ondalık notasyonlu forma çevirmek için kullanılır. - Bu işlev, ağ iletişiminde IP adreslerini daha okunabilir bir formata dönüştürmek için kullanılır. - -->> send <<--------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/2/send -Kütüphane: - #include - #include -Fonksiyon: - ssize_t send(int sockfd, const void *buf, size_t len, int flags); -Tanım: - send(), bir soketten veri göndermek için kullanılan bir işlevidir. - Bu işlev, iletişim kurulan soketten veriyi karşı tarafa göndermek için kullanılır. - -->> recv <<--------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/2/recv -Kütüphane: - #include - #include -Fonksiyon: - ssize_t recv(int sockfd, void *buf, size_t len, int flags); -Tanım: - recv(), bir soketten veri almak için kullanılan bir işlevidir. - Bu işlev, iletişim kurulan soketten veriyi karşı taraftan almak için kullanılır. - -->> signal <<------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/2/signal -Kütüphane: - #include -Fonksiyon: - sighandler_t signal(int signum, sighandler_t handler); -Tanım: - signal(), belirli bir sinyal alındığında gerçekleştirilecek işlevleri (işaretçileri) ayarlamak veya özelleştirmek için kullanılan bir işlevidir. - Sinyaller, bir programın çalışma zamanında olayları veya durumları işaretlemek ve işlemek için kullanılır. - -->> lseek <<-------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/2/lseek -Kütüphane: - #include - #include -Fonksiyon: - off_t lseek(int fd, off_t offset, int whence); -Tanım: - lseek(), bir dosyanın okuma veya yazma konumunu değiştirmek için kullanılan bir işlevidir. - Bu işlev, dosya işaretçisini belirli bir konuma taşımak veya dosyanın hangi konumda okuma veya yazma yapılacağını ayarlamak için kullanılır. - -->> fstat <<-------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/2/fstat -Kütüphane: - #include - #include - #include -Fonksiyon: - int fstat(int fd, struct stat *buf); -Tanım: - fstat(), bir dosyanın durumu ve özellikleri hakkında bilgi almak için kullanılan bir işlevidir. - Bu işlev, dosyanın boyutu, erişim izinleri, değiştirilme tarihi gibi bilgileri elde etmek için kullanılır. - -->> fcntl <<-------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/2/fcntl -Kütüphane: - #include - #include -Fonksiyon: - int fcntl(int fd, int cmd, ... /* arg */ ); -Tanım: - fcntl(), dosya tanıtıcısının farklı özelliklerini kontrol etmek veya değiştirmek için kullanılan bir işlevidir. - Bu işlev, dosya tanıtıcısının sınırlarını genişletmek, dosyanın durumunu değiştirmek, kilitlemek gibi işlemleri gerçekleştirmek için kullanılır. - -->> poll <<--------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/2/poll -Kütüphane: - #include -Fonksiyon: - int poll(struct pollfd *fds, nfds_t nfds, int timeout); -Tanım: - poll(), birden fazla dosya tanıtıcısının (soket, dosya vb.) okuma veya yazma durumunu izlemek ve olaylar oluştuğunda ilgili işlemleri gerçekleştirmek için kullanılan bir işlevidir. - I/O olaylarını takip etmek ve engelleme olmadan çoklu soket veya dosyalar üzerinde aynı anda çalışmak için kullanılır. - -->> select <<------------------------------------------------------------------------------------------------- -URL: - https://linux.die.net/man/2/select -Kütüphane: - #include - #include - #include - #include -Fonksiyon: - int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); -Tanım: - poll() ile aynı işleve sahip fonksiyondur. - select(), verilen soket veya dosya tanıtıcılarını izleyerek, bu tanıtıcılarda okuma veya yazma yapılabilir durumunun olup olmadığını belirleyen bir sistem çağrısıdır. - Bu işlev, çoklu olay izleme (I/O multiplexing) sağlayarak aynı anda birden fazla soket veya dosyayı izlemek ve veri akışını yönetmek için kullanılır. - select() fonksiyonunun temel amacı, I/O işlemlerini engellemeden birden fazla kaynağı izleyebilmektir. - -############################################################################################################## \ No newline at end of file diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/irssi_Example_with_capability_negotiation.png b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/irssi_Example_with_capability_negotiation.png deleted file mode 100644 index 07831f7..0000000 Binary files a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/irssi_Example_with_capability_negotiation.png and /dev/null differ diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/notes.txt b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/notes.txt deleted file mode 100644 index dd855d4..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/notes.txt +++ /dev/null @@ -1,144 +0,0 @@ -LINK: https://modern.ircdocs.horse/#irc-concepts -LINK: https://irssi.org/documentation/ - -NOTES -{ - Max port size: 65536 -> 0 to 65535 - - Max MTU size: 1500-byte. -} - - -What is .hpp, .ipp, .tpp and .cpp files? -{ - -} - -IRC flags -> +b, -b, +k, -k, etc... -{ - EN - IRC (Internet Relay Chat) is a protocol for real-time text-based - communication over the internet. IRC servers use various command - flags to control and manage different aspects of the server and - its channels. These command flags are typically used with the - `/mode` command and are preceded by either a plus (`+`) or minus - (`-`) sign to indicate whether the flag is being set or unset. - - List of some common IRC server command flags: - - [1] `+b` and `-b`: Set or remove a ban on a user or hostmask, preventing - them from joining a channel. - [2] `+e` and `-e`: Set or remove an exception to a ban, allowing a user - or hostmask to join a channel even if they are banned. - [3] `+I` and `-I`: Add or remove a user or hostmask from the invite list - of a channel, allowing them to join the channel even if it is set - to invite-only. - [4] `+k` and `-k`: Set or remove a channel key (password), which users - must provide in order to join the channel. - [5] `+l` and `-l`: Set or remove a user limit on a channel, controlling - the maximum number of users that can join the channel. - [6] `+m` and `-m`: Set or remove moderated mode on a channel, which means - that only users with voice or operator privileges can send messages - to the channel. - [7] `+n` and `-n`: Set or remove no external messages mode on a channel, - which means that only users who are in the channel can send - messages to it. - [8] `+o` and `-o`: Give or take away operator privileges from a user in - a channel. - [9] `+p` and `-p`: Set or remove private mode on a channel, which means - that the channel will not be shown in the server's channel list. - [10] `+s` and `-s`: Set or remove secret mode on a channel, which means - that the channel will not be shown in the server's channel list - and users will not be able to see who is in the channel unless - they are also in it. - [11] `+t` and `-t`: Set or remove topic lock mode on a channel, which - means that only users with operator privileges can change the - topic of the channel. - - TR - IRC (Internet Relay Chat), internet üzerinden gerçek zamanlı metin tabanlı iletişim için bir protokoldür. IRC sunucuları, sunucunun ve kanallarının farklı yönlerini kontrol etmek ve yönetmek için çeşitli komut bayrakları kullanır. Bu komut bayrakları tipik olarak "/mode" komutuyla kullanılır ve bayrağın ayarlanıp ayarlanmadığını belirtmek için önünde bir artı ('+') veya eksi ('-') işareti bulunur. - - Yaygın IRC sunucusu komut işaretlerinin anlamlari: - - - `+b` ve `-b`: Bir kullanıcı veya ana bilgisayar maskesi üzerindeki bir yasağı ayarlamak veya kaldırmak için kullanılır ve bu kişilerin bir kanala katılmasını engeller. - - `+e` ve `-e`: Yasaklanmış olsalar bile bir kullanıcının veya ana bilgisayar maskesinin bir kanala katılmasına izin vererek, bir yasaklama için bir istisna ayarlamak veya kaldırmak için kullanılır. - - `+I` ve `-I`: Bir kanalın davet listesine bir kullanıcı veya ana bilgisayar maskesi eklemek veya çıkarmak için kullanılır; bu, yalnızca davet olarak ayarlanmış olsa bile kanala katılmalarına izin verir. - - `+k` ve `-k`: Kullanıcıların kanala katılmak için sağlamaları gereken bir kanal anahtarı (şifre) ayarlamak veya kaldırmak için kullanılır. - - `+l` ve `-l`: Kanala katılabilecek maksimum kullanıcı sayısını kontrol ederek bir kanalda bir kullanıcı sınırı ayarlamak veya kaldırmak için kullanılır. - - `+m` ve `-m`: Bir kanalda denetimli modu ayarlamak veya kaldırmak için kullanılır; bu, yalnızca ses veya operatör ayrıcalıklarına sahip kullanıcıların kanala mesaj gönderebileceği anlamına gelir. - - `+n` ve `-n`: Bir kanalda harici mesaj yok modunu ayarlamak veya kaldırmak için kullanılır; bu, yalnızca kanalda bulunan kullanıcıların kanala mesaj gönderebileceği anlamına gelir. - - `+o` ve `-o`: Bir kanaldaki bir kullanıcıya operatör ayrıcalıkları vermek veya bu ayrıcalıkları geri almak için kullanılır. - - `+p` ve `-p`: Bir kanalda özel modu ayarlamak veya kaldırmak için kullanılır; bu, kanalın sunucunun kanal listesinde gösterilmeyeceği anlamına gelir. - - `+s` ve `-s`: Bir kanalda gizli modu ayarlamak veya kaldırmak için kullanılır; bu, kanalın sunucunun kanal listesinde gösterilmeyeceği ve kullanıcıların kimlerin olduğunu göremediği anlamına gelir. onlar da içinde olmadıkları sürece kanal. - - `+t` ve `-t`: Bir kanalda konu kilitleme modunu ayarlamak veya kaldırmak için kullanılır; bu, yalnızca operatör ayrıcalıklarına sahip kullanıcıların kanalın konusunu değiştirebileceği anlamına gelir. -} - -IRC Server <- -> IRC Client: Connection Setup -{ - LINK: https://modern.ircdocs.horse/#connection-setup - - EN - IRC client-server connections work over TCP/IP. The standard ports for - client-server connections are TCP/6667 for plaintext, and TCP/6697 - for TLS connections. - - TR - IRC istemci-sunucu bağlantıları TCP/IP üzerinden çalışır. İstemci-sunucu - bağlantıları için standart bağlantı noktaları, düz metin için TCP/6667 - ve TLS bağlantıları için TCP/6697'dir. -} - -What is MTU? -{ - Max MTU size: 1500-byte -} - -What is Irssi? -{ - LINK: https://wiki.archlinux.org/title/irssi -} - -COMMANDS -{ - Write colored on Irssi - { - /set hide_colors OFF - ctrl+c 3 Helloo -> Writing colored text (green). - LINK: https://stackoverflow.com/questions/22429108/how-can-i-write-colored-text-to-an-irc-channel-with-irssi - ctrl+c 8,7 BRUH -> Writing colored text and different background. - LINK: https://www.mirc.com/colors.html - ^C5,12colored text and background^C after the default text -> Look like this - ^C5colored^C not colored(default)^C2,8colored eheheh^C end. - } - - CMD: 'top' -> How can i watch any pid? - { - $> ps - gsever@k2m14s08 ~ % ps - PID TTY TIME CMD - 73718 ttys000 0:00.05 /bin/zsh - 80562 ttys000 0:00.00 ./ircserv 8888 asdf - 80543 ttys001 0:00.06 /bin/zsh - 73732 ttys002 0:00.01 /bin/zsh - Copy the PID. - $> top -pid - Processes: 355 total, 2 running, 353 sleeping, 2076 threads - 20:07:58 Load Avg: 1.08, 1.26, 1.35 - CPU usage: 1.21% user, 0.97% sys, 97.81% idle - SharedLibs: 197M resident, 58M data, 21M linkedit. - MemRegions: 379594 total, 2181M resident, 73M private, 913M sha - PhysMem: 7687M used (1994M wired), 502M unused. - VM: 32T vsize, 1991M framework vsize, 2146344(0) swapins, 23228 - Networks: packets: 22062050/23G in, 22557963/18G out. - Disks: 3714066/69G read, 1779503/75G written. - - PID COMMAND %CPU TIME #TH #WQ #POR MEM PURG CMPR - 80562 ircserv 0.0 00:00.00 1 0 14 396K 0B 0B - } - - CMD: strace - { - strace -p - } - -} \ No newline at end of file diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd.tar.gz b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd.tar.gz deleted file mode 100644 index a38e436..0000000 Binary files a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd.tar.gz and /dev/null differ diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/Makefile b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/Makefile deleted file mode 100644 index 3ce5988..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/Makefile +++ /dev/null @@ -1,28 +0,0 @@ - -SRCS = main.c init_env.c clean_fd.c get_opt.c x.c main_loop.c \ - init_fd.c do_select.c check_fd.c \ - srv_create.c srv_accept.c \ - client_read.c client_write.c - -OBJS = ${SRCS:.c=.o} - -NAME = bircd - -CFLAGS = -I. -g3 -Wall -Werror -LDFLAGS = - -CC = gcc -RM = rm -f - -${NAME}: ${OBJS} - ${CC} -o ${NAME} ${OBJS} ${LDFLAGS} - -all: ${NAME} - -clean: - ${RM} ${OBJS} *~ #*# - -fclean: clean - ${RM} ${NAME} - -re: fclean all diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/bircd.h b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/bircd.h deleted file mode 100644 index 8f5c9f7..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/bircd.h +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef BIRCD_H_ -# define BIRCD_H_ - -# include - -# define FD_FREE 0 -# define FD_SERV 1 -# define FD_CLIENT 2 - -# define BUF_SIZE 4096 - -# define Xv(err,res,str) (x_void(err,res,str,__FILE__,__LINE__)) -# define X(err,res,str) (x_int(err,res,str,__FILE__,__LINE__)) -# define MAX(a,b) ((a > b) ? a : b) - -# define USAGE "Usage: %s port\n" - -typedef struct s_fd -{ - int type; - void (*fct_read)(); - void (*fct_write)(); - char buf_read[BUF_SIZE + 1]; - char buf_write[BUF_SIZE + 1]; -} t_fd; - -typedef struct s_env -{ - t_fd *fds; - int port; - int maxfd; - int max; - int r; - fd_set fd_read; - fd_set fd_write; -} t_env; - -void init_env(t_env *e); -void get_opt(t_env *e, int ac, char **av); -void main_loop(t_env *e); -void srv_create(t_env *e, int port); -void srv_accept(t_env *e, int s); -void client_read(t_env *e, int cs); -void client_write(t_env *e, int cs); -void clean_fd(t_fd *fd); -int x_int(int err, int res, char *str, char *file, int line); -void *x_void(void *err, void *res, char *str, char *file, int line); -void init_fd(t_env *e); -void do_select(t_env *e); -void check_fd(t_env *e); - -#endif /* !BIRCD_H_ */ diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/check_fd.c b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/check_fd.c deleted file mode 100644 index 81a57dd..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/check_fd.c +++ /dev/null @@ -1,20 +0,0 @@ - -#include "bircd.h" - -void check_fd(t_env *e) -{ - int i; - - i = 0; - while ((i < e->maxfd) && (e->r > 0)) - { - if (FD_ISSET(i, &e->fd_read)) - e->fds[i].fct_read(e, i); - if (FD_ISSET(i, &e->fd_write)) - e->fds[i].fct_write(e, i); - if (FD_ISSET(i, &e->fd_read) || - FD_ISSET(i, &e->fd_write)) - e->r--; - i++; - } -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/clean_fd.c b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/clean_fd.c deleted file mode 100644 index ff555e2..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/clean_fd.c +++ /dev/null @@ -1,10 +0,0 @@ - -#include -#include "bircd.h" - -void clean_fd(t_fd *fd) -{ - fd->type = FD_FREE; - fd->fct_read = NULL; - fd->fct_write = NULL; -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/client_read.c b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/client_read.c deleted file mode 100644 index 4f39d21..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/client_read.c +++ /dev/null @@ -1,30 +0,0 @@ - -#include -#include -#include -#include "bircd.h" - -void client_read(t_env *e, int cs) -{ - int r; - int i; - - r = recv(cs, e->fds[cs].buf_read, BUF_SIZE, 0); - if (r <= 0) - { - close(cs); - clean_fd(&e->fds[cs]); - printf("client #%d gone away\n", cs); - } - else - { - i = 0; - while (i < e->maxfd) - { - if ((e->fds[i].type == FD_CLIENT) && - (i != cs)) - send(i, e->fds[cs].buf_read, r, 0); - i++; - } - } -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/client_write.c b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/client_write.c deleted file mode 100644 index bf7d8bc..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/client_write.c +++ /dev/null @@ -1,7 +0,0 @@ - -#include -#include "bircd.h" - -void client_write(t_env *e, int cs) -{ -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/do_select.c b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/do_select.c deleted file mode 100644 index d5ea1a3..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/do_select.c +++ /dev/null @@ -1,8 +0,0 @@ - -#include -#include "bircd.h" - -void do_select(t_env *e) -{ - e->r = select(e->max + 1, &e->fd_read, &e->fd_write, NULL, NULL); -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/get_opt.c b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/get_opt.c deleted file mode 100644 index 6fef11f..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/get_opt.c +++ /dev/null @@ -1,15 +0,0 @@ - -#include -#include -#include "bircd.h" - -void get_opt(t_env *e, int ac, char **av) -{ - if (ac != 2) - { - fprintf(stderr, USAGE, av[0]); - exit(1); - } - e->port = atoi(av[1]); -} - diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/init_env.c b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/init_env.c deleted file mode 100644 index 2ad0c93..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/init_env.c +++ /dev/null @@ -1,20 +0,0 @@ - -#include -#include -#include "bircd.h" - -void init_env(t_env *e) -{ - int i; - struct rlimit rlp; - - X(-1, getrlimit(RLIMIT_NOFILE, &rlp), "getrlimit"); - e->maxfd = rlp.rlim_cur; - e->fds = (t_fd*)Xv(NULL, malloc(sizeof(*e->fds) * e->maxfd), "malloc"); - i = 0; - while (i < e->maxfd) - { - clean_fd(&e->fds[i]); - i++; - } -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/init_fd.c b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/init_fd.c deleted file mode 100644 index 4935ce2..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/init_fd.c +++ /dev/null @@ -1,27 +0,0 @@ - -#include -# include -#include "bircd.h" - -void init_fd(t_env *e) -{ - int i; - - i = 0; - e->max = 0; - FD_ZERO(&e->fd_read); - FD_ZERO(&e->fd_write); - while (i < e->maxfd) - { - if (e->fds[i].type != FD_FREE) - { - FD_SET(i, &e->fd_read); - if (strlen(e->fds[i].buf_write) > 0) - { - FD_SET(i, &e->fd_write); - } - e->max = MAX(e->max, i); - } - i++; - } -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/main.c b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/main.c deleted file mode 100644 index 55a674e..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/main.c +++ /dev/null @@ -1,13 +0,0 @@ - -#include "bircd.h" - -int main(int ac, char **av) -{ - t_env e; - - init_env(&e); - get_opt(&e, ac, av); - srv_create(&e, e.port); - main_loop(&e); - return (0); -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/main_loop.c b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/main_loop.c deleted file mode 100644 index 88c2d27..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/main_loop.c +++ /dev/null @@ -1,12 +0,0 @@ - -#include "bircd.h" - -void main_loop(t_env *e) -{ - while (1) - { - init_fd(e); - do_select(e); - check_fd(e); - } -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/srv_accept.c b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/srv_accept.c deleted file mode 100644 index ebdd2dc..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/srv_accept.c +++ /dev/null @@ -1,21 +0,0 @@ - -#include -#include -#include -#include "bircd.h" - -void srv_accept(t_env *e, int s) -{ - int cs; - struct sockaddr_in csin; - socklen_t csin_len; - - csin_len = sizeof(csin); - cs = X(-1, accept(s, (struct sockaddr*)&csin, &csin_len), "accept"); - printf("New client #%d from %s:%d\n", cs, - inet_ntoa(csin.sin_addr), ntohs(csin.sin_port)); - clean_fd(&e->fds[cs]); - e->fds[cs].type = FD_CLIENT; - e->fds[cs].fct_read = client_read; - e->fds[cs].fct_write = client_write; -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/srv_create.c b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/srv_create.c deleted file mode 100644 index 97b2d96..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/srv_create.c +++ /dev/null @@ -1,22 +0,0 @@ - -#include -#include -#include -#include "bircd.h" - -void srv_create(t_env *e, int port) -{ - int s; - struct sockaddr_in sin; - struct protoent *pe; - - pe = (struct protoent*)Xv(NULL, getprotobyname("tcp"), "getprotobyname"); - s = X(-1, socket(PF_INET, SOCK_STREAM, pe->p_proto), "socket"); - sin.sin_family = AF_INET; - sin.sin_addr.s_addr = INADDR_ANY; - sin.sin_port = htons(port); - X(-1, bind(s, (struct sockaddr*)&sin, sizeof(sin)), "bind"); - X(-1, listen(s, 42), "listen"); - e->fds[s].type = FD_SERV; - e->fds[s].fct_read = srv_accept; -} diff --git a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/x.c b/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/x.c deleted file mode 100644 index 63ea876..0000000 --- a/Additional/Helper_projects/Gorkem_Ahmet/subjectFiles/resources/bircd/x.c +++ /dev/null @@ -1,28 +0,0 @@ - -#include -#include -#include -#include -#include "bircd.h" - -int x_int(int err, int res, char *str, char *file, int line) -{ - if (res == err) - { - fprintf(stderr, "%s error (%s, %d): %s\n", - str, file, line, strerror(errno)); - exit (1); - } - return (res); -} - -void *x_void(void *err, void *res, char *str, char *file, int line) -{ - if (res == err) - { - fprintf(stderr, "%s error (%s, %d): %s\n", - str, file, line, strerror(errno)); - exit (1); - } - return (res); -} diff --git a/Additional/Notes/Info.txt b/Additional/Notes/Info.txt deleted file mode 100644 index 7911d22..0000000 --- a/Additional/Notes/Info.txt +++ /dev/null @@ -1,15 +0,0 @@ -sources: - -http://chi.cs.uchicago.edu/chirc/index.html - -http://chi.cs.uchicago.edu/chirc/irc_examples.html - - -https://datatracker.ietf.org/doc/html/rfc1459 -https://datatracker.ietf.org/doc/html/rfc2810 -https://datatracker.ietf.org/doc/html/rfc2811 -https://datatracker.ietf.org/doc/html/rfc2812 -https://datatracker.ietf.org/doc/html/rfc2813 - -liste des commandes : -https://www.techbull.com/techbull/guide/internet/irccommande.html#msg \ No newline at end of file diff --git a/Additional/Notes/functions b/Additional/Notes/functions deleted file mode 100644 index bfc75d0..0000000 --- a/Additional/Notes/functions +++ /dev/null @@ -1,25 +0,0 @@ -socket -close -setsockopt -getsockname, -getprotobyname -gethostbyname -getaddrinfo, -freeaddrinfo -bind -connect -listen -accept, -htons -htonl -ntohs -ntohl -inet_addr -inet_ntoa, -send -recv -signal -lseek -fstat -fcntl -poll \ No newline at end of file diff --git a/Additional/Notes/pseudo/pseudo_coda.hpp b/Additional/Notes/pseudo/pseudo_coda.hpp deleted file mode 100644 index c2d4c19..0000000 --- a/Additional/Notes/pseudo/pseudo_coda.hpp +++ /dev/null @@ -1,89 +0,0 @@ -#pragma once -#include -#include - -class Client -{ - private: - std::string identifier; - public: - Client(); - ~Client(); -}; - -class Server -{ - private: - char name[63]; - std::vector connected; - - public: - Server(); - ~Server(); -}; - -class User -{ - private: - std::string _username; - char _nickname[9]; // availabilty. - std::vector _oldNames; // - int _mode; //mode infos - bool _isOperator; - public: - void whoIs(User const & target) const; - std::string getFullname() const; - void quit(); - User(); - ~User(); -}; - - -class Operator : public User -{ - private: - /* data */ - public: - void disconnectServer(); - void reconnectServer(); - void removeUser(); - void closeConnexionUserServer(); - Operator(/* args */); - ~Operator(); -}; - -class Services -{ - private: - /* data */ - char _nickname[9]; - std::string _serverName; - public: - Services(/* args */); - ~Services(); -}; - -class Channel -{ - private: - /* data */ - // it SHALL NOT contain any spaces (' '), a control G (^G or ASCII 7), a comma (','). - char _name[50]; // (beginning with a '&', '#', '+' or '!' character) - // Channel names are case insensitive. - public: - Channel(/* args */); - ~Channel(); -}; - -class Message -{ - private: - /* data */ - std::string _sender; - public: - std::string getSender(); - Message(/* args */); - ~Message(); -}; - - diff --git a/Additional/Notes/text.txt b/Additional/Notes/text.txt deleted file mode 100644 index 77e0e01..0000000 --- a/Additional/Notes/text.txt +++ /dev/null @@ -1,271 +0,0 @@ -Vocabulary check: UDP,TCP,FTP -OSI 7 layers -Application (Game Events) {Input Updates, State Updates} -Presentation (Game Packetization) {Serialization, Buffering} -Session (Connection & Data Exchange) {Sockets} -Transport {Tcp Udp} -Network {IP} -Data Link {(Mac) Ethernet} -Physical. - - -Architecture. - -The connetion is always between twho devices, -and each side uses its own IP and port number. -Usually, one side is called the client , -the other side the server. - -The server is continually waiting for incoming connections. -This is called listening which is always done on a ceratin IP and port number. - - -IP addresses. - -Both Srv and cli use an ip and port num. -The ip adress of both -server and client is configured during network setup unless it is allocated dynamically. -A machine may have more than one network interface card -(NIC), in which case it may have more than one IP adress. -When developing Network Programs the port number of the -server is usually specified within the code, whereas the client -port number is allocated by the o/s. -The loopback adress 127.0.0.1 refers to the current machine. -This can be used during development to test both -client and server on a single machine. - - -Ports -For machine to send and receive data. -21 port is ftp (file transfer protocol). - ----------------------------------------------------------------------------------------- - -Sockets -Definition: A pip between two computers on a network through which data flows. -Tcp:streaming Socket (secure connection between client and server). -Udp: Datagram socket (less reliable). - -Binding the ip and port makes a server socket unbound -> bound -Binding is basically adding info to socket. -After the socket is bound, it is put into the listening state, waiting -for incoming connections on the port (in this example port 5555) unbound -> bound -> listening. - -for a client to connect to the server it creates its own socket. -client makes a request. once the request is admited. The listening server is duplicated. The -reason why the listening socket will keep listening for other connections. - - -Data Transfer: -On layered models ( cf. how the data is physically transmitted) : - -Data < TFTP < UDP < IP < Ethernet - -Pratical application of a layered model : -Application Layer (telnet, ftp, etc.) -Host-to-Host Transport Layer (TCP, UDP) -Internet Layer (IP and routing) -Network Access Layer (Ethernet, wi-fi, or whatever) - - -About building a simple packet : " All you have to do for stream sockets is send() the data out." - - -Host byte Order : sur les ordis parfois les valeurs sont stored à l'envers (cf. little Endian avec Intel - vs Big Endian). -Pour être sûrs que tout rentre dans l'ordre : h(ost) to n(etwork) s(hort) <---- -=> la htons() fonction s'occupe de tout convertir dans le bon ordre! - ----------------------------------------------------------------------------------------- - -Socket closer look. ------------ - -Server: -Initialize. -create a socket. socket() -bind the socket. bind() -listen on the socket. listen(). -accept a connection. accept(), connect() -send and receive data. recv(), send(), recvfrom(), sendto(). -disconect. closesocket(). - -Cheat sheet : -Socket: Create a new communication -Bind: Attach a local address to a socket -Listen: Announce willingness to accept connections -Accept: Block caller until a connection request arrives -Connect: Actively attempt to establish a connection -Send: Send some data over a connection -Receive: Receive some data over a connection -Close: Release the connection - -Server Socket -1. create a socket - Get the file descriptor! (socket()) -2. bind to an address -What port am I on? (bind()) -3. listen on a port, and wait for a connection to be established. (listen()) -4. accept the connection from a client. (accept(), connect()) -5. send/recv - the same way we read and write for a file. (send(), recv()) -6. shutdown to end read/write. -7. close to releases data. (close()) - -Creating: -int socket(int af, int type, int protocol); -af: the adress family specification . AF_INET for udp or tcp. -type: the type spec. for the new socket(SOCK_STREAM for tcp and SOCK_DGRAM for udp). -protocol: the protocol to be used (IPPROTO_TCP for tcp). - -Bind: -int bind(Socket s, const struct sockaddr* name, int socklen); -s:Descriptor identifying an unbound socket. -name: Adress to assign to the socket from the sockaddr structure. -socklen: length in bytes of the adress structure. -Error: returns SOCKET_ERROR if error or 0 if ok. - -sockaddr * [XSI] Structure used by kernel to store most addresses. -sockaddr_in * Socket address, internet style. - -the typecast is for compatibility. - -Listen: -int listen(Socket s, int backlog); -s: Descriptor identifying a bound, unconnected socket. -backlog: The maximum number of connections allowed. - -if no error occurs, listen returns zero. SOCKET_ERROR if error. - -Accept: -Socket accept(Socket s, struct sockaddr* addr, int * addrlen); -s: Descriptor that identifies a socket that has been placed -in a listening state with the listen() function. -addr: optional structure containing the client adress information. -addrlen: Optional size of the adress structure. -accept returns an other socket which is dedicated on listening the client. - ------ -Client - side: - -1. create a socket. -2. connect to a server. -3. send/recv - repeat until we have or receive data -4. shutdown to end read/write. -5. close to releases data. - - -Connect: -int connect(Socket s, const struct sockaddr* addr, socklen_t addrlen); -s: Descriptor that identifies a socket. -addr: structure containing server IP adress and port. -addrlen: size in bytes of addr structure. -connect will wait 75 seconds for server to respond. -returns 0 if successful or socket_error if not. - ----------------------------------------------------------------------------------------- - -Detailed Structs. - -Structs - -int Socket descriptor; - -1) struct addrinfo { - int ai_flags; // AI_PASSIVE, AI_CANONNAME, etc. - int ai_family; // AF_INET, AF_INET6, AF_UNSPEC - int ai_socktype; // SOCK_STREAM, SOCK_DGRAM - int ai_protocol; // use 0 for "any" - size_t ai_addrlen; // size of ai_addr in bytes - struct sockaddr *ai_addr; // struct sockaddr_in or _in6 - char *ai_canonname; // full canonical hostname - struct addrinfo *ai_next; // linked list, next node -}; - -getaddrinfo() = returns a pointer to a new linked list of the struct addrinfo filled out. - -Inside the struct addrinfo, there is the struct sockaddr: -2) struct sockaddr { - unsigned short sa_family; // address family, AF_xxx - char sa_data[14]; // 14 bytes of protocol - address -}; - -sa_data contains a destination address and port number for the socket. - -To deal with Ipv4: - -3)struct sockaddr_in { - short sin_family; - unsigned short sin_port; - struct in_addr sin_addr; - char sin_zero[8]; -}; -sin_family: address family must be AF_INET. -sin_port: IP port. -sin_addr: IP adress. -sin_zero: padding to make structure the same size as SOCKADDR. the htons fuction returns the -value in TCP/IP network byte order. - -=> "So even though connect() wants a struct sockaddr*, -you can still use a struct sockaddr_in and cast it at the last minute!" - -More details on the struct: -sin_zero should be set to all 0 using memset() -sin_familiy corresponds to sa_family in sockaddr and should be set to AF_INET -sin_port must be in Network Byte Order using htons() - -sin_addr is a struct in_addr, which is : -4) struct in_addr { - uint32_t s_addr; // that's a 32-bit int (4 bytes) -}; - -5) struct sockaddr_storage that is -designed to be large enough to hold both IPv4 and IPv6 structures. -"See, for some calls, -sometimes you don’t know in advance if it’s going to fill out your struct sockaddr -with an IPv4 or IPv6 address. So you pass in this parallel structure, very similar to -struct sockaddr except larger, and then cast it to the type you need " (struct sockaddr_in for IPv4 for intstance) - -struct sockaddr_storage { - sa_family_t ss_family; // address family - - // all this is padding, implementation specific, ignore it: - char __ss_pad1[_SS_PAD1SIZE]; - int64_t __ss_align; - char __ss_pad2[_SS_PAD2SIZE]; -}; - ----------------------------------------------------------------------------------------- - -IP Adresses - -inet_pton() => converts an IP address in numbers into a struct in(6)_addr -- pton => printable to network - - -Example : -struct sockaddr_in sa; -inet_pton(AF_INET, "10.12.110.57", &(sa.sin_addr)); - -Pour les conversions inverses, il faut utiliser inet_ntop(). - -char ip4[INET_ADDRSTRLEN]; -struct sockaddr_in sa; -inet_ntop(AF_INET, &(sa.sin_addr), ip4, INET_ADDRSTRLEN); - ----------------------------------------------------------------------------------------- - -Systems calls -= we get into the ones that allow you to access the network functionality of any box -that supports the sockets API - -Order of these system calls : -1) getaddrinfo() -2) socket() => get the file descriptor - - int socket(int domain, int type, int protocol); - int socket(IPv4, SOCK_STREAM, tcp); -3) bind() => what port am i on? -4) connect() -5) listen() -6) accept() -7) send() et recv() -8) close() et shutdown() -9) getpeername() -10) gethostname() \ No newline at end of file diff --git a/Additional/README.md b/Additional/README.md deleted file mode 100644 index 30d720b..0000000 --- a/Additional/README.md +++ /dev/null @@ -1,128 +0,0 @@ - -## :zap: Summary - -1. [About the project](https://github.com/marineks/Ft_irc#school_satchel-about-this-project) -* [Definition](https://github.com/marineks/Ft_irc#_-crystal_ball-definition) -* [Subject requirements](https://github.com/marineks/Ft_irc#_-floppy_disk-subject-requirements) -* [Commands that we implemented](https://github.com/marineks/Ft_irc#high_brightness-commands-that-we-implemented-) -2. [Some tips, graphs and other ressources](https://github.com/marineks/Ft_irc#gift-some-tips-graphs-and-other-ressources) -* [Helpful links](https://github.com/marineks/Ft_irc#_-books-helpful-links) -* [Tips](https://github.com/marineks/Ft_irc#_-books-helpful-links) -___ -## :school_satchel: About this project - - -The objective of this project is to reproduce the functioning of an IRC server. - -### _ :crystal_ball: Definition - - -> "IRC (Internet Relay Chat) is a **protocol for real-time text messaging between internet-connected computers created in 1988**. It is mainly used for group discussion in chat rooms called “channels” although it supports private messages between two users, data transfer, and various server-side and client-side commands. As of April 2011, the top 100 IRC networks served over 500,000 users at a time on hundreds of thousands of channels." ([source](https://www.radware.com/security/ddos-knowledge-center/ddospedia/irc-internet-relay-chat/)) - - - -### _ :floppy_disk: Subject requirements - - -**1.** Code the IRC server in C++98 -**2.** Your binary should look like this : `./ircserv ` -**3.** You should use `poll()` and only **once**. -**4.** The client/server communication will be TCP/IP (v4 or v6) -**5.** The following features are mandatory : -> **i)** You should be able to register, i.e to define a nickname, a username - -> **ii)** You should be able to join a channel, send or receive private messages - -> **iii)** Every message sent by a client in a channel must be received by all of the clients who have joined this channel - -> **iv)** You should have normal users and operators, and implement the operators' specific commands -**6.** No leaks (even still reachables) and handle the signals (partial messages with `CTRL+D`, suspended process with `CTRL+Z`, and obviously SIGINT (`CTRL+C`)) -**7.** (bonuses) implement a bot + file transfer. - - -___ -### :high_brightness: Commands that we implemented : - - - -| Command | Description | -| :-----------: | :----------- | -| Invite | The `INVITE` command is used to invite a user to a channel. | -| Join | The `JOIN` command indicates that the client wants to join the given channel(s), each channel using the given key for it. | -| Kick | The `KICK` command can be used to request the forced removal of a user from a channel. | -| Kill | The `KILL` command is used to close the connection between a given client and the server they are connected to. `KILL` is a privileged command and is available only to IRC Operators. | -| List | The `LIST` command is used to get a list of channels along with some information about each channel. | -| Mode | The `MODE` command is used to set or remove options (or modes) from a given target. Our user modes : i, o. Our channels modes: b,k,m,o,p,s,t,v | -| Motd | The `MOTD` command is used to get the “Message of the Day” of the given server. | -| Names | The `NAMES` command is used to view the nicknames joined to a channel and their channel membership prefixes. | -| Nick | The `NICK` command is used to give the client a nickname or change the previous one. | -| Notice | The `NOTICE` command is used to send notices between users, as well as to send notices to channels. The difference between `NOTICE` and `PRIVMSG` is that automatic replies must never be sent in response to a `NOTICE` message. | -| Oper | The `OPER` command is used by a normal user to obtain IRC operator privileges. | -| Part | The `PART` command removes the client from the given channel(s). | -| Pass | The `PASS` command is used to set a ‘connection password’. If set, the password must be set before any attempt to register the connection is made. | -| Ping | The `PING` command is sent by either clients or servers to check the other side of the connection is still connected and/or to check for connection latency, at the application layer. | -| Privmsg | The `PRIVMSG` command is used to send private messages between users, as well as to send messages to channels. | -| Quit | The `QUIT` command is used to terminate a client’s connection to the server. The server acknowledges this by replying with an `ERROR` message and closing the connection to the client. | -| Topic | The `TOPIC` command is used to change or view the topic of the given channel. | -| User | The `USER` command is used at the beginning of a connection to specify the username and realname of a new user. | - -## :gift: Some tips, graphs and other ressources - - -### _ :books: Helpful links - - -- **To understand what exactly is an IRC and begin the project** : [Chirc](http://chi.cs.uchicago.edu/chirc/irc.html) (An irc subject from a Chicago uni) and the next pages too. - - -- **Regarding the client/server connection** : [Beej's Guide to network programming](https://beej.us/guide/bgnet/pdf/bgnet_a4_c_1.pdf). This is super super helpful to better understand what is a socket, what the `poll()` function entails, which system calls we should use or in which order, and so on. - - -

- -- **A link to the IRC Client Protocol with a good formatting** : [Modern IRC Client Protocol](https://modern.ircdocs.horse/). You will find there a description of all the commands with correct syntax, expected Numerical Replies,... - - -### _ :mailbox: Tips - - -- **A suggestion of project roadmap :** - 1- Begin by establishing a working client/server socket connection, - 2- Then build on that : add the signals handling (`CTRL+C`, `CTRL+D`, `CTRL+Z`); - 3- ***Only*** then begin the client registration system (`NICK`, `USER`, `PASS`), - 4- The server commands (`PING`, `OPER`, `KILL`...) and - 5- The channel operations commands (`JOIN`, `PART`, `INVITE`, `KICK`, `PRIVMSG`, `NOTICE`...). - - - ___ - -- **Help, my code works perfectly with irssi but not with nc!** If you have this kind of issue, this is because, like us, you made the mistake of coding with irssi first and not nc :grimacing: Keep in mind that nc is very "minimalist" compared to irssi. That means that irssi will send you everything at once : the command, and the CRLF ending (`\r\n`). It will also append the `:` in some cases (for instance `TOPIC #channel :message`). - - - *This is not the case with nc* : you will have to concatenate the messages sent by the Client until you find the proper "end" (the CRLF). **That means that you should have a (read) buffer ==for each client== connected to your server**. Bonus: this will take care of he `CTRL+D` signal too! :smirk: - - - So now, if you follow us, you should guess that, for each client, **you will need a (send) buffer as well**! This will be very efficient in taking care of the `CTRL+Z` signal :innocent: . Don't forget to also check the `POLLIN and POLLOUT revents` in your server loop... - - ___ - -- **How to know how to correctly format a RPL to be understood by your IRC client of reference** (for instance, irssi) ? - . - - Join an existing server (try `/connect DALNET`), then enter the command `/RAWLOG OPEN debug.log` [(more doc)](https://irssi.org/documentation/help/rawlog/), and try the commands you're having some troubles with. This will open a log file in your workspace containing the all the exact client/server interactions for these commands, such as : - ```c - // [...] - << JOIN #help // from the client - >> :nickname!username@host JOIN :#help // reply from the server - // [...] - ``` - Voilà ! Now you know you forgot the `:` before the channel name! ;) - - ___ -- **Okay, now you have a good format but the code is not clean at all?** Try to use dynamic macros in this way (*we guarantee this is a life changer/saver!*) : - ```cpp - #define user_id(nickname, username) (":" + nickname + "!" + username + "@localhost") - #define RPL_INVITE(user_id, invited, channel) (user_id + " INVITE " + invited + " #" + channel + "\r\n") - // [...] - #define ERR_INVALIDMODEPARAM(client, channel, mode, password) ("696 " + client + " #" + channel + " " + mode + " " + password + " : password must only contained alphabetic character\r\n") - ``` \ No newline at end of file diff --git a/Additional/RPLS.hpp b/Additional/RPLS.hpp deleted file mode 100644 index f856774..0000000 --- a/Additional/RPLS.hpp +++ /dev/null @@ -1,64 +0,0 @@ -#ifndef FT_IRC_HPP -# define FT_IRC_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define ERR_UNKNOWNCOMMAND(source, command) "421 " + source + " " + command + " :Unknown command" -#define ERR_NEEDMOREPARAMS(source, command) "461 " + source + " " + command + " :Not enough parameters" -#define ERR_NOTREGISTERED(source) "451 " + source + " :You have not registered" -#define ERR_ALREADYREGISTERED(source) "462 " + source + " :You may not reregister" -#define ERR_PASSWDMISMATCH(source) "464 " + source + " :Password incorrect" -#define ERR_NONICKNAMEGIVEN(source) "431 " + source + " :Nickname not given" -#define ERR_NICKNAMEINUSE(source) "433 " + source + " " + source + " :Nickname is already in use" -#define ERR_TOOMANYCHANNELS(source, channel) "405 " + source + " " + channel + " :You have joined too many channels" -#define ERR_NOTONCHANNEL(source, channel) "442 " + source + " " + channel + " :You're not on that channel" -#define ERR_NOSUCHCHANNEL(source, channel) "403 " + source + " " + channel + " :No such channel" -#define ERR_BADCHANNELKEY(source, channel) "475 " + source + " " + channel + " :Cannot join channel (+k)" -#define ERR_NOSUCHNICK(source, nickname) "401 " + source + " " + nickname + " :No such nick/channel" -#define ERR_USERNOTINCHANNEL(source, nickname, channel) "441 " + source + " " + nickname + " " + channel + " :They aren't on that channel" -#define ERR_CHANOPRIVSNEEDED(source, channel) "482 " + source + " " + channel + " :You're not channel operator" -#define ERR_CHANNELISFULL(source, channel) "471 " + source + " " + channel + " :Cannot join channel (+l)" -#define ERR_CANNOTSENDTOCHAN(source, channel) "404 " + source + " " + channel + " :Cannot send to channel" - -// NUMERIC REPLIES -#define RPL_WELCOME(source) "001 " + source + " :Welcome " + source + " to the ft_irc network" -#define RPL_NAMREPLY(source, channel, users) "353 " + source + " = " + channel + " :" + users -#define RPL_ENDOFNAMES(source, channel) "366 " + source + " " + channel + " :End of /NAMES list." - -// COMMAND REPLIES -#define RPL_JOIN(source, channel) ":" + source + " JOIN :" + channel -#define RPL_PART(source, channel) ":" + source + " PART :" + channel -#define RPL_PING(source, token) ":" + source + " PONG :" + token -#define RPL_PRIVMSG(source, target, message) ":" + source + " PRIVMSG " + target + " :" + message -#define RPL_NOTICE(source, target, message) ":" + source + " NOTICE " + target + " :" + message -#define RPL_QUIT(source, message) ":" + source + " QUIT :Quit: " + message -#define RPL_KICK(source, channel, target, reason) ":" + source + " KICK " + channel + " " + target + " :" + reason -#define RPL_MODE(source, channel, modes, args) ":" + source + " MODE " + channel + " " + modes + " " + args - -#define BUFFER_SIZE 4096 -#define USER_MAX 100 - -int errCheck(int cnd, int res, std::string msg); -void exitErr(std::string msg); -void serverInfo(const std::string &message); -void ft_write(int _fd, const std::string &message); -std::string toUpper(std::string str); - -#endif \ No newline at end of file diff --git a/Additional/assets/irc.png b/Additional/assets/irc.png deleted file mode 100644 index 590c60e..0000000 Binary files a/Additional/assets/irc.png and /dev/null differ diff --git a/Additional/assets/network.png b/Additional/assets/network.png deleted file mode 100644 index 3ec7f71..0000000 Binary files a/Additional/assets/network.png and /dev/null differ diff --git a/Additional/en.subject.pdf b/Additional/en.subject.pdf deleted file mode 100644 index 9756c50..0000000 Binary files a/Additional/en.subject.pdf and /dev/null differ diff --git a/Additional/ft_irc-evaluation.pdf b/Additional/ft_irc-evaluation.pdf deleted file mode 100644 index d1160b8..0000000 Binary files a/Additional/ft_irc-evaluation.pdf and /dev/null differ diff --git a/Additional/irrsi/Gorkem_Ahmet/includes/utils.hpp b/Additional/irrsi/Gorkem_Ahmet/includes/utils.hpp deleted file mode 100644 index 16779bb..0000000 --- a/Additional/irrsi/Gorkem_Ahmet/includes/utils.hpp +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef UTILS_HPP -# define UTILS_HPP - -# include "colors.hpp" - -#define ERR_UNKNOWNCOMMAND(source, command) "421 " + source + " " + command + " :Unknown command" -#define ERR_NEEDMOREPARAMS(source, command) "461 " + source + " " + command + " :Not enough parameters" -#define ERR_NOTREGISTERED(source) "451 " + source + " :You have not registered" -#define ERR_ALREADYREGISTERED(source) "462 " + source + " :You may not reregister" -#define ERR_PASSWDMISMATCH(source) "464 " + source + " :Password incorrect" -#define ERR_NONICKNAMEGIVEN(nickname) "431 " + nickname + " :Nickname not given" -#define ERR_NICKNAMEINUSE(nickname) "433 " + nickname + " " + nickname + " :Nickname is already in use" -#define ERR_TOOMANYCHANNELS(source, channel) "405 " + source + " " + channel + " :You have joined too many channels" -#define ERR_NOTONCHANNEL(source, channel) "442 " + source + " " + channel + " :You're not on that channel" -#define ERR_NOSUCHCHANNEL(source, channel) "403 " + source + " " + channel + " :No such channel" -#define ERR_BADCHANNELKEY(source, channel) "475 " + source + " " + channel + " :Cannot join channel (+k)" -#define ERR_NOSUCHNICK(source, nickname) "401 " + source + " " + nickname + " :No such nick/channel" -#define ERR_USERNOTINCHANNEL(source, nickname, channel) "441 " + source + " " + nickname + " " + channel + " :They aren't on that channel" -#define ERR_CHANOPRIVSNEEDED(source, channel) "482 " + source + " " + channel + " :You're not channel operator" -#define ERR_CHANNELISFULL(source, channel) "471 " + source + " " + channel + " :Cannot join channel (+l)" -#define ERR_CANNOTSENDTOCHAN(source, channel) "404 " + source + " " + channel + " :Cannot send to channel" -#define ERR_ERRONEUSNICKNAME(source, nick) "432 " + source + " " + nick + " :Erroneous nickname" -#define ERR_UMODEUNKNOWNFLAG(source, nick) "501 " + source + " " + nick + " :Unknown MODE flag" -#define ERR_USERSDONTMATCH(source) "502 " + source + " :Cannot change mode for other users" - -// NUMERIC REPLIES -#define RPL_WELCOME(source, server) "001 " + source + " :" + B_GREEN + "Welcome " + source + " to the " + server + " server!" + END -#define RPL_NAMREPLY(source, channel, users) "353 " + source + " = " + channel + " :" + users -#define RPL_ENDOFNAMES(source, channel) "366 " + source + " " + channel + " :End of /NAMES list." -#define RPL_WHOISUSER(source, nickname, username, hostname, port, realname) "311 " + source + " " + nickname + " ~" + username + " " + hostname + ":" + port + " * :" + realname -#define RPL_WHOISSERVER(source, server) "312 " + source + " * :" + server -#define RPL_WHOISCHANNELS(source, nickname, channels) "319 " + source + " " + nickname + " :" + channels -#define RPL_ENDOFWHOIS(source, nickname) "318 " + source + " " + nickname + " :End of /WHOIS list" -#define RPL_TOPIC(source, channel, topic) "332 " + source + " " + channel + " :" + topic -#define RPL_WHOREPLY(source, channel, user, host, server, nick, flag, hopcount, realname) "352 " + source + " " + channel + " " + user + " " + host + " " + server + " " + nick + " H" + flag + " :" + hopcount + " " + realname -#define RPL_ENDOFWHO(source, channel) "315 " + source + " " + channel + " :End of WHO list" -#define RPL_LISTSTART(client) "321 " + client + " Channel - Users Count - Channel Topic" -#define RPL_LIST(client, channel, clientCount, topic) "322 " + client + " " + channel + " - " + clientCount + " - :" + topic -#define RPL_LISTEND(client) "323 " + client + " :End of /LIST" -#define RPL_INFO(client, string) "371 " + client + " :" + string -#define RPL_ENDOFINFO(client) "374 " + client + " :End of INFO list" -//410 CAP END bilgini tekrardan istiyor. - -// COMMAND REPLIES -#define RPL_JOIN(source, channel) ":" + source + " JOIN :" + channel -#define RPL_PART(source, channel, message) ":" + source + " PART " + channel + " " + message // :" + message -#define RPL_PING(source, token) ":" + source + " PONG :" + token -#define RPL_PONG(source, token) ":" + source + " PING :" + token -#define RPL_PRIVMSG(source, target, message) ":" + source + " PRIVMSG " + target + " " + message // :" + message -#define RPL_NOTICE(source, target, message) ":" + source + " NOTICE " + target + " :" + message -#define RPL_QUIT(source, message) ":" + source + " QUIT :Quit: " + message -#define RPL_KICK(source, channel, target, reason) ":" + source + " KICK " + channel + " " + target + " " + reason // :" + reason -#define RPL_MODE(source, channel, modes, args) ":" + source + " MODE " + channel + " " + modes + " " + args -#define RPL_NICK(source, nickname) ":" + source + " NICK " + nickname -#define ERROR(source, message) ":" + source + " ERROR " + " :" + message - -#endif diff --git a/Additional/tests/Icmp/Ping.cpp b/Additional/tests/Icmp/Ping.cpp deleted file mode 100644 index 5a7ee0a..0000000 --- a/Additional/tests/Icmp/Ping.cpp +++ /dev/null @@ -1,86 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// ICMP başlığı hesaplama işlevi -unsigned short calculateChecksum(unsigned short* buffer, int size) { - unsigned long sum = 0; - while (size > 1) { - sum += *buffer++; - size -= sizeof(unsigned short); - } - if (size) { - sum += *(unsigned char*)buffer; - } - sum = (sum >> 16) + (sum & 0xFFFF); - sum += (sum >> 16); - return (unsigned short)(~sum); -} - -int main(int argc, char* argv[]) { - if (argc != 2) { - std::cerr << "Kullanım: " << argv[0] << " " << std::endl; - return 1; - } - - // Hedef IP adresi komut satırından alınır - const char* targetIP = argv[1]; - - // Bir soket oluştur - int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); - if (sockfd == -1) { - perror("Soket oluşturma hatası"); - exit(EXIT_FAILURE); - } - - // ICMP isteği için bir paket oluştur - char packet[64]; - struct ip* ipHeader = (struct ip*)packet; - struct icmphdr* icmpHeader = (struct icmphdr*)(packet + sizeof(struct ip)); - - // ICMP paketi için başlık bilgilerini ayarla - icmpHeader->type = ICMP_ECHO; - icmpHeader->code = 0; - icmpHeader->checksum = 0; - icmpHeader->un.echo.id = getpid(); - icmpHeader->un.echo.sequence = 0; - - // Hedef IP adresini ayarla - if (inet_pton(AF_INET, targetIP, &(ipHeader->ip_dst)) <= 0) { - perror("Geçersiz hedef IP adresi"); - close(sockfd); - exit(EXIT_FAILURE); - } - - // ICMP paketi için checksum hesapla - icmpHeader->checksum = calculateChecksum((unsigned short*)icmpHeader, sizeof(struct icmphdr)); - - // ICMP isteği gönder - if (sendto(sockfd, packet, sizeof(packet), 0, (struct sockaddr*)&(ipHeader->ip_dst), sizeof(struct sockaddr_in)) == -1) { - perror("ICMP isteği gönderme hatası"); - close(sockfd); - exit(EXIT_FAILURE); - } - - // ICMP yanıtını bekleyin ve ekrana yazdırın - char responsePacket[64]; - ssize_t bytesRead = recv(sockfd, responsePacket, sizeof(responsePacket), 0); - if (bytesRead == -1) { - perror("ICMP yanıtı alma hatası"); - } else { - std::cout << "ICMP yanıtı alındı." << std::endl; - } - - // Soketi kapat - close(sockfd); - - return 0; -} diff --git a/Additional/tests/Icmp/icmp.txt b/Additional/tests/Icmp/icmp.txt deleted file mode 100644 index 60bdcfa..0000000 --- a/Additional/tests/Icmp/icmp.txt +++ /dev/null @@ -1,2 +0,0 @@ -Okulda calistirmiyor. -SOCK_RAW kullanarak yapabiliyoruz sudo izinine ihtiyac var. (neden i don't kno, ogrenen olursa anlatsin.) \ No newline at end of file diff --git a/Additional/tests/test1/client.c b/Additional/tests/test1/client.c deleted file mode 100644 index 43407b4..0000000 --- a/Additional/tests/test1/client.c +++ /dev/null @@ -1,48 +0,0 @@ -// Client side C/C++ program to demonstrate Socket -// programming -#include -#include -#include -#include -#include -#define PORT 8080 - -int main(int argc, char const* argv[]) -{ - int status, valread, client_fd; - struct sockaddr_in serv_addr; - char* hello = "Hello from client"; - char buffer[1024] = { 0 }; - if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { - printf("\n Socket creation error \n"); - return -1; - } - - serv_addr.sin_family = AF_INET; - serv_addr.sin_port = htons(PORT); - - // Convert IPv4 and IPv6 addresses from text to binary - // form - if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) - <= 0) { - printf( - "\nInvalid address/ Address not supported \n"); - return -1; - } - - if ((status - = connect(client_fd, (struct sockaddr*)&serv_addr, - sizeof(serv_addr))) - < 0) { - printf("\nConnection Failed \n"); - return -1; - } - send(client_fd, hello, strlen(hello), 0); - printf("Hello message sent\n"); - valread = read(client_fd, buffer, 1024); - printf("%s\n", buffer); - - // closing the connected socket - close(client_fd); - return 0; -} diff --git a/Additional/tests/test1/server.c b/Additional/tests/test1/server.c deleted file mode 100644 index 9b38897..0000000 --- a/Additional/tests/test1/server.c +++ /dev/null @@ -1,64 +0,0 @@ -// Server side C/C++ program to demonstrate Socket -// programming -#include -#include -#include -#include -#include -#include -#define PORT 8080 -int main(int argc, char const* argv[]) -{ - int server_fd, new_socket, valread; - struct sockaddr_in address; - int opt = 1; - int addrlen = sizeof(address); - char buffer[1024] = { 0 }; - char* hello = "Hello from server"; - - // Creating socket file descriptor - if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { - perror("socket failed"); - exit(EXIT_FAILURE); - } - - // Forcefully attaching socket to the port 8080 - if (setsockopt(server_fd, SOL_SOCKET, - SO_REUSEADDR | SO_REUSEPORT, &opt, - sizeof(opt))) { - perror("setsockopt"); - exit(EXIT_FAILURE); - } - address.sin_family = AF_INET; - address.sin_addr.s_addr = INADDR_ANY; - address.sin_port = htons(PORT); - - // Forcefully attaching socket to the port 8080 - if (bind(server_fd, (struct sockaddr*)&address, - sizeof(address)) - < 0) { - perror("bind failed"); - exit(EXIT_FAILURE); - } - if (listen(server_fd, 3) < 0) { - perror("listen"); - exit(EXIT_FAILURE); - } - if ((new_socket - = accept(server_fd, (struct sockaddr*)&address, - (socklen_t*)&addrlen)) - < 0) { - perror("accept"); - exit(EXIT_FAILURE); - } - valread = read(new_socket, buffer, 1024); - printf("%s\n", buffer); - send(new_socket, hello, strlen(hello), 0); - printf("Hello message sent\n"); - - // closing the connected socket - close(new_socket); - // closing the listening socket - shutdown(server_fd, SHUT_RDWR); - return 0; -} diff --git a/Additional/tests/test10/info.txt b/Additional/tests/test10/info.txt deleted file mode 100644 index ae092d7..0000000 --- a/Additional/tests/test10/info.txt +++ /dev/null @@ -1 +0,0 @@ -Omer ile beraber yaptigim. \ No newline at end of file diff --git a/Additional/tests/test10/main.cpp b/Additional/tests/test10/main.cpp deleted file mode 100644 index 25de915..0000000 --- a/Additional/tests/test10/main.cpp +++ /dev/null @@ -1,127 +0,0 @@ -#include "server.hpp" - -int main() -{ - int sockFd = createSocket(8080); - sockaddr_in cliAddr; - socklen_t cliSize; - int cliFd; - int readed; - char buffer[1024]; - char clientIP[INET_ADDRSTRLEN]; - int cliPort; - client tmp; - server mysw; - mysw.serverFd = sockFd; - cliSize = sizeof(sockaddr_in); - cliFd = -1; - int state = 0; - - - fd_set readFds; - fd_set writeFds; - fd_set readFdsSup; - fd_set writeFdsSup; - // initializes sets of file descriptors (FD_SET) for tracking read and write events. - // The server socket (sockFd) is added to the read FD set. - FD_ZERO(&readFds); - FD_ZERO(&writeFds); - FD_ZERO(&readFdsSup); - FD_ZERO(&writeFdsSup); - - - - FD_SET(sockFd, &readFds); - int k = -1; - while (1) - { - while (state == 0) - { - // Wait for an event using select - readFdsSup = readFds; - writeFdsSup = writeFds; - state = select(mysw.findMaxFd() + 1, &readFdsSup, &writeFdsSup, NULL, 0); - std::cout << ++k << " "; - /* - * The program enters an infinite loop where it waits for events using the select function. - * It waits until state becomes non-zero, - * which means an event has occurred. - */ - } - - if (FD_ISSET(sockFd, &readFdsSup))//? client nasil giriyor. - { - cliFd = accept(sockFd, (sockaddr *)&cliAddr, &cliSize); - cliPort = ntohs(cliAddr.sin_port); - std::cout << "Top G:" << inet_ntop(AF_INET, &(cliAddr.sin_addr), clientIP, INET_ADDRSTRLEN) << std::endl; // insanlar okuyabilsin diye. - tmp.cliFd = cliFd; - tmp.ipAddr = clientIP; - tmp.port = cliPort; - mysw.clients.push_back(tmp); - FD_SET(cliFd, &readFds); // clienti readable fp - - std::cout << "New Client Connected!" << std::endl; - state = 0; - } - - for(std::vector::iterator begin = mysw.clients.begin(); begin != mysw.clients.end() && state;++begin) - { - if (FD_ISSET((*begin).cliFd, &readFdsSup)) - { - std::cout << k << " read" << std::endl; - readed = read((*begin).cliFd, buffer, 1024);// - if (readed <= 0) - { - FD_CLR((*begin).cliFd, &readFds); - FD_CLR((*begin).cliFd, &writeFds); - close((*begin).cliFd); - mysw.clients.erase(begin);//! - std::cout << "A client disconnected!" << std::endl; - } - else - { - buffer[readed] = 0; - for(std::vector::iterator it = mysw.clients.begin(); it != mysw.clients.end();++it)//? - { - if (it != begin) - { - (*it).messageBox.push_back(buffer); - FD_SET((*it).cliFd, &writeFds); - } - - } - } - state = 0; - break; - } - } - - - - for(std::vector::iterator begin = mysw.clients.begin(); begin != mysw.clients.end() && state;++begin) - { - if (FD_ISSET((*begin).cliFd, &writeFdsSup)) - { - std::cout << k << " write" << std::endl; - readed = write((*begin).cliFd, (char *)(*begin).messageBox[0].c_str(), (*begin).messageBox[0].length()); - (*begin).messageBox.erase((*begin).messageBox.begin()); - - if ((*begin).messageBox.empty()) - FD_CLR((*begin).cliFd, &writeFds); - - if (readed <= 0) - { - FD_CLR((*begin).cliFd, &readFds); - FD_CLR((*begin).cliFd, &writeFds); - close((*begin).cliFd); - mysw.clients.erase(begin); - std::cout << "A client disconnected!" << std::endl; - } - state = 0; - break; - } - } - } - - -} \ No newline at end of file diff --git a/Additional/tests/test10/server.hpp b/Additional/tests/test10/server.hpp deleted file mode 100644 index ecfdbae..0000000 --- a/Additional/tests/test10/server.hpp +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include "unistd.h" -#include "iostream" -#include "sys/socket.h" -#include "arpa/inet.h" -#include "sys/types.h" -#include "string.h" -#include "vector" -#include "sys/select.h" - - -int createSocket(int portNo); - -class client -{ - public: - std::vector messageBox; - int cliFd; - int port; - std::string ipAddr; -}; - - -class server -{ - public: - std::vector clients; - int serverFd; - int findMaxFd(); -}; \ No newline at end of file diff --git a/Additional/tests/test10/socket.cpp b/Additional/tests/test10/socket.cpp deleted file mode 100644 index 07a1a75..0000000 --- a/Additional/tests/test10/socket.cpp +++ /dev/null @@ -1,53 +0,0 @@ -#include "server.hpp" - -int createSocket(int portNo) -{ - int sockFd; - sockaddr_in addr; - - - sockFd = socket(AF_INET, SOCK_STREAM, 0); - if (sockFd == -1) - { - std::cerr << "error" << std::endl; - exit(1); - } - - int opt = 1; - setsockopt(sockFd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); - - memset(&addr, 0, sizeof(sockaddr_in)); - addr.sin_addr.s_addr = htonl(INADDR_ANY); - addr.sin_family = AF_INET; - addr.sin_port = htons(portNo); - - if (bind(sockFd, (sockaddr *)&addr, sizeof(addr)) == -1) - { - std::cerr << "bind err" << std::endl; - close(sockFd); - exit(1); - } - - - if (listen(sockFd, 1024) == -1) - { - std::cerr << "listen err" << std::endl; - close(sockFd); - exit(1); - } - - return (sockFd); -} - - -int server::findMaxFd() -{ - int maxFd = this->serverFd; - - for(std::vector::iterator begin = this->clients.begin(); begin != this->clients.end(); begin++) - { - if (maxFd < (*begin).cliFd) - maxFd = (*begin).cliFd; - } - return (maxFd); -} \ No newline at end of file diff --git a/Additional/tests/test11/client.cpp b/Additional/tests/test11/client.cpp deleted file mode 100644 index 5ce78eb..0000000 --- a/Additional/tests/test11/client.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include \ No newline at end of file diff --git a/Additional/tests/test11/server.cpp b/Additional/tests/test11/server.cpp deleted file mode 100644 index 5759ee3..0000000 --- a/Additional/tests/test11/server.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include \ No newline at end of file diff --git a/Additional/tests/test2/client.c b/Additional/tests/test2/client.c deleted file mode 100644 index 66d19ed..0000000 --- a/Additional/tests/test2/client.c +++ /dev/null @@ -1,35 +0,0 @@ -#include -#include -#include -#include -#include - -int main() { - char *ip = "127.0.0.1"; - int port = 5566; - - int sock; - struct sockaddr_in addr; - socklen_t addr_size; - char buffer[1024]; - int n; - - sock = socket(AF_INET, SOCK_STREAM, 0); - if (sock < 0) { - perror("[-]Socket error"); - exit(EXIT_FAILURE); - } - printf("[+]TCP server socket created\n"); - - memset(&addr, '\0', sizeof(addr)); - addr.sin_family = AF_INET; // internet - addr.sin_port = port;// port - addr.sin_addr.s_addr = inet_addr(ip); // local adress - - // connect to the server - - connect(sock, (struct sockaddr*)&addr, sizeof(addr)); - printf("Connected to the server.\n"); - - return 0; -} \ No newline at end of file diff --git a/Additional/tests/test2/server.c b/Additional/tests/test2/server.c deleted file mode 100644 index d75857a..0000000 --- a/Additional/tests/test2/server.c +++ /dev/null @@ -1,58 +0,0 @@ -#include -#include -#include -#include -#include - -int main() { - char *ip = "127.0.0.1"; - - int port = 5566; - - int server_sock, client_sock; - struct sockaddr_in server_addr, client_addr; - - socklen_t addr_size; - - char buffer[1024]; - int n; - - - server_sock = socket(AF_INET, SOCK_STREAM, 0); - if (server_sock < 0) { - perror("[-]Socket error"); - exit(EXIT_FAILURE); - } - printf("[+]TCP server socket created\n"); - - memset(&server_addr, '\0', sizeof(server_addr)); - - server_addr.sin_family = AF_INET; // internet - server_addr.sin_port = port;// port - server_addr.sin_addr.s_addr = inet_addr(ip); // local adress - - - // bind ip adress and the port number - - n = bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr)); - if (n < 0) { - perror("[-]Bind error"); - exit(EXIT_FAILURE); - } - printf("[+]Bind to the port number: %d\n", port); - - - // listen command - - // server is waiting for the client - listen(server_sock, 5); - printf("Listening...\n"); - - while(1) { - addr_size = sizeof(client_addr); - client_sock = accept(server_sock, (struct sockaddr*)&client_addr, &addr_size); - printf("[+]Client connected. \n"); - } - - return 0; -} \ No newline at end of file diff --git a/Additional/tests/test3/server.cpp b/Additional/tests/test3/server.cpp deleted file mode 100644 index 29dd70c..0000000 --- a/Additional/tests/test3/server.cpp +++ /dev/null @@ -1,52 +0,0 @@ -#include -#include - -using namespace std; - - -int main() -{ - char* ip = "127.0.0.1"; - int port = 5566; - - int server_sock, client_sock; - - struct sockaddr_in server_addr, client_addr; - socklen_t addr_size; - - char buffer[1024]; - int n; - - server_sock = socket(AF_INET, SOCK_STREAM, 0); - if (server_sock < 0) { - perror("[-]Socket error"); - exit(EXIT_FAILURE); - } - cout << "[+]TCP server socket created" << endl; - memset(&server_addr, '\0', sizeof(server_addr)); - server_addr.sin_family = AF_INET; - server_addr.sin_port = port;// port - server_addr.sin_addr.s_addr = inet_addr(ip); // local adress - - n = bind(server_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)); - if (n < 0) { - perror("[-]Bind error"); - exit(EXIT_FAILURE); - } - printf("[+]Bind to the port number: %d\n", port); - - - // listen command - - // server is waiting for the client - listen(server_sock, 5); - printf("Listening...\n"); - - while(1) { - addr_size = sizeof(client_addr); - client_sock = accept(server_sock, (struct sockaddr*)&client_addr, &addr_size); - printf("[+]Client connected. \n"); - } - - return 0; -} \ No newline at end of file diff --git a/Additional/tests/test4/client.cpp b/Additional/tests/test4/client.cpp deleted file mode 100644 index 20de4ce..0000000 --- a/Additional/tests/test4/client.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include -#include -#include -#include -#include // Include this header for inet_pton -#include - -int main() { - int clientSocket = socket(AF_INET, SOCK_STREAM, 0); - - sockaddr_in serverAddr; - serverAddr.sin_family = AF_INET; - serverAddr.sin_port = htons(12345); // Port number - - // Convert IP address from string to binary form - if (inet_pton(AF_INET, "127.0.0.1", &serverAddr.sin_addr) <= 0) { - std::cerr << "Invalid address" << std::endl; - return 1; - } - - connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)); - - char buffer[1024]; - ssize_t bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0); - - if (bytesRead > 0) { - buffer[bytesRead] = '\0'; - std::cout << "Received: " << buffer << std::endl; - } else if (bytesRead == 0) { - std::cout << "Connection closed by server." << std::endl; - } else { - std::cerr << "Error in receiving data." << std::endl; - } - - close(clientSocket); - - return 0; -} diff --git a/Additional/tests/test4/server.cpp b/Additional/tests/test4/server.cpp deleted file mode 100644 index b711387..0000000 --- a/Additional/tests/test4/server.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#include -#include -#include -#include -#include - -int main() { - int serverSocket = socket(AF_INET, SOCK_STREAM, 0); - - sockaddr_in serverAddr; - serverAddr.sin_family = AF_INET; - serverAddr.sin_port = htons(12345); // Port number - serverAddr.sin_addr.s_addr = INADDR_ANY; - - bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)); - - listen(serverSocket, 1); - - std::cout << "Server listening..." << std::endl; - - sockaddr_in clientAddr; - socklen_t clientAddrLen = sizeof(clientAddr); - - int clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrLen); - - std::cout << "Client connected." << std::endl; - - const char* message = "Hello, client!"; - send(clientSocket, message, strlen(message), 0); - - close(clientSocket); - close(serverSocket); - - return 0; -} diff --git a/Additional/tests/test5/cli b/Additional/tests/test5/cli deleted file mode 100755 index e90800c..0000000 Binary files a/Additional/tests/test5/cli and /dev/null differ diff --git a/Additional/tests/test5/client.cpp b/Additional/tests/test5/client.cpp deleted file mode 100644 index 2e30065..0000000 --- a/Additional/tests/test5/client.cpp +++ /dev/null @@ -1,65 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -int main() { - // Create a socket - int clientSocket = socket(AF_INET, SOCK_STREAM, 0); - if (clientSocket == -1) { - perror("Error creating client socket"); - exit(EXIT_FAILURE); - } - - // Set up the server address structure - struct sockaddr_in serverAddr; - serverAddr.sin_family = AF_INET; - serverAddr.sin_port = htons(8080); // Port number - serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); // Server IP address - - // Connect to the server - if (connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) { - perror("Error connecting to server"); - exit(EXIT_FAILURE); - } - - std::cout << "Connected to server." << std::endl; - - // Send and receive messages - char message[1024]; - while (true) { - std::cout << "Enter a message (or 'q' to quit): "; - std::cin.getline(message, sizeof(message)); - - if (strcmp(message, "q") == 0) { - break; // Quit the loop - } - - ssize_t bytesSent = send(clientSocket, message, strlen(message), 0); - if (bytesSent == -1) { - perror("Error sending"); - break; - } - - char buffer[1024]; - memset(buffer, 0, sizeof(buffer)); - ssize_t bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0); - if (bytesRead == -1) { - perror("Error receiving"); - break; - } else if (bytesRead == 0) { - std::cout << "Server disconnected." << std::endl; - break; - } else { - std::cout << "Received: " << buffer << std::endl; - } - } - - // Close the socket - close(clientSocket); - - return 0; -} diff --git a/Additional/tests/test5/server b/Additional/tests/test5/server deleted file mode 100755 index 3c80d3a..0000000 Binary files a/Additional/tests/test5/server and /dev/null differ diff --git a/Additional/tests/test5/server.cpp b/Additional/tests/test5/server.cpp deleted file mode 100644 index f80fd6b..0000000 --- a/Additional/tests/test5/server.cpp +++ /dev/null @@ -1,102 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Function to handle client communication in a separate thread -void* handleClient(void* arg) { - int clientSocket = *((int*)arg); - char buffer[1024]; - ssize_t bytesRead; - - while (true) { - memset(buffer, 0, sizeof(buffer)); - bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0); - if (bytesRead == -1) { - perror("Error receiving"); - break; - } else if (bytesRead == 0) { - std::cout << "Client disconnected." << std::endl; - break; - } else { - std::cout << "Received from client: " << buffer << std::endl; - - // Echo the received message back to the client - ssize_t bytesSent = send(clientSocket, buffer, bytesRead, 0); - if (bytesSent == -1) { - perror("Error sending"); - break; - } - } - } - - // Close the client socket - close(clientSocket); - return NULL; -} - -int main() { - // Create a socket - int serverSocket = socket(AF_INET, SOCK_STREAM, 0); - if (serverSocket == -1) { - perror("Error creating server socket"); - exit(EXIT_FAILURE); - } - - // Set up the server address structure - struct sockaddr_in serverAddr; - serverAddr.sin_family = AF_INET; - serverAddr.sin_port = htons(8080); // Port number - serverAddr.sin_addr.s_addr = INADDR_ANY; // Bind to any available network interface - - // Bind the socket to the address and port - if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) { - perror("Error binding"); - exit(EXIT_FAILURE); - } - - // Listen for incoming connections - if (listen(serverSocket, 5) == -1) { - perror("Error listening"); - exit(EXIT_FAILURE); - } - - std::cout << "Server is listening on port 8080..." << std::endl; - - // Accept and handle incoming connections in separate threads - while (true) { - struct sockaddr_in clientAddr; - socklen_t clientAddrLen = sizeof(clientAddr); - int* clientSocket = new int; - - *clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrLen); - if (*clientSocket == -1) { - perror("Error accepting connection"); - delete clientSocket; - continue; - } - - std::cout << "Client connected from " << inet_ntoa(clientAddr.sin_addr) << ":" << ntohs(clientAddr.sin_port) << std::endl; - - pthread_t clientThread; - if (pthread_create(&clientThread, NULL, handleClient, (void*)clientSocket) != 0) { - perror("Error creating thread"); - delete clientSocket; - continue; - } - - pthread_detach(clientThread); - } - - // Close the server socket (unreachable in this example) - close(serverSocket); - - return 0; -} diff --git a/Additional/tests/test6/cli b/Additional/tests/test6/cli deleted file mode 100755 index 2294ed5..0000000 Binary files a/Additional/tests/test6/cli and /dev/null differ diff --git a/Additional/tests/test6/client.cpp b/Additional/tests/test6/client.cpp deleted file mode 100644 index c1f9293..0000000 --- a/Additional/tests/test6/client.cpp +++ /dev/null @@ -1,87 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Function to handle receiving messages from the server -void* receiveMessages(void* arg) { - int clientSocket = *((int*)arg); - char buffer[1024]; - ssize_t bytesRead; - - while (true) { - memset(buffer, 0, sizeof(buffer)); - bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0); - if (bytesRead == -1) { - perror("Error receiving"); - break; - } else if (bytesRead == 0) { - std::cout << "Server disconnected." << std::endl; - break; - } else { - std::cout << "-> " << buffer << std::endl; - } - } - - // Close the client socket - close(clientSocket); - exit(EXIT_SUCCESS); -} - -int main() { - // Create a socket - int clientSocket = socket(AF_INET, SOCK_STREAM, 0); - if (clientSocket == -1) { - perror("Error creating client socket"); - exit(EXIT_FAILURE); - } - - // Set up the server address structure - struct sockaddr_in serverAddr; - serverAddr.sin_family = AF_INET; - serverAddr.sin_port = htons(8080); // Port number - serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); // Server IP address - - // Connect to the server - if (connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) { - perror("Error connecting to server"); - exit(EXIT_FAILURE); - } - - std::cout << "Connected to server." << std::endl; - - // Start a thread to receive messages from the server - pthread_t receiveThread; - if (pthread_create(&receiveThread, NULL, receiveMessages, (void*)&clientSocket) != 0) { - perror("Error creating receive thread"); - exit(EXIT_FAILURE); - } - - // Send messages to the server - char message[1024]; - std::cout << "Enter a message (or 'q' to quit) " << std::endl; - while (true) { - std::cin.getline(message, sizeof(message)); - - if (strcmp(message, "q") == 0) { - break; // Quit the loop - } - - ssize_t bytesSent = send(clientSocket, message, strlen(message), 0); - if (bytesSent == -1) { - perror("Error sending"); - break; - } - } - - // Close the client socket - close(clientSocket); - - return 0; -} diff --git a/Additional/tests/test6/server b/Additional/tests/test6/server deleted file mode 100755 index eb9279c..0000000 Binary files a/Additional/tests/test6/server and /dev/null differ diff --git a/Additional/tests/test6/server.cpp b/Additional/tests/test6/server.cpp deleted file mode 100644 index d41c190..0000000 --- a/Additional/tests/test6/server.cpp +++ /dev/null @@ -1,116 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -std::vector clientSockets; // Store client sockets - -// Function to broadcast a message to all connected clients -void broadcastMessage(const char* message, int senderSocket) { - for(std::vector::iterator it = clientSockets.begin(); it != clientSockets.end(); ++it) - { - int socket = static_cast((*it)); - if (socket != senderSocket) { - send(socket, message, strlen(message), 0); - } - } -} - -// Function to handle client communication in a separate thread -void* handleClient(void* arg) { - int clientSocket = *((int*)arg); - char buffer[1024]; - ssize_t bytesRead; - - while (true) { - memset(buffer, 0, sizeof(buffer)); - bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0); - if (bytesRead == -1) { - perror("Error receiving"); - break; - } else if (bytesRead == 0) { - std::cout << "Client disconnected." << std::endl; - break; - } else { - std::cout << "Received from client: " << buffer << std::endl; - - // Broadcast the received message to all clients - broadcastMessage(buffer, clientSocket); - } - } - - // Close the client socket and remove it from the list - close(clientSocket); - clientSockets.erase(std::remove(clientSockets.begin(), clientSockets.end(), clientSocket), clientSockets.end()); - - return NULL; -} - -int main() { - // Create a socket - int serverSocket = socket(AF_INET, SOCK_STREAM, 0); - if (serverSocket == -1) { - perror("Error creating server socket"); - exit(EXIT_FAILURE); - } - - // Set up the server address structure - struct sockaddr_in serverAddr; - serverAddr.sin_family = AF_INET; - serverAddr.sin_port = htons(8080); // Port number - serverAddr.sin_addr.s_addr = INADDR_ANY; // Bind to any available network interface - - // Bind the socket to the address and port - if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) { - perror("Error binding"); - exit(EXIT_FAILURE); - } - - // Listen for incoming connections - if (listen(serverSocket, 5) == -1) { - perror("Error listening"); - exit(EXIT_FAILURE); - } - - std::cout << "Server is listening on port 8080..." << std::endl; - - // Accept and handle incoming connections in separate threads - while (true) { - struct sockaddr_in clientAddr; - socklen_t clientAddrLen = sizeof(clientAddr); - int* clientSocket = new int; - - *clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrLen); - if (*clientSocket == -1) { - perror("Error accepting connection"); - delete clientSocket; - continue; - } - - std::cout << "Client connected from " << inet_ntoa(clientAddr.sin_addr) << ":" << ntohs(clientAddr.sin_port) << std::endl; - - // Add the client socket to the list - clientSockets.push_back(*clientSocket); - - pthread_t clientThread; - if (pthread_create(&clientThread, NULL, handleClient, (void*)clientSocket) != 0) { - perror("Error creating thread"); - delete clientSocket; - continue; - } - - pthread_detach(clientThread); - } - - // Close the server socket (unreachable in this example) - close(serverSocket); - - return 0; -} diff --git a/Additional/tests/test7/first_web_serv.cpp b/Additional/tests/test7/first_web_serv.cpp deleted file mode 100644 index 986edd9..0000000 --- a/Additional/tests/test7/first_web_serv.cpp +++ /dev/null @@ -1,61 +0,0 @@ -#include -#include -#include -#include -#include -#include - -int main() { - // Create a socket - int serverSocket = socket(AF_INET, SOCK_STREAM, 0); - if (serverSocket == -1) { - std::cerr << "Error creating socket." << std::endl; - return -1; - } - - // Bind the socket to an address and port - sockaddr_in serverAddr; - serverAddr.sin_family = AF_INET; - serverAddr.sin_port = htons(8081); // Listen on port 8080 - serverAddr.sin_addr.s_addr = INADDR_ANY; - if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) { - std::cerr << "Error binding socket." << std::endl; - close(serverSocket); - return -1; - } - - // Listen for incoming connections - if (listen(serverSocket, 5) == -1) { - std::cerr << "Error listening for connections." << std::endl; - close(serverSocket); - return -1; - } - - std::cout << "Server listening on port 8080..." << std::endl; - - // Accept and handle incoming connections - sockaddr_in clientAddr; - socklen_t clientAddrLen = sizeof(clientAddr); - int clientSocket; - - while (true) { - clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrLen); - if (clientSocket == -1) { - std::cerr << "Error accepting connection." << std::endl; - continue; - } - - std::cout << "New client connected." << std::endl; - - - const char* httpResponse = "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello, world!"; - send(clientSocket, httpResponse, strlen(httpResponse), 0); - - close(clientSocket); - } - - // Close the server socket (never reached in this example) - close(serverSocket); - - return 0; -} diff --git a/Additional/tests/test7/read.txt b/Additional/tests/test7/read.txt deleted file mode 100644 index d84e289..0000000 --- a/Additional/tests/test7/read.txt +++ /dev/null @@ -1 +0,0 @@ -"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello, world!" \ No newline at end of file diff --git a/Additional/tests/test8/server.cpp b/Additional/tests/test8/server.cpp deleted file mode 100644 index 47794a5..0000000 --- a/Additional/tests/test8/server.cpp +++ /dev/null @@ -1,202 +0,0 @@ -// #include -// #include -// #include -// #include -// #include - -// struct ServerConfig { -// int port; -// std::string document_root; -// }; - -// ServerConfig readConfig(const std::string& configFileName) { -// ServerConfig config; -// std::ifstream configFile(configFileName.c_str()); - -// if (!configFile) { -// std::cerr << "Error opening the configuration file." << std::endl; -// exit(1); -// } - -// std::string line; -// while (std::getline(configFile, line)) { -// std::istringstream iss(line); -// std::string key, value; -// if (iss >> key) { -// if (key == "port:") { -// if (iss >> config.port) { -// // Successfully read the port value -// } else { -// std::cerr << "Error reading port value." << std::endl; -// } -// } else if (key == "document_root:") { -// if (iss >> config.document_root) { -// // Successfully read the document_root value -// } else { -// std::cerr << "Error reading document_root value." << std::endl; -// } -// } -// } -// } - -// return config; -// } - -// int main() { -// ServerConfig config = readConfig("test.txt"); - -// std::cout << "Port: " << config.port << std::endl; -// std::cout << "Document Root: " << config.document_root << std::endl; - -// // ... Rest of your server code ... - -// return 0; -// } - - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -struct ServerConfig { - int port; - std::string document_root; -}; - -ServerConfig readConfig(const std::string& configFileName) { - ServerConfig config; - std::ifstream configFile(configFileName.c_str()); - - if (!configFile) { - std::cerr << "Error opening the configuration file." << std::endl; - exit(1); - } - - std::string line; - while (std::getline(configFile, line)) { - std::istringstream iss(line); - std::string key, value; - if (iss >> key) { - if (key == "port:") { - if (iss >> config.port) { - // Successfully read the port value - } else { - std::cerr << "Error reading port value." << std::endl; - } - } else if (key == "document_root:") { - if (iss >> config.document_root) { - // Successfully read the document_root value - } else { - std::cerr << "Error reading document_root value." << std::endl; - } - } - } - } - - return config; -} - -std::string getHttpResponse(const std::string& filePath) { - std::ifstream file(filePath.c_str()); - if (!file) { - return "HTTP/1.1 404 Not Found\r\n\r\nFile not found."; - } - - std::ostringstream response; - response << "HTTP/1.1 200 OK\r\n"; - response << "Content-Length: " << file.tellg() << "\r\n\r\n"; - file.seekg(0, std::ios::beg); - response << file.rdbuf(); - - return response.str(); -} - -int main() { - // Read the configuration file - ServerConfig config = readConfig("test.txt"); - - std::cout << "Port: " << config.port << std::endl; - std::cout << "Document Root: " << config.document_root << std::endl; - - // Create a socket - int serverSocket = socket(AF_INET, SOCK_STREAM, 0); - if (serverSocket == -1) { - std::cerr << "Error creating socket." << std::endl; - return 1; - } - - // Bind the socket to an address and port - sockaddr_in serverAddr; - serverAddr.sin_family = AF_INET; - serverAddr.sin_port = htons(config.port); - serverAddr.sin_addr.s_addr = INADDR_ANY; - if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) { - std::cerr << "Error binding socket." << std::endl; - close(serverSocket); - return 1; - } - - // Listen for incoming connections - if (listen(serverSocket, 5) == -1) { - std::cerr << "Error listening for connections." << std::endl; - close(serverSocket); - return 1; - } - - std::cout << "Server listening on port " << config.port << "..." << std::endl; - - while (true) { - int clientSocket = accept(serverSocket, nullptr, nullptr); - if (clientSocket == -1) { - std::cerr << "Error accepting connection." << std::endl; - continue; - } - - std::cout << "New client connected." << std::endl; - - // Handle HTTP request - char buffer[1024]; - int bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0); - - if (bytesRead > 0) { - // Extract requested URL path from the HTTP request (e.g., from the "GET" line) - // Construct the file path within the document root based on the URL path - std::string httpRequest(buffer, bytesRead); - - // Find the "GET" line in the HTTP request - std::string requestedPath; - size_t getLineStart = httpRequest.find("GET "); - if (getLineStart != std::string::npos) { - // Find the end of the "GET" line - size_t getLineEnd = httpRequest.find("\r\n", getLineStart); - - // Extract the requested path from the "GET" line - if (getLineEnd != std::string::npos) { - // Add 4 to skip "GET " and capture the path until the space - requestedPath = httpRequest.substr(getLineStart + 4, getLineEnd - getLineStart - 4); - } - } - std::string filePath = config.document_root + requestedPath; - - // Get the HTTP response based on the file content - std::string httpResponse = getHttpResponse(filePath); - - // Send the HTTP response to the client - send(clientSocket, httpResponse.c_str(), httpResponse.size(), 0); - } - - // Close the client socket - close(clientSocket); - } - - // Close the server socket (never reached in this example) - close(serverSocket); - - return 0; -} diff --git a/Additional/tests/test8/test.txt b/Additional/tests/test8/test.txt deleted file mode 100644 index da4940b..0000000 --- a/Additional/tests/test8/test.txt +++ /dev/null @@ -1,2 +0,0 @@ -port: 8080 -document_root: test8/webconf.txt \ No newline at end of file diff --git a/Additional/tests/test8/webconf.txt b/Additional/tests/test8/webconf.txt deleted file mode 100755 index 95d09f2..0000000 --- a/Additional/tests/test8/webconf.txt +++ /dev/null @@ -1 +0,0 @@ -hello world \ No newline at end of file diff --git a/Additional/tests/test9/content_config.txt b/Additional/tests/test9/content_config.txt deleted file mode 100644 index eee98c6..0000000 --- a/Additional/tests/test9/content_config.txt +++ /dev/null @@ -1,4 +0,0 @@ -/hello.html = Hello, World! -/about.html = This is the about page. -/contact.html = Contact us at contact@example.com. -/bitch.html = Page Title

This is a Heading

This is a paragraph.

\ No newline at end of file diff --git a/Additional/tests/test9/server.cpp b/Additional/tests/test9/server.cpp deleted file mode 100644 index 2e4dd0e..0000000 --- a/Additional/tests/test9/server.cpp +++ /dev/null @@ -1,127 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -std::map contentMap; - -void readContentConfig(const std::string& configFileName) { - std::ifstream configFile(configFileName.c_str()); - if (!configFile) { - std::cerr << "Error opening the configuration file." << std::endl; - exit(1); - } - - std::string line; - while (std::getline(configFile, line)) { - std::cout << line << std::endl; - size_t separatorPos = line.find("="); - if (separatorPos != std::string::npos) { - std::string path = line.substr(0, separatorPos); - std::string content = line.substr(separatorPos + 1); - contentMap[path] = content; - } - } -} - -std::string getHttpResponse(const std::string& requestedPath) { - std::cout << requestedPath << std::endl; - std::map::iterator it = contentMap.find(requestedPath); - if (it != contentMap.end()) { - std::cout << it->second << std::endl; - return "HTTP/1.1 200 OK\r\n\r\n" + it->second; - } else { - return "HTTP/1.1 404 Not Found\r\n\r\nFile not found."; - } -} - -int main() { - // Read the content configuration file - readContentConfig("content_config.txt"); - - // ... Setup socket, bind, and listen ... - int serverSocket = socket(AF_INET, SOCK_STREAM, 0); - if (serverSocket == -1) { - std::cerr << "Error creating socket." << std::endl; - return -1; - } - - // Bind the socket to an address and port - sockaddr_in serverAddr; - serverAddr.sin_family = AF_INET; - serverAddr.sin_port = htons(8080); // Listen on port 8080 - serverAddr.sin_addr.s_addr = INADDR_ANY; - if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) { - std::cerr << "Error binding socket." << std::endl; - close(serverSocket); - return -1; - } - - // Listen for incoming connections - if (listen(serverSocket, 5) == -1) { - std::cerr << "Error listening for connections." << std::endl; - close(serverSocket); - return -1; - } - - std::cout << "Server listening on port 8080..." << std::endl; - - // Accept and handle incoming connections - sockaddr_in clientAddr; - socklen_t clientAddrLen = sizeof(clientAddr); - int clientSocket; - - while (true) { - int clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrLen); - if (clientSocket == -1) { - std::cerr << "Error accepting connection." << std::endl; - continue; - } - - // Handle HTTP request - char buffer[1024]; - int bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0); - std::cout << buffer << std::endl; - - if (bytesRead > 0) { - // Extract requested URL path from the HTTP request (e.g., from the "GET" line) - std::string requestedPath; - std::string httpRequest(buffer, bytesRead); - - // Find the "GET" line in the HTTP request - size_t getLineStart = httpRequest.find("GET "); - if (getLineStart != std::string::npos) { - // Find the end of the "GET" line - size_t getLineEnd = httpRequest.find("\r\n", getLineStart); - - // Extract the requested path from the "GET" line - if (getLineEnd != std::string::npos) { - // Add 4 to skip "GET " and capture the path until the space - requestedPath = httpRequest.substr(getLineStart + 4, getLineEnd - getLineStart - 12); - } - } - - // Get the HTTP response based on the requested path - - std::string httpResponse = getHttpResponse(requestedPath); - std::cout << httpResponse << std::endl; - - // Send the HTTP response to the client - send(clientSocket, httpResponse.c_str(), httpResponse.size(), 0); - } - - // Close the client socket - close(clientSocket); - } - - // ... Rest of the server code ... - close(serverSocket); - - return 0; -} diff --git a/Additional/tests/test9/webconf.txt b/Additional/tests/test9/webconf.txt deleted file mode 100755 index 95d09f2..0000000 --- a/Additional/tests/test9/webconf.txt +++ /dev/null @@ -1 +0,0 @@ -hello world \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index c0d8f8c..0000000 --- a/README.md +++ /dev/null @@ -1,188 +0,0 @@ -# Internet Relay Chat (FT_IRC) - -This project is about creating your own IRC server. -You will use an actual IRC client to connect to your server and test it. -Internet is ruled by solid standards protocols that allow connected computers to interact -with each other. -It’s always a good thing to know. -Version: 6 - -[![-----------------------------------------------------]( -https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/aqua.png)](https://github.com/alpardayalman?tab=repositories) - -## To-do List - -- [x] Socket and Multiplexing -- [x] Makefile / flags and relink -- [x] RFC 1459 (protocols) -- [x] Authentication. -- [x] Nickname, a username. -- [x] Join a channel. -- [x] Send and receive private messages using your reference client. -- [x] All the messages sent from one client to a channel have to be forwarded to every other client that joined the channel. -- [x] Operators and regular users. -- [x] flood -- [x] Notice, ping, pong -- [x] Kick, Topic, Part -- [x] File transfer lessgo -- [x] Bot -- [x] proper usage of clients gui -- [x] Leaks. & seg correction -- [ ] Signal. ^D & ^Z -- [ ] Preliminary last checks (checkout 13'th day) -- [ ] Evo for all 2 of the teams. -- [ ] Everyone's last word for this project. - -[![-----------------------------------------------------]( -https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/aqua.png)](https://github.com/alpardayalman?tab=repositories) - -## Developers - - - - - - - - - -
Emircan Kaymaz
Emircan Kaymaz

Talha Acikgoz
Talha Acikgoz

Yunus Emre Aktas
Yunus Emre Aktas

Sarp Erkiralp
Sarp Erkiralp

-
Alp A. Yalman
Alp A. Yalman

- - - The groups were divided whilst examination. - -[![-----------------------------------------------------]( -https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/aqua.png)](https://github.com/alpardayalman?tab=repositories) - - - - -31 -## NOTES -### Main Objective: finishing this project before our 2nd week. - - ### 1/11/2023 Start of the project. - - Multiplexing handled using select. Uncharted territory in our school, - we are the only group that uses SELECT() for ft_IRC project. - Transmiting of messages works. - We are using Hexchat for reference. - We need to chose which commands we need to implement for our project. For now we have beta PASS PRIVMSG INFO. - 5/5 day as a team. ------------------------------------------ - - ### 2/11/2023 Second day. - - Password check is near perfect. We are stress testing it. - Colors added. - Establishing modularity using a map for all commands. - Our brain melted ... - 2/5 day because rain. frustrated kinda day. ------------------------------------------ - ### 3/11/2023 Third day. - Ascii art added (Emre). - Modularity added (Emircan). - Kick started chanels (˚5) (Talha). - /PASS changed to PASS in nc. - We need to understand how to use signal ^D to send a message immediatly from nc. - Well played boys. ------------------------------------------ - ### 4/11/2023 Fourth day. - Made slight changes to the github repo. - Nick and User added (Need to do slight changes to User to get the information in the right way). - Channel class was updated, 1 user cannot join the same channel 2 times. - Major step in hexchat we were able to create a channel. Number 5 indeed. - ^D signal works. - great day. - Congrats indeed. Wp team. ------------------------------------------ - - ### 5/11/2023 Fifth day. - - Vacational and busy day for all of us. We worked really good so far. ------------------------------------------ - - ### 6/11/2023 Sixth day. - - What a good day, the purpose of this day was to create a channel that we could chat on. - We were able to do more than that. - We recreated the function TOPIC and INVITE today. - We eased on Authentication it works really good. - Divided the socket and the server files because Server::Run() was getting overwhelming. - We added a CAP file to understand which client was being used HEX or nc. - Funny enough whilst connecting hexchat sended CAP LS, PASS, NICK and USER piece by piece always in this order. - Every now and then it sends CAP LS than PASS ... algather. or CAP LS and PASS than the rest ex. - For that reason we recreated a buffer system which gets them line by line. - In general this was probably the day that we worked the best. ------------------------------------------ - - ### 7/11/2023 Seventh day. - - We did Topic, Notice, Part. - We elaborated on Nick and now Topic can be changed for everybody. - We did ^D signal. - We now see the nickname in the left side of the chanel we can send private messages. - !!!! We can transfer filess babay. - We can exit the chanel and now it doesn't say that we are in the chanel we fr get kicked now. - This must be the most productive day yet. - ------------------------------------------ - ### 8/11/2023 Eight'st day. - - Overall good day, - we were able to improve the gui, we did quit and semi whois. - We can see people and change nicknames. - We got some errors during the day. - We did ping and pong. - We need to do more unit testing however we only need to do the bot, - the mode command for the channel, - better the gui and add an operator than we are done with this project. - whois added. - I am proud of my team. - ------------------------------------------ - ### 9/11/2023 Ninth day. - Vacation day for fam', I was sick today. Almost every team members got sick this week. - I did some backup coding for gui part and some systemic improvements however I - could not test them in hexChat (I had troubles instaling hex to my mac). Instead I used limeChat - Listing and some other stuff works however The apperance of names are kinda bad on the right side. - We must Start on the operator priviledges and chanel mods than we are 99% done with the mandetory part. - Once finished we need to program a bot than easy peasy. IRC project is done. - ------------------------------------------ - - ### 10/11/2023 Tenth day. - Sinavda bol sans beyler. - First step to operators. - Fixed notice. - The exam was bad for the team we had some troubles concentrating. - Next day fam'. - ------------------------------------------ - - ### 11/11/2023 Eleventh day. - We updated the makefile which - We learned more about iterators. (creazy stuff). - We fixed a major bug in join. - Topic was added to the list. - Nick display all users. - Exeption class added. - ------------------------------------------ - ### 12/11/2023 Twelth day. - Fix in gui, server topic and nick. Had some problems with ping. We reached 200 commits. - As we are coming to an end of the project, I had some time to add the bot. For the bot I have recreated a new - command called names which sends to the bot. Than the bot sends the message to all the users. - We fixed Mode. - We completed MODE error replies. - ------------------------------------------ - ### 13/11/2023 Thirteenth day. - Ping, Notice, Quit and user fixed. Whist I am writing this We are almost done. - It's 2 am in the morning and the team is exhausted however overjoyed with what we have done. - Before doing some preliminary checks of our project, I would like to thank every one of you. - Let's keep up the paste for the last project people. - -Ps: Evo page test, stress test and flags (shadow and -cpp=98). Welcome message delete. Privmsg and one more stress test ------------------------------------------ diff --git a/__IRC__/include/Chanel.hpp b/__IRC__/include/Chanel.hpp index f3bf305..fb50454 100644 --- a/__IRC__/include/Chanel.hpp +++ b/__IRC__/include/Chanel.hpp @@ -1,8 +1,6 @@ #pragma once #include "Server.hpp" -//privmsg : -//chanelin msgboxina msg atabiliriz #include "Client.hpp" #define L_CODE 1 @@ -20,7 +18,7 @@ class Chanel { std::string topic; std::string key; - int keycode; // hangi key var. + int keycode; int users; diff --git a/__IRC__/include/Server.hpp b/__IRC__/include/Server.hpp index 710db25..47ac219 100644 --- a/__IRC__/include/Server.hpp +++ b/__IRC__/include/Server.hpp @@ -33,7 +33,7 @@ class Server { bool is_running; int reuse; const std::string server_name; - std::vector clients; // client vectoru. + std::vector clients; fd_set readFds; fd_set writeFds; fd_set readFdsSup; diff --git a/__IRC__/include/Utilities.hpp b/__IRC__/include/Utilities.hpp index 94fa39b..69a0786 100644 --- a/__IRC__/include/Utilities.hpp +++ b/__IRC__/include/Utilities.hpp @@ -49,7 +49,7 @@ # define RPL_LISTEND(nick) ": 323 " + nick + " :End of /LIST\r\n" -#define RPL_WELCOME(source, msg) source + msg + "\r\n"//eger duzgun calisirsa joini patlatiyor +#define RPL_WELCOME(source, msg) source + msg + "\r\n" /* [ERROR MESSAGES] */ #define ERR_CHANNELISFULL(source, channel) ": 471 " + source + " " + channel + " :Cannot join channel (+l)" + "\r\n" //JOIN @@ -61,12 +61,7 @@ #define ERR_NICKNAMEINUSE(source) ": 433 " + source + " " + source + " :Nickname is already in use" + "\r\n" //NICK #define ERR_NICKNAMEEMPTY(source) ": 433 " + source + " " + source + " :Nickname cannot empty" + "\r\n" //NICK #define RPL_NOTOPIC(nick, channel) ": 331 " + nick + " " + channel + " :No topic is set" + "\r\n" //TOPIC -// ============= Define ============ -// ctrlz fg -// notice info -// PING // ==========debug=========== -// #define tokenNewlinedeb class Utilities { private: diff --git a/__IRC__/source/Server.cpp b/__IRC__/source/Server.cpp index b2ef54c..8fbf8bb 100644 --- a/__IRC__/source/Server.cpp +++ b/__IRC__/source/Server.cpp @@ -124,11 +124,12 @@ void Server::run(void) { (*begin).buffer.clear(); std::cout << BLUE << s << RESET << std::endl; std::vector parameters = Utilities::tokenNewline(s); - + if (!this->chanels.empty()) + std::cout << YELLOW << "op.nick:" << this->chanels[0].op->nick << RESET << std::endl; for (int i = 0; i < (int)parameters.size(); i++) { Server::commandHandler(parameters[i], (*begin)); } - std::cout << PURPLE << "---------------------" << parameters.size() << RESET << std::endl; + std::cout << PURPLE << "---------------------" << (*begin).cliFd << RESET << std::endl; if (!(Utilities::tokenCmd(parameters[0], 0)[0] == "CAP" && parameters.size() == 1)) { if (!(*begin).passcheku) { FD_CLR((*begin).cliFd, &this->readFds); diff --git a/__IRC__/source/commands/JOIN.cpp b/__IRC__/source/commands/JOIN.cpp index b78bc3d..94bf025 100644 --- a/__IRC__/source/commands/JOIN.cpp +++ b/__IRC__/source/commands/JOIN.cpp @@ -69,6 +69,7 @@ int Server::Join(std::string &s, Client& cli) { } else { (*it).clients.push_back(cli); + (*it).op = &(*it).clients[0]; Utilities::writeRpl(cli.cliFd, RPL_JOIN(cli.nick, cli.ipAddr, chaName)); if (!(*it).topic.empty()) Utilities::writeRpl(cli.cliFd, RPL_TOPIC(cli.nick, cli.ipAddr, chaName, (*it).topic)); @@ -80,6 +81,7 @@ int Server::Join(std::string &s, Client& cli) { } else { (*it).clients.push_back(cli); + (*it).op = &(*it).clients[0]; Utilities::writeRpl(cli.cliFd, RPL_JOIN(cli.nick, cli.ipAddr, chaName)); if (!(*it).topic.empty()) Utilities::writeRpl(cli.cliFd, RPL_TOPIC(cli.nick, cli.ipAddr, chaName, (*it).topic)); @@ -91,6 +93,7 @@ int Server::Join(std::string &s, Client& cli) { } else { (*it).clients.push_back(cli); + (*it).op = &(*it).clients[0]; Utilities::writeRpl(cli.cliFd, RPL_JOIN(cli.nick, cli.ipAddr, chaName)); if (!(*it).topic.empty()) Utilities::writeRpl(cli.cliFd, RPL_TOPIC(cli.nick, cli.ipAddr, chaName, (*it).topic)); @@ -98,6 +101,7 @@ int Server::Join(std::string &s, Client& cli) { } else { (*it).clients.push_back(cli); + (*it).op = &(*it).clients[0]; Utilities::writeRpl(cli.cliFd, RPL_JOIN(cli.nick, cli.ipAddr, chaName)); if (!(*it).topic.empty()) Utilities::writeRpl(cli.cliFd, RPL_TOPIC(cli.nick, cli.ipAddr, chaName, (*it).topic)); @@ -114,8 +118,9 @@ int Server::Join(std::string &s, Client& cli) { } else {//if chanel does not exist, create one and add the client to the chanel vector. Chanel newChanel(chaName); - newChanel.op = &cli; + // newChanel.op = &cli; newChanel.clients.push_back(cli); + newChanel.op = &newChanel.clients[0]; this->chanels.push_back(newChanel); // Chanels cached in server. Utilities::writeRpl(cli.cliFd, RPL_JOIN(cli.nick, cli.ipAddr, chaName)); } diff --git a/__IRC__/source/commands/KICK.cpp b/__IRC__/source/commands/KICK.cpp index 3e7ce9b..94b7a7c 100644 --- a/__IRC__/source/commands/KICK.cpp +++ b/__IRC__/source/commands/KICK.cpp @@ -11,7 +11,7 @@ int Server::Kick(std::string &s, Client &cli) { if (cha.name.empty()){ return 0; } - + // std::cout << s << std::endl; if(cha.op->nick == cmd[1] || cha.op->nick != cli.nick) { if(cha.op->nick != cli.nick) { Utilities::writeRpl(cli.cliFd, ERR_CHANOPRIVSNEEDED(cli.getPrefix(), kick)); diff --git a/__IRC__/source/commands/LIST.cpp b/__IRC__/source/commands/LIST.cpp index d86583b..e54d8a9 100644 --- a/__IRC__/source/commands/LIST.cpp +++ b/__IRC__/source/commands/LIST.cpp @@ -7,7 +7,7 @@ int Server::List(std::string &s, Client& cli) { if (!it->topic.length()) Utilities::writeRpl(cli.cliFd, RPL_LIST(cli.nick, it->name, Utilities::intToString(it->clients.size()), " Empty")); else - Utilities::writeRpl(cli.cliFd, RPL_LIST(cli.nick, it->name, Utilities::intToString(it->clients.size()), it->topic)); + Utilities::writeRpl(cli.cliFd, RPL_LIST(cli.nick, it->name, Utilities::intToString(it->clients.size()), " "+it->topic)); } Utilities::writeRpl(cli.cliFd, RPL_LISTEND(cli.nick)); return 1; diff --git a/__IRC__/source/commands/OP.cpp b/__IRC__/source/commands/OP.cpp index 0b0b4ee..0024f10 100644 --- a/__IRC__/source/commands/OP.cpp +++ b/__IRC__/source/commands/OP.cpp @@ -19,6 +19,7 @@ int getClientPos(Chanel &cha, Client &cli) { int Server::Op(std::string &s, Client &cli) { std::vector cmd = Utilities::splitString(s); Chanel cha = getChanel(cmd[0]); + std::cout << PURPLE << "cmd[0]: " << cmd[0] << " cmd[1]: " << cmd[1] << " cmd[2]: " << cmd[2] << RESET << std::endl; if (cli.nick == cha.op->nick) {//if he is op Utilities::trim(cmd[2]); ClientIterator it_ = this->clients.begin(); @@ -30,16 +31,24 @@ int Server::Op(std::string &s, Client &cli) { return 1; Client newOp = cha.getClient(cmd[2]); Client oldOp = cha.getClient(cli.nick); + if (oldOp.nick.empty() || newOp.nick.empty()) { + std::cout << RED << "oldOp or newOp is empty" << RESET << std::endl; + return 1; + } - std::cout << YELLOW << "cmd:" << cmd[2] << " s:" << s << RESET << std::endl; if (isClientIn(oldOp, cmd[0]) && isClientIn(newOp, cmd[0])) {//if oldop and newop same channel + int posOldOp = getClientPos(cha, oldOp); + int posNewOp = getClientPos(cha, newOp); + std::cout << PURPLE << "posOldOp: " << posOldOp << " " << " posNewOp: " << posNewOp << RESET << std::endl; for (ChanelIterator it = chanels.begin(); it != chanels.end(); it++) { - if (cmd[0] == it->name && getClientPos(*it, oldOp) != -1 && getClientPos(*it, newOp) != -1) { + if (cmd[0] == it->name && posOldOp != -1 && posNewOp != -1) { //swap oldop and newop if they are in same chanel - Client tmp = it->clients[getClientPos(*it, oldOp)]; - it->clients[getClientPos(*it, oldOp)] = it->clients[getClientPos(*it, newOp)]; - it->clients[getClientPos(*it, newOp)] = tmp; - it->op = &it->clients[getClientPos(*it, newOp)]; + Client tmp = it->clients[0]; + it->clients[0] = it->clients[posNewOp]; + it->clients[posNewOp] = tmp; + // it->clients[getClientPos(*it, oldOp)] = it->clients[getClientPos(*it, newOp)]; + // it->clients[getClientPos(*it, newOp)] = tmp; + it->op = &it->clients[0]; } } } diff --git a/__IRC__/source/commands/PRIVMSG.cpp b/__IRC__/source/commands/PRIVMSG.cpp index 288d7e5..1a3e7c5 100644 --- a/__IRC__/source/commands/PRIVMSG.cpp +++ b/__IRC__/source/commands/PRIVMSG.cpp @@ -10,7 +10,7 @@ int Server::PrivMsg(std::string &s, Client& cli) { { if (it->cliFd != cli.cliFd && isClientIn((*it), params[0]))//if you are not yourself and client(it) is in this chanel { - if (!isClientIn(cli, params[0])) // sen chanelde misin. + if (!isClientIn(cli, params[0])) //are you in chanel. return 1; (*it).messageBox.push_back(RPL_PRIVMSG(cli.getPrefix(), params[0], (params[1][0]==':'?params[1].substr(1, params[1].length()) : params[1]))); FD_SET((*it).cliFd, &this->writeFds); diff --git a/__IRC__/source/commands/QUIT.cpp b/__IRC__/source/commands/QUIT.cpp index 29094f3..6b6c966 100644 --- a/__IRC__/source/commands/QUIT.cpp +++ b/__IRC__/source/commands/QUIT.cpp @@ -2,7 +2,6 @@ int Server::Quit(std::string &s, Client &cli) { for (ChanelIterator it = this->chanels.begin(); it != this->chanels.end(); ++it) { - std::cout << PURPLE << it->name << RESET << std::endl; Server::Part(it->name, cli); if (it == this->chanels.end()) break; @@ -10,15 +9,16 @@ int Server::Quit(std::string &s, Client &cli) { for (ClientIterator it = this->clients.begin(); it != this->clients.end(); ++it) { if (it->nick == cli.nick) { std::cout << YELLOW << "Client " << cli.nick << " has left the server." << RESET << std::endl; + close(cli.cliFd); + if (FD_ISSET(cli.cliFd, &this->writeFds)) + FD_CLR(cli.cliFd, &this->writeFds); + if (FD_ISSET(cli.cliFd, &this->readFds)) + FD_CLR(cli.cliFd, &this->readFds); + Utilities::writeRpl(cli.cliFd, RPL_QUIT(cli.getPrefix(), s.c_str())); + std::cout << YELLOW << cli.cliFd << RESET << std::endl; this->clients.erase(it); break; } } - if (FD_ISSET(cli.cliFd, &this->writeFds)) - FD_CLR(cli.cliFd, &this->writeFds); - if (FD_ISSET(cli.cliFd, &this->readFds)) - FD_CLR(cli.cliFd, &this->readFds); - Utilities::writeRpl(cli.cliFd, RPL_QUIT(cli.getPrefix(), s.c_str())); - close(cli.cliFd); return 1; }