adding first tests with cgi

This commit is contained in:
hugogogo
2022-07-27 20:47:13 +02:00
parent d4a14798f4
commit 8477669e6f
9 changed files with 146 additions and 14 deletions

View File

@@ -177,6 +177,73 @@ void Webserv::_read_request(int fd)
void Webserv::_send_response(int fd)
{
// TMP test cgi
// find POST in _buf
std::string tmpstr = _buf;
std::size_t found;
found = tmpstr.find("POST");
// if "POST" found, execve a cgi
if (found != std::string::npos)
{
int save_stdout;
char** env = new char*[4];
char * const * nll = NULL;
// set env
env[0] = strdup("PATH_INFO=/no");
env[1] = strdup("REQUEST_METHOD=POST");
env[2] = strdup("SERVER_PROTOCOL=HTTP/1.1");
env[3] = NULL;
// save STDOUT
save_stdout = dup(STDOUT_FILENO);
// inside chil process
if (fork() == 0)
{
dup2(fd, STDOUT_FILENO);
execve("./srcs/cgi-bin/cgi_cpp.cgi", nll, env);
}
// inside parent process
else
waitpid(-1, NULL, 0);
// restore stdout
dup2(save_stdout, STDOUT_FILENO);
// don't send the rest
::close(fd);
return;
}
else
found = tmpstr.find("index.html");
// if "index.html" found, send the page
if (found != std::string::npos)
{
int index_fd;
std::string to_send;
std::string end_header = "\r\n\r\n";
std::string body;
std::stringstream strs;
char buffer[1];
to_send = "HTTP/1.1 200 OK\nContent-Type: text/html; charset=UTF-8\nContent-Length: ";
index_fd = open("./index.html", O_RDONLY);
for (int ret = 1; ret > 0;)
{
ret = read(index_fd, buffer, 1);
body += buffer;
}
strs << body.size();
to_send += strs.str();
to_send += end_header;
to_send += body;
::send(fd, to_send.c_str(), to_send.size(), 0);
// don't send the rest
::close(fd);
return;
}
// TMP end test cgi
std::cout << "send()\n";
if (::send(fd, _buf, _read_ret, 0) == -1)
std::perror("err send(): ");

41
srcs/cgi-bin/cgi.cpp Normal file
View File

@@ -0,0 +1,41 @@
# include <iostream>
# include <string>
# include <sstream>
int main (int ac, char **av) {
std::string to_send;
std::string header;
std::string end_header = "\r\n\r\n";
std::string response;
std::stringstream strs;
header = "HTTP/1.1 200 OK\n";
header += "Content-Type: text/html; charset=UTF-8\n";
header += "Content-Length: ";
response = "<!DOCTYPE html>\n";
response += "<html>\n";
response += "<head>\n";
response += "<title>CGI</title>\n";
response += "</head>\n";
response += "<body>\n";
response += "<h2>CGI request :</h2>\n";
for (int i = 1; i < ac; i++)
{
response += "<p>";
response += av[i];
response += "</p>\n";
}
response += "</body>\n";
response += "</html>\n";
strs << response.size();
header += strs.str();
header += end_header;
to_send = header;
to_send += response;
std::cout << to_send;
return 0;
}

BIN
srcs/cgi-bin/cgi_cpp.cgi Executable file

Binary file not shown.

7
srcs/cgi-bin/php-cgi Executable file
View File

@@ -0,0 +1,7 @@
#! /usr/bin/php
# <?php phpinfo(); ?>
<?php
echo getenv('REQUEST_METHOD');
echo $_POST['REQUEST_METHOD'];
?>