Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dtolmaco/add debug log #388

Merged
merged 18 commits into from
May 24, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions conf/single.conf
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
server {
listen 127.0.0.1:8080;
listen 127.0.0.1:8080 8081 8082;
listen 127.0.0.2:8080;
server_name www.saladbook;
root /var/www/html;
root /var/;
}
5 changes: 4 additions & 1 deletion include/webserv.hpp
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this change here?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you mean? I just added defines for timeouts

Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@

#define SEND_BUFFER_SIZE 1024 * 100 // 100 KB
#define BUFFER_SIZE 1025
#define CGI_TIMEOUT_MS 10000
#define CGI_TIMEOUT_S 10 // 10 seconds
#define CGI_POLL_TIMEOUT_MS 500 // 0.5 seconds
#define CLIENT_POLL_TIMEOUT_MS 10000 // 10 seconds
#define CLIENT_TIMEOUT_S 7 // 7 seconds
#define CONFIG_FILE_DEFAULT_PATH "./conf/webserv_default.conf"

#define RED "\033[1;31m"
Expand Down
34 changes: 17 additions & 17 deletions src/CGIHandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ CGIHandler &CGIHandler::operator=(const CGIHandler &other)

void CGIHandler::handleRequest(HTTPRequest &request, HTTPResponse &response)
{

std::cout << RED << "Entering CGIHandler::handleRequest" << RESET << std::endl;
Debug::log("CGIHandler::handleRequest", Debug::CGI);
MetaVariables env;
env.HTTPRequestToMetaVars(request, env);
if (!executeCGI(env, response))
Expand All @@ -46,18 +45,19 @@ void CGIHandler::handleRequest(HTTPRequest &request, HTTPResponse &response)
// TODO: it should be hardcoded
response.setBody("500 Internal Server Error");
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is this TODO? Why we need to set the body, if we already set the statusCode, which is associated with a certain message? We can probably imporove setStatusCode or create a Wrapper for both of them.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dunno. It was added a long time ago. I guess we can remove it now

Debug::log("Connection PID" + toString(_connection.getCGIPid()), Debug::CGI);
return;
}

