From e3aa12a8cfa137f65c5ca06489e1f58f0608db54 Mon Sep 17 00:00:00 2001 From: cflip Date: Sat, 17 Sep 2022 11:47:23 -0600 Subject: Make a nice wrapper class for running CGI scripts --- src/main.cpp | 34 ++++------------------------------ 1 file changed, 4 insertions(+), 30 deletions(-) (limited to 'src/main.cpp') diff --git a/src/main.cpp b/src/main.cpp index 4eb90bd..410cb19 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4,6 +4,7 @@ #include #include +#include "CGIScript.h" #include "ClientConnection.h" #include "HttpRequest.h" #include "HttpResponse.h" @@ -54,43 +55,16 @@ static HttpResponse serve_from_cgi(const std::string& executable_path, HttpReque HttpResponse response; response.add_header("Server", "cfws"); - setenv("CONTENT_LENGTH", "0", true); - setenv("REQUEST_URI", request.uri().c_str(), true); - setenv("SCRIPT_NAME", executable_path.c_str(), true); - setenv("SCRIPT_FILENAME", executable_path.c_str(), true); - setenv("REQUEST_METHOD", "GET", true); - setenv("SERVER_PROTOCOL", "HTTP/1.1", true); - setenv("SERVER_SOFTWARE", "cfws/1.0-dev", true); - - std::stringstream sstream; - - FILE* fp = popen(executable_path.c_str(), "r"); - if (!fp) { - perror("cfws: popen"); + CGIScript script(executable_path, request); + if (!script.is_open()) { response.set_status_code(HttpStatusCode::InternalServerError); response.add_header("Content-Type", "text/plain"); response.set_content("Failed to open CGI executable!"); return response; } - char ch; - while ((ch = fgetc(fp)) != EOF) - sstream << ch; - - pclose(fp); - - unsetenv("CONTENT_LENGTH"); - unsetenv("REQUEST_URI"); - unsetenv("SCRIPT_NAME"); - unsetenv("SCRIPT_FILENAME"); - unsetenv("REQUEST_METHOD"); - unsetenv("SERVER_PROTOCOL"); - unsetenv("SERVER_SOFTWARE"); - - // TODO: We should be able to construct a repsonse from an entire string - // instead of always needing to individually set headers and content. response.set_status_code(HttpStatusCode::OK); - response.add_headers_and_content(sstream.str()); + response.add_headers_and_content(script.read_output()); return response; } -- cgit v1.2.3