From 63365a9067e3704c6b136c585a8593c5117ce0a8 Mon Sep 17 00:00:00 2001 From: hugogogo Date: Sun, 7 Aug 2022 22:33:39 +0200 Subject: [PATCH] cgi_script read and write on a string --- srcs/webserv/cgi_script.cpp | 47 +++++++++++++++++++++++++++++-------- 1 file changed, 37 insertions(+), 10 deletions(-) diff --git a/srcs/webserv/cgi_script.cpp b/srcs/webserv/cgi_script.cpp index 55df2d9..662094d 100644 --- a/srcs/webserv/cgi_script.cpp +++ b/srcs/webserv/cgi_script.cpp @@ -68,22 +68,49 @@ char** Webserv::_set_env(Client *client) void Webserv::_exec_script(Client *client, char **env) { - int save_stdout; - char * const * nll = NULL; + #define RD 0 + #define WR 1 + #define BUF_SIZE 10 - // save STDOUT - save_stdout = dup(STDOUT_FILENO); - // inside child process + char buf[BUF_SIZE]; + int fd_in[2]; + int fd_out[2]; + char * const * nll = NULL; + std::string response; + std::string body = client->get_rq_body(); + + pipe(fd_in); + pipe(fd_out); if (fork() == 0) - { - dup2(client->get_cl_fd(), STDOUT_FILENO); + { + close(fd_in[WR]); + close(fd_out[RD]); + dup2(fd_in[RD], STDIN_FILENO); + dup2(fd_out[WR], STDOUT_FILENO); execve(client->get_rq_script_path().c_str(), nll, env); + std::cerr << "execve crashed\n"; } - // inside parent process else + { + close(fd_in[RD]); + close(fd_out[WR]); + // write to stdin of child programm + write(fd_in[WR], body.c_str(), body.size()); + close(fd_in[WR]); waitpid(-1, NULL, 0); - // restore stdout - dup2(save_stdout, STDOUT_FILENO); + + // read stdout of child programm + memset(buf, '\0', BUF_SIZE); + while (read(fd_out[RD], buf, BUF_SIZE) > 0) + { + response += buf; + memset(buf, '\0', BUF_SIZE); + } + } + if (response.empty()) + response += "Status: 500\r\n\r\n"; + // TODO: see how this must be handled + client->response += response; } void Webserv::_construct_client(Client *client)