diff --git a/StatusCodes/ErrorTemplate.html b/Templates/ErrorTemplate.html similarity index 100% rename from StatusCodes/ErrorTemplate.html rename to Templates/ErrorTemplate.html diff --git a/Master/dir_list.html b/Templates/dir_list.html similarity index 100% rename from Master/dir_list.html rename to Templates/dir_list.html diff --git a/conf/eval.conf b/conf/eval.conf index b8b42b4..6f4b9ab 100644 --- a/conf/eval.conf +++ b/conf/eval.conf @@ -1,42 +1,26 @@ -/* format type of the configutation file # This is a comment part /* -server:{ - port:8001; # listening port, mandatory parameter. Can be multiple ex: 8000:8100, 8060, 8020 - host:127.0.0.1; # host or 127.0.0.1 by default - server_name:test; # specify server_name, need to be added into /etc/hosts to work - error_page:/error/; # default error page - client_max_body_size:1024; # max request body size in bytes - root:docs/fusion_web/; # root folder of site directory, full or relative path, mandatory parameter - index:index.html; # default page when requesting a directory, index.html by default -} -*/ server:{ - port:8080; # listening port, mandatory parameter - host:0.0.0.0; # host or 127.0.0.1 by default - server_name:example.com; # specify server_name, need to be added into /etc/hosts to work - error_page:./www/errors; # default error page - client_max_body_size:120MB; # max request body size in bytes - root:./www/web1; # root folder of site directory, full or relative path, mandatory parameter - index:index.html; # default page when requesting a directory, index.html by default + port:8080, 8081; + host:127.0.0.1; + server_name:example.com; + error_page:./www/errors; + client_max_body_size:120MB; + root:./www/web1; + index:index.html; autoindex: on; -# location:{ -# name:/; -# root:./www/web1; # root folder of site directory, full or relative path, mandatory parameter -# index:index.html; # default page when requesting a directory, index.html by default -# } location:{ name:/redirect; - return:https://www.42barcelona.com/; # redirection + return:https://www.42barcelona.com/; } location:{ name:/redirect2; - return:/uploads; # redirection + return:/uploads; } location:{ - name:/post; - allow_methods: GET; #allowed methods in location, GET only by default - index:index5.html; # default page when requesting a directory, copies root index by default - alias: ./www/web3; # replaces location part of URI. + name:/post/; + allow_methods: GET; + index:index6.html; + alias: ./www/web3; } location:{ name:/uploads; @@ -46,12 +30,13 @@ server:{ } location:{ name:/cgi-bin; + cgi_enabled: true; alias:./www/web6; allow_methods: GET, POST, DELETE; autoindex:on; - cgi_path:/usr/bin/python3, /bin/sh; - cgi_extension:.py, .sh; + cgi_extension:cgi, py, sh; } + location:{ name:/cgi-no-bin; alias:./www/web6; @@ -64,4 +49,44 @@ server:{ allow_methods: GET; autoindex:on; } + location:{ + name:/set-cookie/; + alias:./www/web7; + index:set-cookie3.html; + allow_methods: GET, POST; + autoindex:on; + } + location:{ + name:/get-cookie/; + set-cookie:id, name, lastname, theme; + set-id: true; + alias:./www/web7; + index:welcome.html; + allow_methods: GET, POST; + } + location:{ + name:/cookie/; + alias:./www/web7; + allow_methods: GET, POST; + autoindex:on; + } + location:{ + name: /cgi-crash/; + alias:./www/web4; + index:index.html; + allow_methods: GET, POST; + cgi_enabled: true; + cgi_extension: cgi; + } }; + +server:{ + port:8082:8090; + host:0.0.0.0; + server_name:example.com; + error_page:./www/errors; + client_max_body_size:120MB; + root:./www/web1; + index:index.html; + autoindex: on; +}; \ No newline at end of file diff --git a/conf/simple.conf b/conf/simple.conf index b412eff..2e7d479 100644 --- a/conf/simple.conf +++ b/conf/simple.conf @@ -67,7 +67,7 @@ server:{ alias:./www/web4; allow_methods: GET, POST, DELETE; autoindex:on; - cgi_path:/bin/sh; + cgi_enabled: true; cgi_extension:cgi; } }; diff --git a/mandatory/inc/Attributes.hpp b/mandatory/inc/Attributes.hpp index 1ffc60b..8178ba0 100644 --- a/mandatory/inc/Attributes.hpp +++ b/mandatory/inc/Attributes.hpp @@ -6,7 +6,7 @@ /* By: eavedill +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/06/07 18:22:35 by eavedill #+# #+# */ -/* Updated: 2024/06/15 14:34:07 by eavedill ### ########.fr */ +/* Updated: 2024/06/30 14:29:47 by eavedill ### ########.fr */ /* */ /* ************************************************************************** */ @@ -31,10 +31,10 @@ class Attributes Attributes(); Attributes(const std::string& filename); ~Attributes(); - void setAttributesFromFile(const std::string& filename); - + + void setAttributesFromFile(const std::string& filename); std::string getName() ; - bool getIsDir() ; + bool getIsDir() ; std::string getSize() ; std::string getDevice() ; std::string getCreated() ; diff --git a/mandatory/inc/CGI.hpp b/mandatory/inc/CGI.hpp index 7ea9076..775c28d 100644 --- a/mandatory/inc/CGI.hpp +++ b/mandatory/inc/CGI.hpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* CGI.hpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:47:27 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:00:16 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #pragma once #include #include @@ -12,43 +24,38 @@ #include "StatusCodesDefinition.hpp" #include #include "ExtendedString.hpp" +#include "Environment.hpp" -class CGI +class CGI : public Environment { private: - std::string CGIFolder; - std::string fileName; - std::string fileArgs; - bool isCGI; - std::vector args; - std::map CGIExtensions; + std::string CGIFolder; + std::string fileName; + std::string fileArgs; + bool isCGI; + std::vector args; + std::map CGIExtensions; public: CGI(); CGI(const std::string &, const std::string &); CGI(const CGI &); ~CGI(); - //------ Setters and Getters ------// - //setters - void setCGIFolder(const std::string &); - void setFileName(const std::string&, const std::string&); - void setIsCGI(bool); - bool setIdentifyCGIFromFileName(const std::string &str); - bool getIsCGI(); - //bool setIsCGI(const std::string &str); - void setArgs(const std::string &); - void setCGIMapExtensions(std::string const &cgi_extension); - //getters - std::string getFileName(); - std::string getCGIFolder(); - std::vector getArgs(); - std::string getCGIExtension(const std::string &); - std::string getFileExtension(); + void setCGIFolder(const std::string &); + void setFileName(const std::string&, const std::string&); + void setIsCGI(bool); + bool setIdentifyCGIFromFileName(const std::string &str); + bool getIsCGI(); + void setArgs(const std::string &); + void setCGIMapExtensions(std::string const &cgi_extension); + std::string getFileName(); + std::string getCGIFolder(); + std::vector getArgs(); + std::string getCGIExtension(const std::string &); + std::string getFileExtension(); + std::string execute(); + CGI *clone(); + static int ChildPID; + static void alarm_handler(int); std::map::iterator findCGIExtension(const std::string &); - //------ OTHER Methods ------// - std::string execute(); - CGI *clone(); - - static int ChildPID; - static void alarm_handler(int); }; diff --git a/mandatory/inc/Environment.hpp b/mandatory/inc/Environment.hpp new file mode 100644 index 0000000..59d32ab --- /dev/null +++ b/mandatory/inc/Environment.hpp @@ -0,0 +1,56 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* Environment.hpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:47:48 by eavedill #+# #+# */ +/* Updated: 2024/06/30 14:57:33 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#pragma once +#include +#include +#include +#include +#include "ExtendedString.hpp" + +#define SCRIPT_FILENAME_KEY "SCRIPT_FILENAME" +#define QUERY_STRING_KEY "QUERY_STRING" +#define REQUEST_METHOD_KEY "REQUEST_METHOD" +#define CONTENT_TYPE_KEY "CONTENT_TYPE" +#define CONTENT_LENGTH_KEY "CONTENT_LENGTH" +#define GATEWAY_INTERFACE_KEY "GATEWAY_INTERFACE" +#define SERVER_SOFTWARE_KEY "SERVER_SOFTWARE" +#define REMOTE_ADDR_KEY "REMOTE_ADDR" +#define REMOTE_PORT_KEY "REMOTE_PORT" +#define SERVER_ADDR_KEY "SERVER_ADDR" +#define SERVER_PORT_KEY "SERVER_PORT" +#define CONTENT_LENGTH_KEY "CONTENT_LENGTH" +#define CONTENT_TYPE_KEY "CONTENT_TYPE" +#define SERVER_NAME_KEY "SERVER_NAME" +#define HTTP_HOST_KEY "HTTP_HOST" +#define HTTP_USER_AGENT_KEY "HTTP_USER_AGENT" +#define HTTP_ACCEPT_KEY "HTTP_ACCEPT" +#define HTTP_ACCEPT_LANGUAGE_KEY "HTTP_ACCEPT_LANGUAGE" +#define HTTP_ACCEPT_ENCODING_KEY "HTTP_ACCEPT_ENCODING" +#define HTTP_COOKIE_KEY "HTTP_COOKIE" +#define HTTP_CONNECTION_KEY "HTTP_CONNECTION" +#define HTTP_UPGRADE_INSECURE_REQUESTS_KEY "HTTP_UPGRADE_INSECURE_REQUESTS" +#define PATH_INFO_KEY "PATH_INFO" + + +class Environment +{ + private: + std::map _env; + std::vector _envArray; + public: + Environment(); + ~Environment(); + void setEnv(const std::string $key, const std::string $value); + std::vector getEnv(); + std::string getEnv(std::string key); +}; diff --git a/mandatory/inc/ExtendedString.hpp b/mandatory/inc/ExtendedString.hpp index 008910e..1431fde 100644 --- a/mandatory/inc/ExtendedString.hpp +++ b/mandatory/inc/ExtendedString.hpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ExtendedString.hpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:47:57 by eavedill #+# #+# */ +/* Updated: 2024/06/30 14:56:55 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #pragma once #include #include @@ -5,27 +17,23 @@ #include #include "utils.hpp" -class ExtendedString : public std::string { -public: - //using std::string::string; // Inherit constructors from std::string - ExtendedString(); - ExtendedString(const std::string &str); - ~ExtendedString(); - ExtendedString &operator=(const std::string &str); - - bool isNumber() const; - bool firstCharIsSign() const; - void replaceString(const std::string& , const std::string& ); - bool validIPAddress(); - size_t stringToSizeT(); - std::vector splitString(char ); - //***To be used in case do not want to modify the original string - //ExtendedString removeCharFromString(char); - void removeCharFromString(char); - //***To be used in case do not want to modify the original string - // ExtendedString removeBlanksAndTabs() ; - void removeBlanksAndTabs() ; - int count_chars(char c); - void replaceFirstString(const std::string& searchString, const std::string& replaceString); +class ExtendedString : public std::string +{ + public: + ExtendedString(); + ExtendedString(const std::string &str); + ~ExtendedString(); + ExtendedString &operator=(const std::string &str); + + bool isNumber() const; + bool firstCharIsSign() const; + void replaceString(const std::string& , const std::string& ); + bool validIPAddress(); + size_t stringToSizeT(); + std::vector splitString(char ); + void removeCharFromString(char); + void removeBlanksAndTabs() ; + int count_chars(char c); + void replaceFirstString(const std::string& searchString, const std::string& replaceString); }; \ No newline at end of file diff --git a/mandatory/inc/FileContent.hpp b/mandatory/inc/FileContent.hpp index ab1cda7..a240c36 100644 --- a/mandatory/inc/FileContent.hpp +++ b/mandatory/inc/FileContent.hpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* FileContent.hpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:48:24 by eavedill #+# #+# */ +/* Updated: 2024/06/30 14:55:08 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #pragma once #include #include @@ -20,64 +32,60 @@ //#define MAX_SENT_BYTES 8192 class FileContent : public StatusCode { + protected: + CGI *cgiModule; private: - std::string fileName; - std::string indexName; - std::vector args; - ExtendedString content; - std::ifstream file; - bool isFistFragment; - bool isFileOpen; - bool sendComplete; - bool isAutoIndex; - std::string homeFolder; - struct stat fileStat; - long long startRange; - long long currentSendingPosition; - long long lastSendingPosition; - CGI *cgiModule; - ListDir *listDir; - //Server *server; - size_t completeContentSize; - std::string splitFileFromArgs(const std::string &); - bool FileOrFolerExtists(const std::string &); - size_t endRange; - // bool isCgi; + std::string fileName; + std::string indexName; + std::vector args; + ExtendedString content; + std::ifstream file; + bool isFistFragment; + bool isFileOpen; + bool sendComplete; + bool isAutoIndex; + std::string homeFolder; + struct stat fileStat; + long long startRange; + long long currentSendingPosition; + long long lastSendingPosition; + ListDir *listDir; + size_t completeContentSize; + size_t endRange; + + std::string splitFileFromArgs(const std::string &); + bool FileOrFolerExtists(const std::string &); public: - // FileContent(Server *); FileContent(); - // FileContent(const std::string &, Server *); ~FileContent(); - int openFile(); - bool setFileName(const std::string &, const std::string &); - void setIsCGI(bool isCgi); - void setStartRange(long long); - void setEndRange(long long); - long long getStartRange(); - std::string getFileName(); - std::string getContent(); - void setIsFileOpen(bool); - void setIsSendComplete(bool); - bool getIsSendComplete(); - void setIsCgi(bool ); - bool getIsCgi(); - - bool getIsFileOpen(); - void setFirstFragment(bool); - bool getFirstFragment(); - std::string getLastModified(); - size_t getCompleteContentSize(); - void setCompleteContentSize(size_t); - bool isInputDirectory(); - void setRange(size_t ); - void setIsAutoIndex(bool); - bool getIsAutoIndex(); - void setIndexName(const std::string &); - std::string getIndexName(); - void setHomeFolder(const std::string &); - std::string getHomeFolder(); - void setCGIModule(CGI *); - long long getFileSize(); - long long getCurrentSendingPosition(); - long long getLastSendingPosition(); + int openFile(); + bool setFileName(const std::string &, const std::string &); + void setIsCGI(bool isCgi); + void setStartRange(long long); + void setEndRange(long long); + long long getStartRange(); + std::string getFileName(); + std::string getContent(); + void setIsFileOpen(bool); + void setIsSendComplete(bool); + bool getIsSendComplete(); + void setIsCgi(bool ); + bool getIsFileOpen(); + void setFirstFragment(bool); + bool getFirstFragment(); + std::string getLastModified(); + size_t getCompleteContentSize(); + void setCompleteContentSize(size_t); + bool isInputDirectory(); + void setRange(size_t ); + void setIsAutoIndex(bool); + bool getIsAutoIndex(); + void setIndexName(const std::string &); + std::string getIndexName(); + void setHomeFolder(const std::string &); + std::string getHomeFolder(); + void setCGIModule(CGI *); + long long getFileSize(); + long long getCurrentSendingPosition(); + long long getLastSendingPosition(); }; diff --git a/mandatory/inc/Header.hpp b/mandatory/inc/Header.hpp index d7d8b77..383c50a 100644 --- a/mandatory/inc/Header.hpp +++ b/mandatory/inc/Header.hpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* Header.hpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:48:01 by eavedill #+# #+# */ +/* Updated: 2024/06/30 14:50:34 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #pragma once #include #include @@ -11,39 +23,38 @@ class Header { private: /* Receive Header*/ - std::string method; - ExtendedString path; - - std::string protocol; - std::string status; - std::string server; - std::string date; - std::string lastModified; - size_t contentLength; - std::string contentType; - std::map attributes; + std::string method; + ExtendedString path; + std::string protocol; + std::string status; + std::string server; + std::string date; + std::string lastModified; + size_t contentLength; + std::string contentType; + std::map attributes; + std::multimap cookies; public: Header(); Header(std::string receiveHeader); ~Header(); - std::string generateHeader() const; - void setVersion(std::string version); - void setStatus(std::string status); - void setServer(std::string server); - void setDate(); - void setLastModified(std::string lastModified); - void setContentLength(size_t contentLength); - void setContentType(std::string contentType); - void setAttribute(std::string key, std::string value); - void setMethod(std::string method); - void setPath(std::string path); - void setProtocol(std::string protocol); - std::string getMethod(); - ExtendedString getPath(); - std::string getProtocol(); + std::string generateHeader() const; + void setStatus(std::string status); + void setServer(std::string server); + void setDate(); + void setLastModified(std::string lastModified); + void setContentLength(size_t contentLength); + void setContentType(std::string contentType); + void setAttribute(std::string key, std::string value); + void setPath(std::string path); + void setProtocol(std::string protocol); + std::string getMethod(); + ExtendedString getPath(); + std::string getProtocol(); + std::string getContentType(); + std::string getAttribute(std::string key); + void printReceivedHeader(); + void setCookie(std::string value); std::map getAttributes(); - std::string getContentType(); - std::string getAttribute(std::string key); - void printReceivedHeader(); }; diff --git a/mandatory/inc/ListDir.hpp b/mandatory/inc/ListDir.hpp index 0811886..acb1ffa 100644 --- a/mandatory/inc/ListDir.hpp +++ b/mandatory/inc/ListDir.hpp @@ -3,10 +3,10 @@ /* ::: :::::::: */ /* ListDir.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ -/* By: eavedill +#+ +:+ +#+ */ +/* By: eavedill +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/06/07 19:03:57 by eavedill #+# #+# */ -/* Updated: 2024/06/21 14:35:44 by eavedill ### ########.fr */ +/* Updated: 2024/06/30 14:47:57 by eavedill ### ########.fr */ /* */ /* ************************************************************************** */ @@ -20,30 +20,33 @@ #include "Attributes.hpp" #include "utils.hpp" #include "colors.h" +#define TEMPLATE_LIST_DIR "./Templates/dir_list.html" + class ListDir { - private: - std::ifstream file; - std::string path; - std::string homePath; - std::string contentToSend; - std::size_t posToSend; - std::map files; - bool isSendComplete; - public: - ListDir(); - ListDir(const std::string &, const std::string &); - ~ListDir(); - void setListOfFiles(); - std::map ::iterator getBeginOfFiles(); - std::map ::iterator getEndOfFiles(); - std::string getDirFileList(); - void setContentToList(); - void setIsSendComlete(); - bool getIsSendComlete(); - void openMasterListFile(); - std::string getContentToSend(); - size_t getSizeToSend(); - void setSubdirectory(const std::string &); + private: + std::ifstream file; + std::string path; + std::string homePath; + std::string contentToSend; + std::size_t posToSend; + std::map files; + bool isSendComplete; + + public: + ListDir(); + ListDir(const std::string &, const std::string &); + ~ListDir(); + std::map ::iterator getBeginOfFiles(); + std::map ::iterator getEndOfFiles(); + void setListOfFiles(); + std::string getDirFileList(); + void setContentToList(); + void setIsSendComlete(); + bool getIsSendComlete(); + void openMasterListFile(); + std::string getContentToSend(); + size_t getSizeToSend(); + void setSubdirectory(const std::string &); }; diff --git a/mandatory/inc/ListeningSocket.hpp b/mandatory/inc/ListeningSocket.hpp index 29a0d55..311df75 100644 --- a/mandatory/inc/ListeningSocket.hpp +++ b/mandatory/inc/ListeningSocket.hpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ListeningSocket.hpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:48:33 by eavedill #+# #+# */ +/* Updated: 2024/06/30 14:46:10 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #pragma once #include #include @@ -9,13 +21,11 @@ #include #include #include - #ifdef __APPLE__ -#include + #include #else -#include + #include #endif - #include #include #include @@ -28,16 +38,13 @@ #include "FileContent.hpp" #include "Header.hpp" #include "LocationParser.hpp" - - +#include "Environment.hpp" #define MAX_CONNECTIONS 10 class Server; class Receive; - -// #define MAX_EVENTS 10 class ListeningSocket : public FileContent { private: @@ -48,20 +55,19 @@ class ListeningSocket : public FileContent Header response; Header request; - //void handleConnection(int clientSocketFd); - public: ListeningSocket(int port, Server *srv); ListeningSocket(Server *srv); ~ListeningSocket(); - bool startListening(); - void stopListening(); - int getFd(); - bool sendData(int); - void loadRequest(std::vector servers); - ListeningSocket *clone(int fd); - std::string getAnswerToSend(); - bool receive(); - void matchServerName(std::vector servers); + bool startListening(); + void stopListening(); + int getFd(); + bool sendData(int); + void loadRequest(std::vector servers); + ListeningSocket *clone(int fd); + std::string getAnswerToSend(); + bool receive(); + void matchServerName(std::vector servers); + void setCgiEnviroment(); }; diff --git a/mandatory/inc/Location.hpp b/mandatory/inc/Location.hpp index c67bc44..9b130dd 100644 --- a/mandatory/inc/Location.hpp +++ b/mandatory/inc/Location.hpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* Location.hpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:48:41 by eavedill #+# #+# */ +/* Updated: 2024/06/30 13:48:42 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #ifndef LOCATION_HPP #define LOCATION_HPP @@ -92,6 +104,7 @@ class Location bool getIsSessionId() const; std::vector getCookies() const; std::string getSessionId() const; + // Setter methods void setName(const std::string&); diff --git a/mandatory/inc/LocationParser.hpp b/mandatory/inc/LocationParser.hpp index 58cd2fb..48c2d37 100644 --- a/mandatory/inc/LocationParser.hpp +++ b/mandatory/inc/LocationParser.hpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* LocationParser.hpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:48:49 by eavedill #+# #+# */ +/* Updated: 2024/06/30 14:43:58 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #pragma once #include #include @@ -29,35 +41,30 @@ class Server; class LocationParser { private: - Header request; - Header response; - Server *server; - Receive *receiver; - std::string query; - bool isAutoIndex; - bool isCGI; - size_t startRange; - size_t endRange; - std::string cgiPath; - // std::string - bool isCookie; - std::vector cookies; + Header request; + Header response; + Server *server; + Receive *receiver; + std::vector cookies; + std::string query; + bool isAutoIndex; + bool isCGI; + bool isCookie; + size_t startRange; + size_t endRange; + std::string cgiPath; - bool isSessionId; - std::string sessionId; public: LocationParser(Header request, Server *server, Receive *receiver); ~LocationParser(); - int matchingLocation(); - int isAllowedMethod(Location *location); - Header getRequest(); - Header getResponse(); - bool getIsAutoIndex(); - bool getIsCGI(); - void checks(); - void setCookies(); - size_t getStartRange(); - size_t getEndRange(); - std::string getQuery(); - void setSessionId(); -}; \ No newline at end of file + int matchingLocation(); + int isAllowedMethod(Location *location); + Header getRequest(); + Header getResponse(); + bool getIsAutoIndex(); + bool getIsCGI(); + void checks(); + void setCookies(); + size_t getStartRange(); + size_t getEndRange(); + std::string getQuery(); diff --git a/mandatory/inc/Parser.hpp b/mandatory/inc/Parser.hpp index 4a6e44d..e2b04b3 100644 --- a/mandatory/inc/Parser.hpp +++ b/mandatory/inc/Parser.hpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* Parser.hpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:48:59 by eavedill #+# #+# */ +/* Updated: 2024/06/30 14:41:40 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #pragma once # include # include @@ -16,22 +28,20 @@ class Parser { private: public: - static bool checkPorts(std::vector const &ports); - static bool checkPort(std::string port); - static bool checkHost(std::string host); - static bool checkServerName(std::string serverName); - static bool checkErrorPage(std::string errorPage); - static bool checkRoot(std::string root); - static bool checkPath(std::string root, std::string attributeName); - static bool checkIndex(std::string index, std::string root); + static bool checkPorts(std::vector const &ports); + static bool checkPort(std::string port); + static bool checkHost(std::string host); + static bool checkServerName(std::string serverName); + static bool checkErrorPage(std::string errorPage); + static bool checkRoot(std::string root); + static bool checkPath(std::string root, std::string attributeName); + static bool checkIndex(std::string index, std::string root); static in_addr_t isValidHost(std::string hostname); - static long long checkClientBodySize(std::string maxClientBodySize); - - static bool checkAutoIndex(std::string autoindex); - static int checkLocationName(std::string name); - static int checkRootAliasReturn(std::string root, std::string alias, std::string return_); - static bool checkReturnIgnore(std::string allowMethods, std::string autoindex, std::string index); - static bool checkCgiString(std::string cgiPath, std::string cgiExtension); - static bool checkCgi(std::vector paths, std::vector extensions); - static bool checkAllowedMethods(std::string allowMethods); + static long long checkClientBodySize(std::string maxClientBodySize); + static bool checkAutoIndex(std::string autoindex); + static int checkLocationName(std::string name); + static int checkRootAliasReturn(std::string root, std::string alias, std::string return_); + static bool checkReturnIgnore(std::string allowMethods, std::string autoindex, std::string index); + static bool checkCgi(std::string cgiExtension); + static bool checkAllowedMethods(std::string allowMethods); }; \ No newline at end of file diff --git a/mandatory/inc/Receive.hpp b/mandatory/inc/Receive.hpp index 6ce5bee..04b4003 100644 --- a/mandatory/inc/Receive.hpp +++ b/mandatory/inc/Receive.hpp @@ -1,42 +1,53 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* Receive.hpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:49:11 by eavedill #+# #+# */ +/* Updated: 2024/06/30 14:37:50 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #pragma once #include #include #include #include #include +#define MAX_MSG_SIZE 8192 - -#define MAX_MSG_SIZE 8192//2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 class Receive { - private: - std::string buffer; - std::string request; - std::string body; - bool isbody; - size_t maxSize; - size_t sizeSent; - std::ofstream file; - std::string boundary; - bool isform; - std::string postHeader; + private: + std::string buffer; + std::string request; + std::string body; + bool isbody; + size_t maxSize; + size_t sizeSent; + std::ofstream file; + std::string boundary; + bool isform; + std::string postHeader; - public: - Receive(); - ~Receive(); - Receive(Receive const ©); - Receive &operator=(Receive const ©); - - bool receiveHeader(int fd); - bool receiveBody(int fd); - bool receive(int fd); - void setBuffer(std::string buffer); - void setRequest(std::string request); - void setBody(std::string body); - void setmaxSize(size_t size); - - std::string getBuffer(); - std::string getRequest(); - std::string getBody(); - bool getisform(); - std::string getPostHeader(); + public: + Receive(); + ~Receive(); + Receive(Receive const ©); + Receive &operator=(Receive const ©); + + bool receiveHeader(int fd); + bool receiveBody(int fd); + bool receive(int fd); + void setBuffer(std::string buffer); + void setRequest(std::string request); + void setBody(std::string body); + void setmaxSize(size_t size); + + std::string getBuffer(); + std::string getRequest(); + std::string getBody(); + bool getisform(); + std::string getPostHeader(); }; \ No newline at end of file diff --git a/mandatory/inc/Server.hpp b/mandatory/inc/Server.hpp index 6d7b554..79dd3ad 100644 --- a/mandatory/inc/Server.hpp +++ b/mandatory/inc/Server.hpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* Server.hpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:49:18 by eavedill #+# #+# */ +/* Updated: 2024/06/30 14:35:38 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #ifndef SERVER_HPP # define SERVER_HPP # include @@ -14,15 +26,15 @@ # include "Parser.hpp" # include "ExtendedString.hpp" -#define VAR_PORT "port" -#define VAR_HOST "host" -#define VAR_SERVER_NAME "server_name" -#define VAR_ERROR_PAGE "error_page" -#define VAR_ROOT "root" -#define VAR_INDEX "index" +#define VAR_PORT "port" +#define VAR_HOST "host" +#define VAR_SERVER_NAME "server_name" +#define VAR_ERROR_PAGE "error_page" +#define VAR_ROOT "root" +#define VAR_INDEX "index" #define VAR_CLIENT_MAX_BODY_SIZE "client_max_body_size" -#define VAR_LOCATIONS "location" -#define VAR_AUTOINDEX "autoindex" +#define VAR_LOCATIONS "location" +#define VAR_AUTOINDEX "autoindex" #ifdef __APPLE__ #define READ_EVENT EVFILT_READ @@ -41,30 +53,27 @@ class ListeningSocket; class Server { protected: - bool isDefault; - std::map port; - std::vector ports; - long long maxBodySize; - std::string maxBodySizeStr; - std::string Host; - std::string serverName; - ExtendedString errorPage; - std::string root; - std::string index; - std::string autoIndexStr; - bool autoIndex; - std::vector locations; - CGI *cgiModule; - in_addr_t hostAddr; - // void setDefaultData(); + bool isDefault; + std::map port; + std::vector ports; + long long maxBodySize; + std::string maxBodySizeStr; + std::string Host; + std::string serverName; + ExtendedString errorPage; + std::string root; + std::string index; + std::string autoIndexStr; + bool autoIndex; + std::vector locations; + CGI *cgiModule; + in_addr_t hostAddr; public: - // Server(); Server(std::string &); ~Server(); Server(Server const &); - Server &operator=(Server const &); - //---- Server Methods ------// + Server &operator=(Server const &); //---- Server Methods ------// int loadData(std::string const &); CGI *cgiModuleClone(); @@ -83,34 +92,30 @@ class Server void setPorts(std::string const &ports); void setHostAddr(in_addr_t Addr); void setAutoindex(std::string const &); - //---- Server getters ------// - ListeningSocket *getListening(int i); - std::vector getPorts(); - std::vector getServerFds(); - - ListeningSocket * getPort(int i); - bool getIsDefault(); - std::string getHost(); - std::string getServerName(); - std::string getErrorPage(); - std::string getRoot(); - std::string getIndex(); - std::string getCGIExtension(const std::string &); - std::string getCGIFolder(); - in_addr_t getHostAddr(); - std::string getMaxClientBodySizeStr(); - long long getMaxClientBodySize(); - std::vector getLocations(); - bool getAutoIndex(); - void print(); - void createListeningSockets(); - void checkVariables(); - - //std::vector getLocations(); + ListeningSocket *getListening(int i); + std::vector getPorts(); + std::vector getServerFds(); + ListeningSocket * getPort(int i); + bool getIsDefault(); + std::string getHost(); + std::string getServerName(); + std::string getErrorPage(); + std::string getRoot(); + std::string getIndex(); + std::string getCGIExtension(const std::string &); + std::string getCGIFolder(); + in_addr_t getHostAddr(); + std::string getMaxClientBodySizeStr(); + long long getMaxClientBodySize(); + std::vector getLocations(); + bool getAutoIndex(); + void print(); + void createListeningSockets(); + void checkVariables(); }; -typedef void (Server::*server)(std::string); -typedef std::map server_methods_t; +typedef void (Server::*server)(std::string); +typedef std::map server_methods_t; #endif diff --git a/mandatory/inc/StatusCode.hpp b/mandatory/inc/StatusCode.hpp index b36f50e..2b7eb5d 100644 --- a/mandatory/inc/StatusCode.hpp +++ b/mandatory/inc/StatusCode.hpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* StatusCode.hpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:49:24 by eavedill #+# #+# */ +/* Updated: 2024/06/30 13:49:24 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #pragma once #include #include diff --git a/mandatory/inc/StatusCodesDefinition.hpp b/mandatory/inc/StatusCodesDefinition.hpp index 73681e3..fa9c517 100644 --- a/mandatory/inc/StatusCodesDefinition.hpp +++ b/mandatory/inc/StatusCodesDefinition.hpp @@ -1,4 +1,16 @@ -#define DEFAULT_ERROR_FILE "./StatusCodes/ErrorTemplate.html" +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* StatusCodesDefinition.hpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:49:29 by eavedill #+# #+# */ +/* Updated: 2024/06/30 13:49:29 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#define DEFAULT_ERROR_FILE "./Templates/ErrorTemplate.html" #define CONTINUE_CODE 100 #define SWITCHING_PROTOCOLS_CODE 101 #define OK_CODE 200 diff --git a/mandatory/inc/colors.h b/mandatory/inc/colors.h index 059d8f7..2b8072b 100644 --- a/mandatory/inc/colors.h +++ b/mandatory/inc/colors.h @@ -3,10 +3,10 @@ /* ::: :::::::: */ /* colors.h :+: :+: :+: */ /* +:+ +:+ +:+ */ -/* By: eavedill +#+ +:+ +#+ */ +/* By: eavedill +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/05/06 11:16:47 by eavedill #+# #+# */ -/* Updated: 2024/02/09 11:18:46 by eavedill ### ########.fr */ +/* Updated: 2024/06/30 14:58:03 by eavedill ### ########.fr */ /* */ /* ************************************************************************** */ @@ -14,7 +14,6 @@ # define COLORS_H // Standard color # define RESET "\033[0m" -//# define RESET "" // Background colors over black # define BCK_BLACK "\033[0;40m" # define BCK_RED "\033[0;41m" @@ -33,7 +32,6 @@ # define CHR_MGENTA "\033[0;35m" # define CHR_CYAN "\033[0;36m" # define CHR_WHITE "\033[0;37m" - # define BLACK "\033[30m" # define RED "\033[31m" # define GREEN "\033[32m" diff --git a/mandatory/inc/utils.hpp b/mandatory/inc/utils.hpp index b366bdf..afdf9fd 100644 --- a/mandatory/inc/utils.hpp +++ b/mandatory/inc/utils.hpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* utils.hpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:49:35 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:03:42 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #pragma once #include #include @@ -18,41 +30,22 @@ #include #include #include -#define MAX_SENT_BYTES 16048 //8024 +#define MAX_SENT_BYTES 16048 template bool isrange(T value, T min, T max); -bool isNumber(std::string str); -bool validIPAddress(std::string ip); -bool isDirPermissions(std::string path, int mode); -int isFilePermissions(std::string path, int mode); template std::string toString (T n) { std::string str; std::stringstream ss; - ss << n; ss >> str; - return str; } -std::string removeBlanksAndTabs(const std::string& input); -std::string removeCharFromString(const std::string& input, char c); -std::vector splitString(const std::string &str, char delimiter); -size_t stringToSizeT(const std::string& str); -std::map create_filetypes(); -void replaceString(std::string &mainString, const std::string &searchString, const std::string &replaceString); -int count_chars(const std::string &str, char c); - -std::string getTime(); -std::string getLocalTime(); -void printLog(std::string type ,std::string message); -std::string decodeURL(const std::string& url); - template T minimum(T a, T b) { @@ -69,4 +62,18 @@ T maximum(T a, T b) return b; }; -std::string getRandomHash(int lenght); \ No newline at end of file +bool isNumber(std::string str); +bool validIPAddress(std::string ip); +bool isDirPermissions(std::string path, int mode); +int isFilePermissions(std::string path, int mode); +std::string removeBlanksAndTabs(const std::string& input); +std::string removeCharFromString(const std::string& input, char c); +std::vector splitString(const std::string &str, char delimiter); +size_t stringToSizeT(const std::string& str); +std::map create_filetypes(); +void replaceString(std::string &mainString, const std::string &searchString, const std::string &replaceString); +int count_chars(const std::string &str, char c); +std::string getLocalTime(); +void printLog(std::string type ,std::string message); +std::string decodeURL(const std::string& url); + diff --git a/mandatory/src/Attributes.cpp b/mandatory/src/Attributes.cpp index b832a8a..042e9cf 100644 --- a/mandatory/src/Attributes.cpp +++ b/mandatory/src/Attributes.cpp @@ -6,7 +6,7 @@ /* By: eavedill +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/06/07 18:22:26 by eavedill #+# #+# */ -/* Updated: 2024/06/15 14:34:16 by eavedill ### ########.fr */ +/* Updated: 2024/06/30 15:10:47 by eavedill ### ########.fr */ /* */ /* ************************************************************************** */ @@ -24,7 +24,8 @@ Attributes::Attributes(const std::string& filename) this->setAttributesFromFile(filename); } -Attributes::~Attributes() { +Attributes::~Attributes() +{ } void Attributes::setAttributesFromFile(const std::string& filename) @@ -65,7 +66,6 @@ std::string Attributes::getCreated() std::string Attributes::getModified() { std::tm *timeInfo = std::gmtime(&this->attributes.st_mtime); - char buffer[80]; std::strftime(buffer, sizeof(buffer), "%A, %d-%b-%y %H:%M:%S GMT", timeInfo); return buffer; diff --git a/mandatory/src/CGI.cpp b/mandatory/src/CGI.cpp index d48ba56..a44673b 100644 --- a/mandatory/src/CGI.cpp +++ b/mandatory/src/CGI.cpp @@ -1,6 +1,18 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* CGI.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:49:55 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:28:58 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/CGI.hpp" -CGI::CGI() +CGI::CGI() : Environment() { this->fileName = ""; this->fileArgs = ""; @@ -9,7 +21,7 @@ CGI::CGI() this->setCGIMapExtensions("cgi"); } -CGI::CGI(const std::string &folder, const std::string &extensions) +CGI::CGI(const std::string &folder, const std::string &extensions) : Environment() { this->fileName = ""; this->isCGI = false; @@ -17,7 +29,7 @@ CGI::CGI(const std::string &folder, const std::string &extensions) this->setCGIMapExtensions(extensions); } -CGI::CGI(const CGI &src) +CGI::CGI(const CGI &src) : Environment() { this->fileName = ""; this->isCGI = false; @@ -41,15 +53,6 @@ void CGI::setFileName(const std::string &Name, const std::string &Args) fileName = Name; this->setArgs(Args); tmp = splitString(Args, '&'); - // std::map::iterator it = this->findCGIExtension(this->getFileExtension()); - // if (it != this->CGIExtensions.end()) - // { - // if (it->second.size() != 0) - // { - // fileName =it->second; - // this->setArgs(tmp[1]); - // } - // } } void CGI::setIsCGI(bool valCGI) @@ -87,11 +90,9 @@ std::string CGI::getCGIFolder() void CGI::setArgs(const std::string &str) { - std::cout << "Args: " << str << std::endl; std::vector vec = splitString(str, '&'); for (size_t i = 0; i < vec.size(); i++) { - std::cout << "Args: " << vec[i] << std::endl; args.push_back(vec[i]); } @@ -102,9 +103,15 @@ std::vector CGI::getArgs() return args; } -std::map::iterator CGI::findCGIExtension(const std::string &str) { return this->CGIExtensions.find(str); } +std::map::iterator CGI::findCGIExtension(const std::string &str) +{ + return this->CGIExtensions.find(str); +} -std::string CGI::getCGIExtension(const std::string &str) { return this->CGIExtensions[str]; } +std::string CGI::getCGIExtension(const std::string &str) +{ + return this->CGIExtensions[str]; +} std::string CGI::getFileExtension() { @@ -120,7 +127,6 @@ std::string CGI::execute() signal(SIGALRM, &CGI::alarm_handler); int fd[2], tmp_fd; tmp_fd = dup(STDOUT_FILENO); - std::cout << "Executable: " << Executable << std::endl; std::vector ExecArray; ExecArray.push_back(const_cast(Executable.c_str())); std::vector::iterator itb = args.begin(); @@ -135,57 +141,41 @@ std::string CGI::execute() } pid_t pid = fork(); if (pid == -1) { - // Handle error forking process throw INTERNAL_SERVER_ERROR_CODE; return ""; } if (pid == 0) { - // Child process dup2(fd[1], STDOUT_FILENO); close(fd[0]); - // Convert the arguments vector to a null-terminated array - // Execute the file with its parameters - if (execve(Executable.c_str(), ExecArray.data(), NULL) == -1) + std::vector envp = this->getEnv(); + if (execve(Executable.c_str(), ExecArray.data(), envp.data()) == -1) { - // Handle error executing file - std::cerr << "Error executing file " << Executable << " with errno " << errno << std::endl; - exit(EXIT_FAILURE); + std::cerr << "Error: " << errno << std::endl; + exit(errno); } } - // Parent process close(fd[1]); - // Wait for the child process to finish CGI::ChildPID = pid; alarm(timeout); int status; - // pid_t result = waitpid(pid, &status, 0); waitpid(pid, &status, 0); - std::string output; - // Check if the child process exited normally - // std::cout << "Result: " << static_cast (result) << "errno "<< EINTR << "vs" << errno << std::endl; - // if (result == -1 && errno == EINTR) - // { - // kill(pid, SIGKILL); - // throw GATEWAY_TIME_OUT_CODE; - // } - // else - // { - if (WIFEXITED(status)) + if (WIFEXITED(status) && WEXITSTATUS(status) == 0) + { + char buffer[1024]; + ssize_t bytesRead; + while ((bytesRead = read(fd[0], buffer, sizeof(buffer))) > 0) { - // Read the output from the file descriptor - char buffer[1024]; - ssize_t bytesRead; - while ((bytesRead = read(fd[0], buffer, sizeof(buffer))) > 0) { - output += std::string(buffer, bytesRead); - } - close(fd[0]); - fd[1] = tmp_fd; + output += std::string(buffer, bytesRead); } - else - throw INTERNAL_SERVER_ERROR_CODE; - // } - return output; + close(fd[0]); + fd[1] = tmp_fd; + } + else + { + throw INTERNAL_SERVER_ERROR_CODE; + } + return output; } void CGI::setCGIMapExtensions(std::string const &cgi_extension) @@ -215,7 +205,7 @@ void CGI::setCGIMapExtensions(std::string const &cgi_extension) } else if (n == 0) { - this->CGIExtensions[aux[i]] = ""; // Si no hay programa de ejecuciĆ³n, se asume que es un CGI ejecutable. + this->CGIExtensions[aux[i]] = ""; } else { diff --git a/mandatory/src/Environment.cpp b/mandatory/src/Environment.cpp new file mode 100644 index 0000000..86dcdc2 --- /dev/null +++ b/mandatory/src/Environment.cpp @@ -0,0 +1,53 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* Environment.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:50:02 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:27:37 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "../inc/Environment.hpp" +#include + +Environment::Environment() +{ +} + +Environment::~Environment() +{ + std::vector::iterator itb = this->_envArray.begin(); + std::vector::iterator ite = this->_envArray.end(); + while(itb != ite) + { + delete *itb; + itb++; + } +} + +void Environment::setEnv(const std::string key, const std::string value) +{ + this->_env[key] = value; +} + +std::vector Environment::getEnv() +{ + std::map::iterator itb = this->_env.begin(); + std::map::iterator ite = this->_env.end(); + while(itb != ite) + { + std::string *tmp = new std::string(itb->first + "=" + itb->second + '\0'); + _envArray.push_back(const_cast(tmp->c_str())); + itb++; + } + _envArray.push_back(NULL); + return _envArray; +} + +std::string Environment::getEnv(std::string key) +{ + return this->_env[key]; +} diff --git a/mandatory/src/ExtendedString.cpp b/mandatory/src/ExtendedString.cpp index 48f1864..92edb7c 100644 --- a/mandatory/src/ExtendedString.cpp +++ b/mandatory/src/ExtendedString.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ExtendedString.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:50:11 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:27:27 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/ExtendedString.hpp" ExtendedString::ExtendedString() : std::string() {} @@ -25,7 +37,8 @@ bool ExtendedString::isNumber() const { return true; } -bool ExtendedString::firstCharIsSign() const { +bool ExtendedString::firstCharIsSign() const +{ return this->at(0) == '-' || this->at(0) == '+'; } @@ -52,7 +65,6 @@ bool ExtendedString::validIPAddress() size_t pos = 0; ExtendedString token; int count = 0; - while ((pos = this->find('.')) != std::string::npos) { token = this->substr(0, pos); @@ -61,10 +73,8 @@ bool ExtendedString::validIPAddress() this->erase(0, pos + 1); count++; } - if (count != 4 || !this->isNumber() || !isrange(std::atoi(this->c_str()), 0, 255)) return false; - return count == 4; } @@ -88,17 +98,6 @@ std::vector ExtendedString::splitString(char delimiter) { return result; } -//***To be used in case do not want to modify the original string -// ExtendedString ExtendedString::removeCharFromString(char charToRemove) { -// ExtendedString result; -// for (size_t i = 0; i < this->size(); i++) { -// if (this->at(i) != charToRemove) { -// result += this->at(i); -// } -// } -// return result; -// } - void ExtendedString::removeCharFromString(char charToRemove) { size_t pos = 0; while ((pos = this->find(charToRemove, pos)) != std::string::npos) { @@ -106,17 +105,6 @@ void ExtendedString::removeCharFromString(char charToRemove) { } } -//***To be used in case do not want to modify the original string -// ExtendedString ExtendedString::removeBlanksAndTabs() { -// ExtendedString result; -// for (size_t i = 0; i < this->size(); i++) { -// if (this->at(i) != ' ' && this->at(i) != '\t') { -// result += this->at(i); -// } -// } -// return result; -// } - void ExtendedString::removeBlanksAndTabs() { size_t pos = 0; while ((pos = this->find(' ', pos)) != std::string::npos) { diff --git a/mandatory/src/FileContent.cpp b/mandatory/src/FileContent.cpp index 5b3a0f2..bbcaadf 100644 --- a/mandatory/src/FileContent.cpp +++ b/mandatory/src/FileContent.cpp @@ -1,6 +1,17 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* FileContent.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:50:28 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:26:47 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/FileContent.hpp" -// FileContent::FileContent(Server *srv) : StatusCode() FileContent::FileContent() : StatusCode() { fileName = ""; @@ -66,12 +77,10 @@ std::string FileContent::getContent() if (this->startRange != 0 && this->getFirstFragment()) { - //file.seekg(0, std::ios::beg); file.seekg(startRange, std::ios::beg); lastSendingPosition = currentSendingPosition; file.read(buffer, MAX_SENT_BYTES); content.append(buffer, file.gcount()); - //this->setIsSendComplete(true); } else { @@ -82,7 +91,6 @@ std::string FileContent::getContent() currentSendingPosition = file.tellg(); if (file.eof()) { -// std::cout << "Cierro fichero " << fileName << std::endl; file.close(); this->setIsSendComplete(true); } @@ -110,8 +118,6 @@ bool FileContent::setFileName(const std::string &file_name, const std::string &f listDir->setSubdirectory(file_name); listDir->setContentToList(); } - // else if (cgiModule->setIdentifyCGIFromFileName(file_name)) - // else if (this->isCgi) else if (cgiModule->getIsCGI() ) { cgiModule->setFileName(file_name, fileArgs); @@ -119,20 +125,10 @@ bool FileContent::setFileName(const std::string &file_name, const std::string &f } else { - // if (this->isInputDirectory()) - // { - // fileName = homeFolder + indexName; - // } - // else - // { - fileName = file_name; - // } + fileName = file_name; stat(fileName.c_str(), &fileStat); completeContentSize = fileStat.st_size; this->setIsFileOpen(this->openFile()); - // isFileOpen = true; - // if (this->getIsFileOpen()) - // file.seekg(startRange, std::ios::beg); } } return this->getIsFileOpen(); @@ -181,7 +177,6 @@ std::string FileContent::getLastModified() return ""; } char buffer[80]; - strftime(buffer, sizeof(buffer), "%A, %d-%b-%y %H:%M:%S GMT", localtime(&fileStat.st_mtime)); return buffer; } diff --git a/mandatory/src/Header.cpp b/mandatory/src/Header.cpp index 6736334..64c6de8 100644 --- a/mandatory/src/Header.cpp +++ b/mandatory/src/Header.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* Header.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:52:00 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:26:03 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/Header.hpp" @@ -14,7 +26,6 @@ Header::Header(std::string receiveHeader) { std::istringstream iss(receiveHeader); std::string line; - while (std::getline(iss, line)) { size_t colonPos = line.find(':'); @@ -43,11 +54,6 @@ Header::Header(std::string receiveHeader) } } } - // std::cout << "HEADER" << std::endl; - // for (std::map::const_iterator it = attributes.begin(); it != attributes.end(); ++it) - // { - // std::cout << it->first << " => " << it->second << std::endl; - // } } void Header::setAttribute(std::string key, std::string value) @@ -84,8 +90,6 @@ void Header::setPath(std::string path) std::string Header::generateHeader() const { std::string header; - - // std::cout << "Version: $" << Version << "$" << std::endl; header = protocol + " " + status + "\r\n"; header += "Server: " + server + "\r\n"; header += "Date: " + date + "\r\n"; @@ -96,7 +100,8 @@ std::string Header::generateHeader() const header += "Content-Type: " + contentType + "\r\n"; for (std::map::const_iterator it = attributes.begin(); it != attributes.end(); ++it) header += it->first + ": " + it->second + "\r\n"; - + for (std::multimap::const_iterator it = cookies.begin(); it != cookies.end(); ++it) + header += it->first + ": " + it->second + "\r\n"; header += "\r\n"; return header; @@ -129,18 +134,19 @@ void Header::setServer(std::string server) void Header::setDate() { - // Get the current time std::time_t currentTime = std::time(NULL); - - // Convert the current time to a string in the desired format std::tm* timeInfo = std::gmtime(¤tTime); char buffer[80]; std::strftime(buffer, sizeof(buffer), "%A, %d-%b-%y %H:%M:%S GMT", timeInfo); - - // Set the date in the header this->date = buffer; } +void Header::setCookie(std::string value) +{ + this->cookies.insert(std::pair("Set-Cookie", value)); +} + + void Header::setLastModified(std::string lastModified) { this->lastModified = lastModified; @@ -155,15 +161,11 @@ void Header::setContentType(std::string contentType) { size_t point = contentType.find_last_of("."); std::string extension = contentType.substr(point + 1, contentType.size()); - - /* Create once only */ std::map Mimetype = create_filetypes(); - if (Mimetype.find(extension) != Mimetype.end()) this->contentType = Mimetype[extension]; else this->contentType = "text/html"; - } void Header::printReceivedHeader() diff --git a/mandatory/src/ListDir.cpp b/mandatory/src/ListDir.cpp index 0195795..e08e376 100644 --- a/mandatory/src/ListDir.cpp +++ b/mandatory/src/ListDir.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ListDir.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:51:56 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:25:36 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/ListDir.hpp" @@ -62,14 +74,12 @@ std::string ListDir::getDirFileList() { std::string content = ""; std::map ::iterator itb = files.begin(); - //do not add ./ and ../ itb++; itb++; std::map::iterator ite = files.end(); while (itb != ite) { content = content + "\n"); contentToSend += "\n"; } @@ -111,12 +118,12 @@ void ListDir::setIsSendComlete() bool ListDir::getIsSendComlete() { - return isSendComplete; + return isSendComplete; } void ListDir::openMasterListFile() { - std::string filename = "./Master/dir_list.html"; + std::string filename = TEMPLATE_LIST_DIR; file.open(filename.c_str(), std::ios::out | std::ios::binary); } diff --git a/mandatory/src/ListeningSocket.cpp b/mandatory/src/ListeningSocket.cpp index 056409b..65a0caf 100644 --- a/mandatory/src/ListeningSocket.cpp +++ b/mandatory/src/ListeningSocket.cpp @@ -1,13 +1,22 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ListeningSocket.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:51:47 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:38:42 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/ListeningSocket.hpp" ListeningSocket::ListeningSocket(int myPort, Server *srv): FileContent() { this->port = myPort; this->server = srv; - // this->client = new Client(srv); this->receiver = new Receive(); - // this->fileContent = new FileContent(); - this->socketFd = -1; if (this->startListening()) { @@ -23,9 +32,7 @@ ListeningSocket::ListeningSocket(int myPort, Server *srv): FileContent() ListeningSocket::ListeningSocket(Server *srv): FileContent() { - // this->client = new Client(srv); this->receiver = new Receive(); - // this->fileContent = new FileContent(); this->server = srv; this->loadErrorPageFromDir(srv->getErrorPage()); this->setIsAutoIndex(srv->getAutoIndex()); @@ -38,7 +45,6 @@ ListeningSocket::~ListeningSocket() { stopListening(); delete this->receiver; - // delete this->fileContent; } bool ListeningSocket::startListening() @@ -49,13 +55,11 @@ bool ListeningSocket::startListening() std::cerr << "Failed to create socket" << std::endl; return false; } - if (fcntl(socketFd, F_SETFL, O_NONBLOCK) < 0) { std::cerr << CHR_RED"Error" << std::endl; exit(1); } - int enable = 1; setsockopt(socketFd, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(enable)); if (setsockopt(socketFd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) @@ -63,21 +67,15 @@ bool ListeningSocket::startListening() std::cerr << "setsockopt(SO_REUSEADDR) failed" << std::endl; exit(1); } - - // Set up the server address sockaddr_in serverAddress; serverAddress.sin_family = AF_INET; serverAddress.sin_addr.s_addr = this->server->getHostAddr(); serverAddress.sin_port = htons(port); - - // Bind the socket to the server address if (bind(socketFd, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) { printLog("ERROR", "Failed to bind socket to address of port " CHR_RED + toString(port) + RESET); return false; } - - // Start listening for incoming connections if (listen(socketFd, SOMAXCONN) < 0) { std::cerr << "Failed to start listening of port " << port << std::endl; @@ -103,10 +101,11 @@ int ListeningSocket::getFd() bool ListeningSocket::sendData(int clientSocketFd) { ExtendedString answer = this->getAnswerToSend(); - // std::cout << "answer: " << answer.size() << std::endl; - // std::cout << "My answer: " << answer << std::endl; - if ((send(clientSocketFd, answer.c_str(), answer.size(), 0)) < 0) + int ret; + if ((ret = send(clientSocketFd, answer.c_str(), answer.size(), 0)) < 0) std::cerr << "Failed to write to client" << std::endl; + else if (ret == 0) + printLog("WARNING", "send 0 bytes"); return this->getIsSendComplete(); } @@ -119,23 +118,20 @@ bool ListeningSocket::receive() ListeningSocket *ListeningSocket::clone(int fd) { ListeningSocket *newSocket = new ListeningSocket(this->server); + newSocket->port = this->port; newSocket->socketFd = fd; return newSocket; } std::string ListeningSocket::getAnswerToSend() { - // long long sendingValue; std::string answer; std::string filePath = this->getFileName(); std::string file_content = this->getContent(); - if (this->getFirstFragment()) { answer = response.generateHeader() + file_content; this->setFirstFragment(false); - // std::cout << "Answer: " << answer.substr(0, 200) << std::endl; - // std::cout << "------------------------------------------------" << std::endl; } else answer = file_content; @@ -163,16 +159,13 @@ void ListeningSocket::setCgiEnviroment() this->cgiModule->setEnv(SERVER_ADDR_KEY, server->getHost()); this->cgiModule->setEnv(SERVER_NAME_KEY, server->getServerName()); this->cgiModule->setEnv(REQUEST_METHOD_KEY, this->request.getMethod()); - // this->cgiModule->setEnv(PATH_INFO, this->request.getPath()); - // this->cgiModule->setEnv(PROT, this->request.getProtocol()); - this->cgiModule->setEnv(SERVER_PORT_KEY, this->request.getAttribute("Host").substr(this->request.getAttribute("Host").find(":"))); + this->cgiModule->setEnv(SERVER_PORT_KEY, toString(this->port)); this->cgiModule->setEnv(CONTENT_LENGTH_KEY, this->request.getAttribute("Content-Lenght")); this->cgiModule->setEnv(CONTENT_TYPE_KEY, this->request.getAttribute("Content-Type")); this->cgiModule->setEnv(HTTP_USER_AGENT_KEY, this->request.getAttribute("User-Agent")); - // this->cgiModule->setEnv(, this->request.getAttribute("Host")); this->cgiModule->setEnv(SERVER_SOFTWARE_KEY, "ws_cheelave/1.0"); this->cgiModule->setEnv(GATEWAY_INTERFACE_KEY, "CGI/1.1"); - // this->cgiModule->setEnv(QUERY_STRING_KEY,this->); + } void ListeningSocket::loadRequest(std::vector servers) @@ -192,16 +185,13 @@ void ListeningSocket::loadRequest(std::vector servers) this->response = Parser.getResponse(); return ; } - this->cgiModule->setEnv(SCRIPT_FILENAME_KEY, this->request.getPath()); + Parser.setCookies(); - Parser.setSessionId(); this->request = Parser.getRequest(); + this->cgiModule->setEnv(PATH_INFO_KEY, this->request.getPath().substr(0, this->request.getPath().rfind("/"))); + this->cgiModule->setEnv(SCRIPT_FILENAME_KEY, this->request.getPath()); this->response = Parser.getResponse(); this->setIsAutoIndex(Parser.getIsAutoIndex()); this->setIsCGI(Parser.getIsCGI()); - - this->setStartRange(Parser.getStartRange()); - this->setEndRange(Parser.getEndRange()); - this->setFileName(this->request.getPath(), Parser.getQuery()); } diff --git a/mandatory/src/Location.cpp b/mandatory/src/Location.cpp index c850d58..3a7090a 100644 --- a/mandatory/src/Location.cpp +++ b/mandatory/src/Location.cpp @@ -3,10 +3,10 @@ /* ::: :::::::: */ /* Location.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ -/* By: jcheel-n +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/04/29 17:38:18 by eavedill #+# #+# */ -/* Updated: 2024/06/29 21:31:29 by jcheel-n ### ########.fr */ +/* Updated: 2024/06/30 15:24:13 by eavedill ### ########.fr */ /* */ /* ************************************************************************** */ @@ -47,7 +47,6 @@ std::map getLocationMethods return locationMethods; } - Location::Location() { name = ""; @@ -57,16 +56,20 @@ Location::Location() allowMethodsStr = ""; autoindex = ""; alias = ""; - // cgiPathStr = ""; cgiExtensionStr = ""; isCgi = false; isSessionId = false; isCookie = false; + cookiesStr = ""; } + Location::Location(std::string const &content) { this->isCgi = false; this->cgiEnabledStr = ""; + isCookie = false; + cookiesStr = ""; + isSessionId = false; this->loadData(content); } @@ -81,10 +84,8 @@ Location::Location(const Location& other) setAlias(other.alias); } - Location::~Location() {} -// Getter methods const std::string &Location::getName() const { return name; } const std::string &Location::getRoot() const { return root; } const std::string &Location::getReturn() const { return return_; } @@ -100,9 +101,6 @@ enum LocationType Location::getLocationType() { return this->LocationType; } bool Location::getIsCgi() const { return isCgi; } bool Location::getIsCookie() const { return isCookie; } std::vector Location::getCookies() const { return cookies; } -bool Location::getIsSessionId() const { return isSessionId; } -std::string Location::getSessionId() const { return sessionIdStr; } -// Setter methods void Location::setName(const std::string &n) { name = n; } void Location::setRoot(const std::string &r) { root = r; } void Location::setReturn(const std::string &ret) { return_ = ret; } @@ -110,11 +108,11 @@ void Location::setIndex(const std::string &idx) { index = idx; } void Location::setAllowMethodsStr(const std::string &allow) { allowMethodsStr = allow; } void Location::setAutoindex(const std::string &autoidx) { autoindexStr = autoidx; } void Location::setAlias(const std::string &als) { alias = als; } -void Location::setCgiEnabledStr(const std::string &cgiEnabled) { - this->cgiEnabledStr = cgiEnabled; -} + +void Location::setCgiEnabledStr(const std::string &cgiEnabled) {this->cgiEnabledStr = cgiEnabled;} void Location::setSessionIdStr(const std::string &name){ this->isSessionId = true ; this->sessionIdStr = name; } void Location::setCookieStr(const std::string &cookie) {this->isCookie = true ; this->cookiesStr = cookie; } + bool Location::setCgiEnabled() { if (this->cgiEnabledStr == "true") @@ -130,6 +128,7 @@ bool Location::setCgiEnabled() isCgi = false; return isCgi; } + void Location::setCgiExtensionStr(const std::string &extensions) { this->cgiExtensionStr = extensions; } void Location::setAllowMethods(const std::string& methods) @@ -140,7 +139,7 @@ void Location::setAllowMethods(const std::string& methods) { if (line.length() == 0) continue; - if (line == "GET")// || line == "POST" || line == "DELETE") + if (line == "GET") { this->allowMethods.push_back(line); this->isGetAllowed = true; @@ -162,17 +161,6 @@ void Location::setAllowMethods(const std::string& methods) } } } -// void Location ::setCgiPath(const std::string &paths) -// { -// std::string line; -// std::istringstream cgiPathStream(paths); -// while (std::getline(cgiPathStream, line, ',')) -// { -// if (line.length() == 0) -// continue; -// this->cgiPath.push_back(line); -// } -// } void Location ::setCgiExtension(const std::string &extensions) { @@ -188,14 +176,12 @@ void Location ::setCgiExtension(const std::string &extensions) } } -// Load data from a string configuration int Location::loadData(const std::string &content) { std::string start_string = STR_START; std::string line; std::string straux; std::map varnames = var_names_location(); - std::istringstream fileContentStream(content); while (std::getline(fileContentStream, line, ';')) { @@ -262,7 +248,6 @@ void Location::checkVariables(bool serverAutoIndex) if (!Parser::checkCgi(this->cgiExtensionStr)) exit(1); } - switch (Parser::checkRootAliasReturn(this->root, this->alias,this->return_)) { case ROOT: @@ -283,7 +268,6 @@ void Location::checkVariables(bool serverAutoIndex) default: break; } - switch (Parser::checkAutoIndex(this->getAutoIndexStr())) { case true: @@ -301,7 +285,6 @@ void Location::checkVariables(bool serverAutoIndex) this->autoindex = false; break; } - this->setAllowMethods(this->allowMethodsStr); if (!Parser::checkAllowedMethods(this->allowMethodsStr)) this->isGetAllowed = true; @@ -318,13 +301,6 @@ void Location::checkVariables(bool serverAutoIndex) else if (this->isCookie && !this->cookiesStr.empty()) this->setCookies(this->cookiesStr); - if (this->isSessionId && this->sessionIdStr.empty()) - { - printLog("WARNING", "set-sesion-id\t\t\tnot defined."); - this->isSessionId = false; - } - else if (this->isSessionId && !this->sessionIdStr.empty()) - this->setSessionIdStr(this->sessionIdStr); } std::vector Location::getCgiExtension() diff --git a/mandatory/src/LocationParser.cpp b/mandatory/src/LocationParser.cpp index 5b9f4a3..542ece4 100644 --- a/mandatory/src/LocationParser.cpp +++ b/mandatory/src/LocationParser.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* LocationParser.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:51:38 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:22:31 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/LocationParser.hpp" #include #include @@ -6,8 +18,6 @@ static std::string getMimeType(std::string contentType) { size_t point = contentType.find_last_of("."); std::string extension = contentType.substr(point + 1, contentType.size()); - - /* Create once only */ std::map Mimetype = create_filetypes(); if (Mimetype.find(extension) != Mimetype.end()) return(Mimetype[extension]); @@ -15,25 +25,11 @@ static std::string getMimeType(std::string contentType) return ("text/html"); } -bool LocationParser::getIsAutoIndex() -{ - return this->isAutoIndex; -} - -bool LocationParser::getIsCGI() -{ - return this->isCGI; -} - -size_t LocationParser::getStartRange() -{ - return this->startRange; -} - -size_t LocationParser::getEndRange() -{ - return this->endRange; -} +bool LocationParser::getIsAutoIndex() { return this->isAutoIndex; } +bool LocationParser::getIsCGI(){ return this->isCGI; } +Header LocationParser::getResponse() { return this->response; } +Header LocationParser::getRequest() { return this->request; } +std::string LocationParser::getQuery() { return this->query; } int LocationParser::isAllowedMethod(Location *location) { @@ -52,7 +48,6 @@ int LocationParser::isAllowedMethod(Location *location) response.setStatus("405 Method Not Allowed"); return NOT_ALLOWED; } - } else if (this->request.getMethod() == "DELETE") { @@ -79,8 +74,6 @@ int LocationParser::matchingLocation() this->isAutoIndex = locations[i]->getAutoIndex(); if ((this->isCookie = locations[i]->getIsCookie()) == true) this->cookies = locations[i]->getCookies(); - if ((this->isSessionId = locations[i]->getIsSessionId()) == true) - this->sessionId = locations[i]->getSessionId(); if (locations[i]->getIsCgi() == true) { std::string extension; @@ -119,7 +112,6 @@ int LocationParser::matchingLocation() } } return NO_LOCATION; - } off_t getFileSize(const std::string &filename) @@ -129,27 +121,6 @@ off_t getFileSize(const std::string &filename) return rc == 0 ? stat_buf.st_size : -1; } -std::string escapeNonPrintableChars(const std::string& str) { - std::string escapedStr; - for (size_t i = 0; i < str.size(); ++i) { - switch (str[i]) { - case '\n': - escapedStr += "\\n"; - break; - case '\r': - escapedStr += "\\r"; - break; - case '\t': - escapedStr += "\\t"; - break; - default: - escapedStr += str[i]; - break; - } - } - return escapedStr; -} - bool isBadRequest(std::string request) { if (request.empty()) @@ -157,7 +128,6 @@ bool isBadRequest(std::string request) std::istringstream iss(request); std::string line; bool firstLine = true; - while (std::getline(iss, line)) { if (firstLine) @@ -214,36 +184,6 @@ void LocationParser::setCookies() } } -void LocationParser::setSessionId() -{ - std::cout << "SESSIONID " << this->sessionId << std::endl; - std::cout << "ISSESSIONID " << this->isSessionId << std::endl; - if (isSessionId) - { - std::string cookieHeader = this->request.getAttribute("Cookie"); - if (cookieHeader.empty() || cookieHeader.find(this->sessionId) == std::string::npos) - { - std::cout << "cookieHeader " << cookieHeader << std::endl; - - this->sessionId = this->sessionId + "=" + getRandomHash(50); - - std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); - std::tm* expireDate = std::gmtime(&now); - // expireDate->tm_min += 2; // Add 2 minutes to the current time - expireDate->tm_sec += 30; - if (expireDate->tm_sec >= 60) { // Ajusta si los segundos exceden 60 - expireDate->tm_sec -= 60; - expireDate->tm_min += 1; - } - - std::string expireDateString = std::asctime(expireDate); - expireDateString = expireDateString.substr(0, expireDateString.size() - 1); // Remove the newline character - - response.setCookie(sessionId + "; path=/ ; expires=" + expireDateString + " GMT"); - } - } -} - void LocationParser::checks() { std::string path; @@ -269,12 +209,11 @@ void LocationParser::checks() case REDIRECT: return ; } - this->request.setPath(decodeURL(this->request.getPath())); ExtendedString tmp = this->request.getPath(); tmp.replaceFirstString("//", "/"); this->request.setPath(tmp); - if (isBadRequest(receiver->getRequest()))//|| isURIMalformed(this->request.getPath()) + if (isBadRequest(receiver->getRequest())) { response.setStatus("400 Bad Request"); throw BAD_REQUEST_CODE; @@ -302,31 +241,6 @@ void LocationParser::checks() { if (getMimeType(this->request.getPath()).find("video") != std::string::npos) { - // std::string attr = request.getAttribute("Range"); - // int tt = isFilePermissions(this->request.getPath(), F_OK | R_OK); - // (void)tt; - // if (isFilePermissions(this->request.getPath(), F_OK | R_OK) == 1 && request.getAttribute("Range") != "") - // { - - // response.setStatus("206 Partial Content"); - // response.setContentType(this->request.getPath()); - - // if (this->request.getAttribute("Range") != "") - // { - // this->startRange = stringToSizeT(this->request.getAttribute("Range").substr(6, this->request.getAttribute("Range").find("-"))); - // std::cout << "STARTRANGE " << this->startRange << std::endl; - // std::string endRangeStr = this->request.getAttribute("Range").substr(this->request.getAttribute("Range").find("-") + 1, this->request.getAttribute("Range").size()); - // std::cout << "ENDRANGE " << endRangeStr << std::endl; - // if (endRangeStr.empty()) - // { - // this->endRange = getFileSize(this->request.getPath()); - // } - // else - // { - // this->endRange = stringToSizeT(endRangeStr); - // } - // } - // } if (isFilePermissions(this->request.getPath(), F_OK | R_OK) == 1) { response.setContentType(this->request.getPath()); @@ -357,7 +271,6 @@ void LocationParser::checks() } else if (this->request.getMethod() == "POST") { - std::string body = receiver->getBody(); if (body.size() > (size_t)this->server->getMaxClientBodySize()) { @@ -408,15 +321,23 @@ void LocationParser::checks() else if (receiver->getisform()) { this->query = decodeURL(body); - std::cout << this->query << std::endl; - response.setStatus("201 Created"); - throw CREATED_CODE; + return ; + } response.setServer(server->getServerName()); } else if (this->request.getMethod() == "DELETE") { + switch (isFilePermissions(this->request.getPath(), W_OK)) + { + case -5: + response.setStatus("404 Not Found"); + throw NOT_FOUND_CODE; + case -4: + response.setStatus("403 Forbidden"); + throw FORBIDDEN_CODE; + } if (std::remove(this->request.getPath().c_str()) == 0) response.setStatus("200 OK"); else @@ -443,25 +364,11 @@ LocationParser::LocationParser(Header request_, Server *server_, Receive *receiv this->isAutoIndex = server->getAutoIndex(); this->startRange = 0; this->endRange = 0; + this->isCookie = false; } LocationParser::~LocationParser() { -} - -Header LocationParser::getResponse() -{ - return this->response; -} - -Header LocationParser::getRequest() -{ - return this->request; -} - -std::string LocationParser::getQuery() -{ - return this->query; } \ No newline at end of file diff --git a/mandatory/src/Parser.cpp b/mandatory/src/Parser.cpp index 6f053d0..016384c 100644 --- a/mandatory/src/Parser.cpp +++ b/mandatory/src/Parser.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* Parser.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:51:31 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:20:52 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/Parser.hpp" #include @@ -48,13 +60,11 @@ in_addr_t Parser::isValidHost(std::string hostname) struct addrinfo hints, *res; struct sockaddr_in *addr; in_addr_t in_addr; - std::memset(&hints, 0, sizeof(hints)); std::memset(&in_addr, 0, sizeof(in_addr)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; - int status = getaddrinfo(hostname.c_str(), NULL, &hints, &res); if (status != 0) return 0; @@ -94,8 +104,6 @@ bool Parser::checkErrorPage(std::string errorPage) printLog("WARNING", "error_page\t<" + errorPage + ">\tnot a valid directory." ); return false; } - - std::vector foundFiles; DIR *errorDirectory = opendir(errorPage.c_str()); struct dirent *entry; @@ -110,13 +118,10 @@ bool Parser::checkErrorPage(std::string errorPage) break; } } - } closedir(errorDirectory); - std::sort(foundFiles.begin(), foundFiles.end()); std::cout << CHR_GREEN << getLocalTime() << " [" << "NOTICE" << "]" RESET << "\t\terror_pages found\t" << RESET ; - if (foundFiles.size() == 0) { printLog("WARNING", "error_page\t<" + errorPage + ">\tno error files found." ); @@ -165,7 +170,6 @@ bool Parser::checkIndex(std::string index, std::string root) { if (index.length() == 0) return true; - switch (isFilePermissions(root + "/" + index, R_OK)) { case -1: @@ -186,7 +190,7 @@ bool Parser::checkIndex(std::string index, std::string root) return true; } -const long long MAX_BYTES = 1099511627776; // 1 Terabyte for example +const long long MAX_BYTES = 1099511627776; long long convertToBytes(const std::string& sizeStr) { @@ -194,7 +198,6 @@ long long convertToBytes(const std::string& sizeStr) while (pos < sizeStr.size() && (std::isdigit(sizeStr[pos]) || sizeStr[pos] == '.')) { pos++; } - if (pos == 0) { throw std::invalid_argument("Invalid size format"); } @@ -205,13 +208,11 @@ long long convertToBytes(const std::string& sizeStr) for (size_t i = 0; i < unit.size(); ++i) { unit[i] = std::tolower(unit[i]); } - const long long BYTES_IN_KB = 1024; const long long BYTES_IN_MB = BYTES_IN_KB * 1024; const long long BYTES_IN_GB = BYTES_IN_MB * 1024; const long long BYTES_IN_TB = BYTES_IN_GB * 1024; const long long BITS_IN_BYTE = 8; - long long bytes; if (unit.empty() || unit == "b") { bytes = static_cast(sizeValue); @@ -236,11 +237,9 @@ long long convertToBytes(const std::string& sizeStr) } else { throw std::invalid_argument("Unknown size unit"); } - if (bytes > MAX_BYTES) { throw std::overflow_error("Size exceeds the maximum allowed bytes"); } - return bytes; } @@ -275,7 +274,6 @@ long long Parser::checkClientBodySize(std::string maxClientBodySize) return nbr; } - bool Parser::checkAutoIndex(std::string autoindex) { if (autoindex.length() == 0) @@ -304,11 +302,6 @@ int Parser::checkLocationName(std::string name) printLog("ERROR", "location name\t\t\t\tmust start with /" ); exit(1); } - std::string tmp; - tmp = name; - tmp.erase(std::remove(tmp.begin(), tmp.end(), '/'), tmp.end()); - if (tmp == "cgi-bin") - return 2; return 1; } @@ -358,58 +351,13 @@ bool Parser::checkReturnIgnore(std::string allowMethods, std::string autoindex, return true; } -bool Parser::checkCgiString(std::string cgiPath, std::string cgiExtension) +bool Parser::checkCgi(std::string cgiExtension) { - if (cgiPath.empty() && cgiExtension.empty()) - { - printLog("ERROR", "cgi_path\t\t\tis not defined."); - printLog("ERROR", "cgi_extension\t\t\tis not defined."); - return false; - } - else if (cgiPath.empty()) - { - printLog("ERROR", "cgi_path\t\t\tis not defined."); - return false; - } - else if (cgiExtension.empty()) + if (cgiExtension.empty()) { printLog("ERROR", "cgi_extension\t\t\tis not defined."); return false; } - - return true; -} - -bool Parser::checkCgi(std::vector paths, std::vector extensions) -{ - if (paths.size() != extensions.size()) - { - printLog("ERROR", "cgi_path and cgi_extension must have the same number of elements."); - return false; - } - for (size_t size = 0; size < paths.size(); size++) - { - switch (isFilePermissions(paths[size], X_OK)) - { - case -2: - printLog("ERROR", "cgi_path\t\t<" + paths[size] + ">\tempty path"); - return false; - case -1: - printLog("ERROR", "cgi_path\t\t<" + paths[size] + ">\terror getting file metadata"); - return false; - case -3: - printLog("ERROR", "cgi_path\t\t<" + paths[size] + ">\tnot a regular file"); - return false; - case -4: - printLog("ERROR", "cgi_path\t\t<" + paths[size] + ">\tpermission denied"); - return false; - case -5: - printLog("ERROR", "cgi_path\t\t<" + paths[size] + ">\tfile not found"); - return false; - default: - break ; - } - } return true; } diff --git a/mandatory/src/Recieve.cpp b/mandatory/src/Recieve.cpp index 6c7f646..5e4ea3b 100644 --- a/mandatory/src/Recieve.cpp +++ b/mandatory/src/Recieve.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* Recieve.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:51:26 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:19:01 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/Receive.hpp" #include #include @@ -7,12 +19,10 @@ Receive::Receive() : buffer(""), request(""), body(""), isbody(false), maxSize(0), sizeSent(0), isform(false) { - // std::cerr << "Receive created" << std::endl; } Receive::~Receive() { - // std::cerr << "Receive destroyed" << std::endl; } Receive::Receive(Receive const ©) @@ -31,13 +41,11 @@ Receive &Receive::operator=(Receive const ©) return *this; } - /* Setters */ void Receive::setBuffer(std::string buffer) { this->buffer = buffer; } void Receive::setRequest(std::string request) { this->request = request; } void Receive::setBody(std::string body) { this->body = body; } void Receive::setmaxSize(size_t size) { this->maxSize = size; } - /* Getters */ std::string Receive::getBuffer() { return this->buffer; } std::string Receive::getRequest() { return this->request; } std::string Receive::getBody() { return this->body; } @@ -86,10 +94,9 @@ bool Receive::receiveHeader(int fd) this->isform = true; else { - this->body += this->buffer.substr(0, this->buffer.rfind(this->boundary) - 4); - this->body = this->body.substr(0, this->body.find(this->boundary) - 4); - this->postHeader = this->body.substr(this->body.find(this->boundary) + this->boundary.size() + 4, this->body.find("\r\n\r\n")); + this->postHeader = this->body.substr(this->boundary.size() + 4, this->body.find("\r\n\r\n") - this->boundary.size() - 4); this->body = this->body.substr(this->body.find("\r\n\r\n") + 4); + this->body = this->body.substr(0, this->body.rfind(this->boundary) - 2); } this->isbody = false; return true; @@ -102,7 +109,7 @@ bool Receive::receiveHeader(int fd) std::memset(buf, 0, MAX_MSG_SIZE); } - if (ret < 0) // This is not handle as an error + if (ret < 0) return false; else if (ret == 0) { @@ -116,7 +123,6 @@ bool Receive::receiveBody(int fd) { char buf[MAX_MSG_SIZE] = {0}; int ret = 0; - while ((ret = recv(fd, buf, MAX_MSG_SIZE, 0)) > 0) { this->sizeSent += ret; diff --git a/mandatory/src/Server.cpp b/mandatory/src/Server.cpp index e528e3b..4962fb8 100644 --- a/mandatory/src/Server.cpp +++ b/mandatory/src/Server.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* Server.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:51:20 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:17:30 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/Server.hpp" std::map var_names_server() @@ -32,6 +44,7 @@ std::map ServerSetters() Server::Server(std::string &str) { this->cgiModule = new CGI(); + this->cgiModule->setEnv("SERVER_HOST", this->getHost()); while (str.find("location") != std::string::npos) { std::string aux = str.substr(str.find("location:{")); @@ -53,11 +66,13 @@ Server::~Server() delete this->locations[i]; } -Server::Server(Server const ©) { +Server::Server(Server const ©) +{ *this = copy; } -Server &Server::operator=(Server const ©) { +Server &Server::operator=(Server const ©) +{ if (this != ©) { this->isDefault = copy.isDefault; this->port = copy.port; @@ -72,11 +87,11 @@ Server &Server::operator=(Server const ©) { return *this; } -int Server::loadData(std::string const &content) { +int Server::loadData(std::string const &content) +{ std::string line; std::string straux; std::map varnames = var_names_server(); - std::istringstream fileContentStream(content.substr(8, content.length() - 1)); while (std::getline(fileContentStream, line,';')) { @@ -141,7 +156,6 @@ void Server::createListeningSockets() } } - void Server::checkVariables() { if (Parser::checkPorts(this->getPorts()) == false) @@ -172,6 +186,5 @@ void Server::checkVariables() printLog("NOTICE", "OK! Location " + toString(i + 1)); std::cout << CHR_MGENTA"------------------------------" RESET << std::endl; } - std::cout << std::endl; } \ No newline at end of file diff --git a/mandatory/src/ServerGetters.cpp b/mandatory/src/ServerGetters.cpp index 39912e6..4041693 100644 --- a/mandatory/src/ServerGetters.cpp +++ b/mandatory/src/ServerGetters.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ServerGetters.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:51:14 by eavedill #+# #+# */ +/* Updated: 2024/06/30 13:51:14 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/Server.hpp" diff --git a/mandatory/src/ServerSetters.cpp b/mandatory/src/ServerSetters.cpp index 51c5b0a..ca4de88 100644 --- a/mandatory/src/ServerSetters.cpp +++ b/mandatory/src/ServerSetters.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ServerSetters.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:51:10 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:16:21 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/Server.hpp" void Server::setHost(std::string const &host) { this->Host = host; } @@ -9,9 +21,7 @@ void Server::setRoot(std::string const &root) { this->root = root; } void Server::setIndex(std::string const &index) { this->index = index; } void Server::setCGIFolder(std::string const &str) { this->cgiModule->setCGIFolder(str); } void Server::addLocation(std::string const &content) { this->locations.push_back(new Location(content)); } - void Server::setHostAddr(in_addr_t Addr) { this->hostAddr = Addr; } - void Server::setCGIExtension(std::string const &str) { this->cgiModule->setCGIMapExtensions(str); @@ -63,7 +73,6 @@ void Server::setPorts(std::string const &portsLine) { this->ports.push_back(toString(i)); } - } else { diff --git a/mandatory/src/StatusCode.cpp b/mandatory/src/StatusCode.cpp index e46be16..7a13dfd 100644 --- a/mandatory/src/StatusCode.cpp +++ b/mandatory/src/StatusCode.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* StatusCode.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:51:07 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:15:28 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/StatusCode.hpp" StatusCode::StatusCode() @@ -65,7 +77,6 @@ void StatusCode::setFileContentForStatusCode(int CodeNumber, const std::string & ExtendedString content(""); std::ifstream fileStream; fileStream.open(CodeFileContent.c_str(), std::ios::out | std::ios::binary); //| std::ios::app | std::ios::ate - if(fileStream.is_open()) { char buffer[MAX_SENT_BYTES]; @@ -77,7 +88,6 @@ void StatusCode::setFileContentForStatusCode(int CodeNumber, const std::string & { printLog("WARNING", CodeFileContent + " File does not exist.\t Set error page to default " CHR_GREEN "GET" RESET " value"); } - mapCodesFileContent[CodeNumber] = content; } @@ -120,7 +130,6 @@ void StatusCode::loadErrorPageFromDir(const ExtendedString &dir) } while ((dirp = readdir(dp)) != NULL) { - // std::cout << "dir " << dir << std::endl; if (dirp->d_type == DT_REG) { std::string fileName = dir + "/" + dirp->d_name; diff --git a/mandatory/src/WebServer.cpp b/mandatory/src/WebServer.cpp index 4a7f254..d572a49 100644 --- a/mandatory/src/WebServer.cpp +++ b/mandatory/src/WebServer.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* WebServer.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:50:54 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:14:05 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/WebServer.hpp" WebServer::WebServer() @@ -53,7 +65,6 @@ void WebServer::launchServers() { std::cout << CHR_YELLOW "Launching servers..." RESET << std::endl << std::endl; std::cout << "\e[4;37m Date & time \t\t\t\t\t\t\tport\tfd" << RESET << std::endl; - this->createListeningSockets(); std::cout << std::endl; try diff --git a/mandatory/src/WebServerLNX.cpp b/mandatory/src/WebServerLNX.cpp index 788785d..cfb6abb 100644 --- a/mandatory/src/WebServerLNX.cpp +++ b/mandatory/src/WebServerLNX.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* WebServerLNX.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:50:51 by eavedill #+# #+# */ +/* Updated: 2024/06/30 13:50:51 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #ifdef __linux__ #include "../inc/WebServer.hpp" @@ -19,7 +31,7 @@ void WebServer::addEventSet() { struct epoll_event event; memset(&event, 0, sizeof(event)); - event.events = EPOLLIN | EPOLLET; // Edge-triggered mode + event.events = EPOLLIN | EPOLLET; event.data.fd = serverFds[j]; if (epoll_ctl(this->kq, EPOLL_CTL_ADD, serverFds[j], &event) == -1) { @@ -38,8 +50,6 @@ int WebServer::waitEvent(struct epoll_event *evList) void WebServer::modifEvent(struct epoll_event eventList, int type) { - // struct epoll_event evSet; - eventList.events = type; if (epoll_ctl(this->kq, EPOLL_CTL_MOD, eventList.data.fd, &eventList) == -1) { @@ -83,7 +93,6 @@ int WebServer::acceptNewEvent(int curfd) std::cerr << "Error listening" << std::endl; exit(1); } - while (1) { struct sockaddr_storage addr; @@ -105,5 +114,4 @@ int WebServer::acceptNewEvent(int curfd) } return fd; } - #endif diff --git a/mandatory/src/WebServerMAC.cpp b/mandatory/src/WebServerMAC.cpp index 0ff6662..cdbd5a9 100644 --- a/mandatory/src/WebServerMAC.cpp +++ b/mandatory/src/WebServerMAC.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* WebServerMAC.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:50:44 by eavedill #+# #+# */ +/* Updated: 2024/06/30 13:50:44 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #ifdef __APPLE__ #include "../inc/WebServer.hpp" @@ -18,8 +30,6 @@ void WebServer::addEventSet() for (size_t j = 0; j < serverFds.size(); j++) { struct kevent evSet; - - // EV_SET(&evSet, serverFds[j], EVFILT_READ, EV_ADD | EV_CLEAR, NOTE_WRITE, 0, NULL); EV_SET(&evSet, serverFds[j], EVFILT_READ, EV_ADD | EV_CLEAR, 0, 0, NULL); if (kevent(this->kq, &evSet, 1, NULL, 0, NULL) == -1) { @@ -41,7 +51,6 @@ void WebServer::modifEvent(struct kevent event, int typeRem, int typeAdd) struct kevent evSet; (void) typeRem; EV_SET(&evSet, event.ident, typeAdd, EV_ADD, 0, 0, NULL); - //removeEventFd(event.ident, typeRem); if (kevent(this->kq, &evSet, 1, NULL, 0, NULL) == -1) { std::cerr << "Error: could not add event" << std::endl; @@ -88,7 +97,7 @@ int WebServer::acceptNewEvent(int curfd) else { std::cerr << "Error accepting connection" << std::endl; - return fd; // Continue to the next event + return fd; } } fcntl(curfd, F_SETFL, O_NONBLOCK, FD_CLOEXEC); @@ -99,5 +108,4 @@ int WebServer::acceptNewEvent(int curfd) } return fd; } - #endif diff --git a/mandatory/src/WebservParser.cpp b/mandatory/src/WebservParser.cpp index ff18163..3a8100b 100644 --- a/mandatory/src/WebservParser.cpp +++ b/mandatory/src/WebservParser.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* WebservParser.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:50:32 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:11:42 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + # include "../inc/WebServer.hpp" std::string removeComments(std::string &str) @@ -6,7 +18,6 @@ std::string removeComments(std::string &str) std::string aux; std::istringstream fileContentStream(str); std::string serverContentConfig = ""; - while (std::getline(fileContentStream, line)) { line = line.substr(0, line.find_first_of("#")); @@ -45,10 +56,8 @@ static bool mismatchedBraces(std::string fileString) static bool endWithSemicolon(std::string &fileString) { std::string line; - fileString = removeComments(fileString); fileString = removeBlanksAndTabs(fileString); - std::istringstream fileStream(fileString); while (std::getline(fileStream, line)) { @@ -59,7 +68,7 @@ static bool endWithSemicolon(std::string &fileString) continue; else { - printLog("ERROR", "Missing semicolon " CHR_YELLOW ":" RESET " at the end: \"" YELLOW + line + RESET"\""); + printLog("ERROR", "Missing semicolon " CHR_YELLOW ";" RESET " at the end: \"" YELLOW + line + RESET"\""); return false; } } @@ -82,7 +91,6 @@ static bool hasDoublePoints(std::string &fileString) std::istringstream fileStream(fileString); while (std::getline(fileStream, line)) { - if ((line.length() == 0 || line == "{" || line == "}" || line == "};") || (!line.empty() && (line.find(":") != std::string::npos))) continue; else @@ -98,16 +106,12 @@ bool WebServer::checkSyntax() { if (!isServerBlock(this->configFileString)) return false; - if (!mismatchedBraces(this->configFileString)) return false; - if (!endWithSemicolon(this->configFileString)) return false; - if (!hasDoublePoints(this->configFileString)) return false; - return true; } @@ -151,7 +155,6 @@ void WebServer::processConfigFile() while (this->configFileString.find("server:{") != std::string::npos) { - configFileString.erase(std::remove(configFileString.begin(), configFileString.end(), '\n'), configFileString.end()); pos = this->configFileString.find("server:{", 8); if(pos == std::string::npos) @@ -175,11 +178,9 @@ bool WebServer::parseInfo() { std::cout << CHR_CYAN"-------------Checking Server [" << i + 1 << "]------------" RESET<< std::endl; this->servers[i]->checkVariables(); - // this->servers[i]->print(); // print all Server parameters for debug printLog("NOTICE", "OK! Server " + toString(i + 1)); std::cout << CHR_CYAN"--------------------------------------------" RESET<< std::endl; } - std::vector ports; for (size_t i = 0; i < this->servers.size(); i++) { diff --git a/mandatory/src/main.cpp b/mandatory/src/main.cpp index f03a3af..2f4c189 100644 --- a/mandatory/src/main.cpp +++ b/mandatory/src/main.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* main.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:51:34 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:21:02 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/WebServer.hpp" int main(int av, char **ac) @@ -11,7 +23,6 @@ int main(int av, char **ac) webServer.loadConfigFile(ac[1]); if (!webServer.checkSyntax()) return 1; - webServer.processConfigFile(); if (!webServer.parseInfo()) return 1; diff --git a/mandatory/src/utils.cpp b/mandatory/src/utils.cpp index e5e082c..cbefb01 100644 --- a/mandatory/src/utils.cpp +++ b/mandatory/src/utils.cpp @@ -1,3 +1,15 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* utils.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: eavedill +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/06/30 13:51:03 by eavedill #+# #+# */ +/* Updated: 2024/06/30 15:15:09 by eavedill ### ########.fr */ +/* */ +/* ************************************************************************** */ + #include "../inc/utils.hpp" template @@ -28,7 +40,6 @@ bool validIPAddress(std::string ip) size_t pos = 0; std::string token; int count = 0; - while ((pos = ip.find('.')) != std::string::npos) { token = ip.substr(0, pos); @@ -37,10 +48,8 @@ bool validIPAddress(std::string ip) ip.erase(0, pos + 1); count++; } - if (count != 4 || !isNumber(ip) || !isrange(std::atoi(ip.c_str()), 0, 255)) return false; - return count == 4; } @@ -75,7 +84,8 @@ int isFilePermissions(std::string path, int mode) return 1; } -size_t stringToSizeT(const std::string& str) { +size_t stringToSizeT(const std::string& str) +{ std::stringstream ss(str); size_t result = 0; ss >> result; @@ -86,14 +96,10 @@ size_t stringToSizeT(const std::string& str) { std::vector splitString(const std::string& str, char delimiter) { std::vector result; std::string token; - std::cout << "str: " << str << std::endl; std::istringstream tokenStream(str); - while (std::getline(tokenStream, token, delimiter)) { - // if (token != "") - result.push_back(token); + result.push_back(token); } - return result; } @@ -117,7 +123,8 @@ std::string removeBlanksAndTabs(const std::string& input) { return result; } -void replaceString(std::string& mainString, const std::string& searchString, const std::string& replaceString) { +void replaceString(std::string& mainString, const std::string& searchString, const std::string& replaceString) +{ size_t pos = 0; while ((pos = mainString.find(searchString, pos)) != std::string::npos) { mainString.replace(pos, searchString.length(), replaceString); @@ -125,7 +132,8 @@ void replaceString(std::string& mainString, const std::string& searchString, con } } -int count_chars(const std::string& str, char c) { +int count_chars(const std::string& str, char c) +{ int count = 0; for (size_t i = 0; i < str.size(); i++) { if (str[i] == c) { @@ -138,11 +146,9 @@ int count_chars(const std::string& str, char c) { std::string getLocalTime() { std::time_t currentTime = std::time(NULL); - std::tm* timeInfo = std::localtime(¤tTime); char buffer[20]; std::strftime(buffer, sizeof(buffer), "%Y/%m/%d %H:%M:%S", timeInfo); - return std::string(buffer); } @@ -161,10 +167,8 @@ void printLog(std::string type ,std::string message) static int hexStringToInt(const std::string& hexStr) { int value; std::stringstream ss; - ss << std::hex << hexStr; ss >> value; - return value; } @@ -191,10 +195,23 @@ std::string decodeURL(const std::string& url) return decoded; } -void replaceFirstString(std::string& mainString, const std::string& searchString, const std::string& replaceString) { +void replaceFirstString(std::string& mainString, const std::string& searchString, const std::string& replaceString) +{ size_t pos = 0; if ((pos = mainString.find(searchString, pos)) != std::string::npos) { mainString.replace(pos, searchString.length(), replaceString); pos += replaceString.length(); } } + +std::string getRandomHash(int lenght) +{ + std::string characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + + std::string hash; + int x; + std::srand(static_cast(std::time(0)) ^ reinterpret_cast(&x)); + for (int i = 0 ; i < lenght; i++) + hash += characters[rand() % characters.size()]; + return hash; +} \ No newline at end of file diff --git a/www/web3/index6.html b/www/web3/index6.html new file mode 100644 index 0000000..7fed569 --- /dev/null +++ b/www/web3/index6.html @@ -0,0 +1,101 @@ + + + + + + File Upload and Delete + + + +
+

Upload File

+
+ + +
+ +

Delete File

+
+ + + +
+
+ + + + diff --git a/www/web4/cgi/test.cgi b/www/web4/cgi/test.cgi index 29f5a98..b99ffab 100755 Binary files a/www/web4/cgi/test.cgi and b/www/web4/cgi/test.cgi differ diff --git a/www/web4/cgi/test.cpp b/www/web4/cgi/test.cpp index d0728f3..00b7abd 100644 --- a/www/web4/cgi/test.cpp +++ b/www/web4/cgi/test.cpp @@ -2,18 +2,7 @@ #include using namespace std; -const string ENV[24] = { - "COMSPEC", "DOCUMENT_ROOT", "GATEWAY_INTERFACE", - "HTTP_ACCEPT", "HTTP_ACCEPT_ENCODING", - "HTTP_ACCEPT_LANGUAGE", "HTTP_CONNECTION", - "HTTP_HOST", "HTTP_USER_AGENT", "PATH", - "QUERY_STRING", "REMOTE_ADDR", "REMOTE_PORT", - "REQUEST_METHOD", "REQUEST_URI", "SCRIPT_FILENAME", - "SCRIPT_NAME", "SERVER_ADDR", "SERVER_ADMIN", - "SERVER_NAME", "SERVER_PORT", "SERVER_PROTOCOL", - "SERVER_SIGNATURE", "SERVER_SOFTWARE"}; - -int main(int av, char **ac) +int main(int av, char **ac, char **envp) { (void)av; cout << "\n"; @@ -29,7 +18,13 @@ int main(int av, char **ac) { cout << "" << "Argumento de entrada N." << i << "= " << ac[i] << "\n"; } - + cout << "" << "Variables de entorno" << "\n"; + int i = 0; + while(envp[i] != NULL) + { + cout << "" << "N." << i << "= " << envp[i] << "\n"; + i++; + } cout << "<\n"; cout << "\n"; cout << "\n";