std::vector<std::string> CGIHandler::createArgvForExecve(const MetaVariables &env)
{
std::vector<std::string> argv;
std::string scriptName = env.getVar("SCRIPT_NAME");
std::cout << "createArgvForExecve: scriptName: " << scriptName << std::endl;
Debug::log("createArgvForExecve: scriptName: " + scriptName, Debug::CGI);
std::string pathTranslated = env.getVar("PATH_TRANSLATED");
std::cout << "createArgvForExecve: pathTranslated: " << pathTranslated << std::endl;
Debug::log("createArgvForExecve: pathTranslated: " + pathTranslated, Debug::CGI);
std::string scriptPath = pathTranslated;
std::cout << "createArgvForExecve: scriptPath: " << scriptPath << std::endl;
Debug::log("createArgvForExecve: scriptPath: " + scriptPath, Debug::CGI);

if (env.getVar("X_INTERPRETER_PATH") != "")
{
Expand Down Expand Up @@ -99,12 +99,12 @@ std::vector<char *> CGIHandler::convertToCStringArray(const std::vector<std::str
void handleTimeout(int sig)
{
(void)sig;
std::cout << "CGIHandler: Timeout" << std::endl;
Debug::log("CGIHandler: Timeout", Debug::CGI);
}

bool CGIHandler::executeCGI(const MetaVariables &env, HTTPResponse &response)
{
std::cout << RED << "Entering CGIHandler::executeCGI" << RESET << std::endl;
Debug::log("CGIHandler::executeCGI", Debug::CGI);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my branch https there is a new version of Debug::log taking also colors. Maybe you can cherry pick the commit(s) from that branch without the SSL stuff, like git cherry-pick -n <HASH> the -n flag is to cherry pick without committing.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lets do it in your PR, when we gonna merge this one

std::string cgiOutput;
std::vector<std::string> argv = createArgvForExecve(env);
std::vector<std::string> envp = env.getForExecve();
Expand Down Expand Up @@ -147,7 +147,7 @@ bool CGIHandler::executeCGI(const MetaVariables &env, HTTPResponse &response)

if (access(argvPointers[0], X_OK) == -1)
{
perror("access");
Debug::log("CGIHandler: access failed", Debug::CGI);
return false;
_exit(EXIT_FAILURE);
// TODO: @leo I don't think we should exit here. We don't want to kill the whole server cause of a CGI
Expand All @@ -157,7 +157,7 @@ bool CGIHandler::executeCGI(const MetaVariables &env, HTTPResponse &response)
// execve(argvPointers[0], argvPointers.data(), envpPointers.data());
if (execve(argvPointers[0], argvPointers.data(), envpPointers.data()) == -1)
{
perror("execve");
Debug::log("CGIHandler: execve failed", Debug::CGI);
return false;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

perror gives extra information and this way we are losing them. Please provide a Debug::log version that integrates the perror functionalities.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright

// TODO: @leo We should check if execve failed and return an error response and not exti
_exit(EXIT_FAILURE);
Expand All @@ -167,24 +167,24 @@ bool CGIHandler::executeCGI(const MetaVariables &env, HTTPResponse &response)
response.setIsCGI(true);
response.setCGIpipeFD(pipeFD);

std::cout << "PIPE SAVED: "<< *response.getCGIpipeFD() << std::endl;
Debug::log("PIPE SAVED: " + toString(*response.getCGIpipeFD()), Debug::CGI);

close(pipeFD[1]);
EventData data = {1, pid, pipeFD[0], pipeFD[1]}; // Assuming 1 is the event type for CGI started

_eventManager.emit(data); // Emit event indicating a CGI process has started

_connection.addCGI(pid);
std::cout << GREEN << _connection.getCGIPid() << RESET << std::endl;
Debug::log("CGIHandler: CGI PID: " + toString(pid), Debug::CGI);

// clang-format off
std::vector<std::pair<int, int> > pipes = _eventManager.getPipeFDs();
for (std::vector<std::pair<int, int> >::const_iterator it = pipes.begin(); it != pipes.end(); ++it)
{
std::cout << GREEN << "CGIHandler: pipeFDs: " << (*it).first << RESET << std::endl;
}
// std::vector<std::pair<int, int> > pipes = _eventManager.getPipeFDs();
// for (std::vector<std::pair<int, int> >::const_iterator it = pipes.begin(); it != pipes.end(); ++it)
// {
// std::cout << GREEN << "CGIHandler: pipeFDs: " << (*it).first << RESET << std::endl;
// }
// clang-format on
std::cout << RED << "Exiting CGIHandler::executeCGI with true" << RESET << std::endl;
Debug::log("CGIHandler: Waiting for CGI to finish", Debug::CGI);
return true;
}

Expand Down
34 changes: 12 additions & 22 deletions src/Connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,13 @@ Connection &Connection::operator=(const Connection &other)
_cgiOutputBuffer = other._cgiOutputBuffer;
_startTime = other._startTime;
}
std::cout << "Connection object assigned" << std::endl;
Debug::log("Connection object assigned", Debug::OCF);
return *this;
}

Connection::~Connection()
{
// std::cout << "Connection object destroyed" << std::endl;
Debug::log("Connection object destroyed", Debug::OCF);
}

// GETTERS AND SETTERS
Expand Down Expand Up @@ -352,18 +352,14 @@ void Connection::setCGIExitStatus(int status)

bool Connection::readHeaders(Parser &parser)
{
// std::cout << "\nEntering readHeaders" << std::endl;
const int bufferSize = BUFFER_SIZE;
char buffer[bufferSize] = {0};
std::cout << "buffers size: " << sizeof(buffer) << std::endl;
Debug::log("buffer size: " + toString(sizeof(buffer)), Debug::SERVER);
ssize_t bytesRead = recv(_pollFd.fd, buffer, bufferSize, 0);
std::cout << "bytesRead: " << bytesRead << std::endl;
Debug::log("bytesRead: " + toString(bytesRead), Debug::SERVER);
if (bytesRead > 0)
{
parser.setBuffer(parser.getBuffer() + std::string(buffer, bytesRead));
// std::cout << "The buffer is: " << parser.getBuffer() << std::endl;

// std::cout << "Exiting readHeaders" << std::endl;
return true;
}
else if (bytesRead < 0)
Expand All @@ -373,15 +369,14 @@ bool Connection::readHeaders(Parser &parser)
}
else if (bytesRead == 0)
{
// TODO: think about it
std::cout << "Connection closed before headers being completely sent" << std::endl;
Debug::log("Connection closed before headers being completely sent", Debug::SERVER);
return false;
// std::cout << "bytes_read == 0" << std::endl;
// return true;
}
else
{
std::cout << "Exiting readHeaders. This will never happen here!" << std::endl;
Debug::log("Exiting readHeaders. This will never happen here!", Debug::SERVER);
return true;
}
}
Expand Down Expand Up @@ -453,7 +448,7 @@ bool Connection::readChunkSize(std::string &line)
}
else
{
std::cout << "Connection closed" << std::endl;
Debug::log("Connection closed while reading chunk size", Debug::SERVER);
return false;
}
}
Expand Down Expand Up @@ -500,24 +495,20 @@ bool Connection::readChunk(size_t chunkSize, std::string &chunkData, HTTPRespons

bool Connection::readBody(Parser &parser, HTTPRequest &req, HTTPResponse &res)
{
std::cout << "\nEntering readBody" << std::endl;
size_t contentLength = req.getContentLength();

char buffer[BUFFER_SIZE];
// We could also use _bodyTotalBytesRead from the parser
size_t bytesRead = parser.getBuffer().size();
std::cout << "contentLength: " << contentLength << std::endl;
std::cout << "bytesRead: " << bytesRead << std::endl;
Debug::log("contentLength: " + toString(contentLength), Debug::SERVER);
Debug::log("bytesRead: " + toString(bytesRead), Debug::SERVER);
if (bytesRead < contentLength)
{
ssize_t read = recv(_pollFd.fd, buffer, BUFFER_SIZE, 0);
if (read > 0)
{
std::cout << "read > 0" << std::endl;
// _body.append(buffer, read);j
parser.setBuffer(parser.getBuffer() + std::string(buffer, read));
std::cout << "bytesRead: " << parser.getBuffer().size() << std::endl;
// std::cout << "The 'body; is: " << parser.getBuffer() << std::endl;
Debug::log("bytesRead: " + toString(parser.getBuffer().size()), Debug::SERVER);
bytesRead += read;
if (bytesRead == contentLength)
{
Expand All @@ -533,14 +524,13 @@ bool Connection::readBody(Parser &parser, HTTPRequest &req, HTTPResponse &res)
}
else
{
std::cout << "read == 0" << std::endl;
Debug::log("read == 0", Debug::SERVER);
res.setStatusCode(499, "Connection closed by the client"); // Client Closed Request
return false;
}
}
else
parser.setBodyComplete(true);
std::cout << "Exiting readBody" << std::endl;
return true;
}

Expand All @@ -549,7 +539,7 @@ void Connection::addCGI(pid_t pid)
{
_hasCGI = true;
_CGIPid = pid;
std::cout << "CGI process added with pid: " << _CGIPid << std::endl;
Debug::log("CGI process added with pid: " + toString(_CGIPid), Debug::CGI);
_CGIStartTime = time(NULL);
}

Expand Down
2 changes: 1 addition & 1 deletion src/HTTPRequest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ void HTTPRequest::replaceHeader(const std::string &key, const std::string &value
std::string lowerKey = key;
for (size_t i = 0; i < lowerKey.size(); ++i)
lowerKey[i] = std::tolower(static_cast<unsigned char>(lowerKey[i]));
std::cout << "Replacing header: " << key << " with value: " << lowerKey << std::endl;
Debug::log("Replacing header: " + key + " with value: " + lowerKey, Debug::PARSER);
std::multimap<std::string, std::string>::iterator it = _headers.find(lowerKey);
if (it != _headers.end())
_headers.erase(it);
Expand Down
24 changes: 11 additions & 13 deletions src/HTTPResponse.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,14 @@ void HTTPResponse::setErrorResponse(int statusCode)
{
std::string statusMessage = getStatusMessage(statusCode);
std::string code = toString(statusCode);
std::cout << "\033[31m"
<< "Error " << statusCode << " in request"
<< "\033[0m" << std::endl;
Debug::log("statusCode: " + code + " statusMessage: " + statusMessage, Debug::NORMAL);
std::string body = "<html><head><title>Error</title></head>"
"<body><h1>Error: " +
code + " " + "</h1><p>" + statusMessage + "</p></body></html>";

// print purple to identify a 0 status code
std::cout << PURPLE << "setErrorResponse: statusCode: " << statusCode << " statusMessage: " << statusMessage
<< " body: " << body << RESET << std::endl;
Debug::log("setErrorResponse: statusCode: " + code + " statusMessage: " + statusMessage +
" body: " + body,
Debug::NORMAL);
setStatusCode(statusCode, "");
setHeader("Content-Length", toString(body.length()));
setHeader("Content-Type", "text/html");
Expand All @@ -43,7 +41,7 @@ std::string HTTPResponse::objToString() const
std::stringstream responseStream;
if (_statusCode == 0)
{
std::cerr << "\033[31mWarning: Sending a response with status code 0\033[0m" << std::endl;
Debug::log("Sending a response with status code 0", Debug::NORMAL);
}
responseStream << "HTTP/1.1 " << _statusCode << " " << getStatusMessage(_statusCode) << "\r\n";
for (size_t i = 0; i < _headers.size(); ++i)
Expand Down Expand Up @@ -82,12 +80,13 @@ int HTTPResponse::getStatusCode() const
void HTTPResponse::setStatusCode(int statusCode, const std::string &message)
{
if (!message.empty())
std::cerr << message << std::endl;
Debug::log(message, Debug::NORMAL);
if (_statusCode != 0)
{
std::cerr << "\033[31mWarning: Overwriting existing status code (" << _statusCode << ") and message ("
<< _statusMessage << ") with new code (" << statusCode << ") and message ("
<< getStatusMessage(statusCode) << ").\033[0m" << std::endl;
Debug::log("Warning: Overwriting existing status code (" + toString(_statusCode) + ") and message (" +
_statusMessage + ") with new code (" + toString(statusCode) + ") and message (" +
getStatusMessage(statusCode) + ").",
Debug::NORMAL);
}

_statusCode = statusCode;
Expand Down Expand Up @@ -156,7 +155,7 @@ void HTTPResponse::CGIStringToResponse(const std::string &cgiOutput)
std::string headersPart = cgiOutput.substr(0, headerEndPos);
std::string bodyPart = cgiOutput.substr(headerEndPos);

std::cout << "------------------CGIStringToResponse-------------------" << std::endl;
Debug::log("------------------CGIStringToResponse-------------------", Debug::CGI);

std::istringstream headerStream(headersPart);
std::string headerLine;
Expand Down Expand Up @@ -328,7 +327,6 @@ const std::string &HTTPResponse::getStatusMessage() const

std::ostream &operator<<(std::ostream &out, const HTTPResponse &response)
{
std::cout << "HTTPResponse operator<< called" << std::endl;
// Output the status
out << "\033[35m";
out << "Status Code: " << response.getStatusCode() << "\n";
Expand Down
2 changes: 1 addition & 1 deletion src/Listen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Listen::Listen(std::string str)
std::cerr << "Throwing exception" << std::endl;
throw("Invalid ip or port");
}
std::cout << "Listen object created. IP: " << _ip << ", Port: " << _port << std::endl;
Debug::log("Listen object created. IP: " + _ip + ", Port: " + toString(_port), Debug::OCF);
}

Listen::Listen(const Listen &obj)
Expand Down
7 changes: 4 additions & 3 deletions src/MetaVariables.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,11 @@ void MetaVariables::HTTPRequestToMetaVars(const HTTPRequest &request, MetaVariab
std::string queryString = formatQueryString(request.getQueryString());
env.setVar("QUERY_STRING", queryString);

std::cout << "MetaVariables::HTTPRequestToMetaVars: request.getRequestTarget(): " << request.getRequestTarget()
<< std::endl;
Debug::log("MetaVariables::HTTPRequestToMetaVars: request.getRequestTarget(): " + request.getRequestTarget(),
Debug::CGI);

std::pair<std::string, std::string> pathComponents = separatePathAndInfo(request.getRequestTarget());
std::cout << "MetaVariables::HTTPRequestToMetaVars: pathComponents.first: " << pathComponents.first << std::endl;
Debug::log("MetaVariables::HTTPRequestToMetaVars: pathComponents.second: " + pathComponents.second, Debug::CGI);

std::string root = request.getRoot();
std::string host = request.getSingleHeader("host").second;
Expand Down
7 changes: 1 addition & 6 deletions src/Parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,15 @@ Parser::~Parser()

bool Parser::preParseHeaders(HTTPResponse &res)
{
// We read the buffer with readHeaders if headersComplete is not true and we write the buffer in the _headersBuffer
std::size_t headersEnd = _buffer.find("\r\n\r\n");
if (headersEnd != std::string::npos)
{
_headersBuffer = _buffer.substr(0, headersEnd + 4);
_headersComplete = true;
_buffer = _buffer.substr(headersEnd + 4);
// std::cout << _buffer << std::endl;
// std::cout << "\033[31m"
// << "_buffer size " << _buffer.size() << "\033[0m" << std::endl;
return (true);
}
std::cout << "headers are not complete" << std::endl;
Debug::log("headers are not complete", Debug::PARSER);
if (_buffer.length() > CLIENT_MAX_HEADERS_SIZE)
return (res.setStatusCode(431, "Headers too large"), false);
return true;
Expand Down Expand Up @@ -309,7 +305,6 @@ void Parser::saveCokies(HTTPRequest &req)
i++;
value = cookie.substr(start, i - start);
req.setCookies(key, value);
std::cout << cookie.substr(i) << std::endl;
if (cookie[i] == ';')
start = ++i;
}
Expand Down
Loading
Loading