From 801b42cc3c535cd0fb482d2275186df62d2908c5 Mon Sep 17 00:00:00 2001 From: Valentin Rakush Date: Sat, 21 Dec 2019 16:04:25 +0000 Subject: [PATCH] Implement call to external script and return stdout in response --- lib/ProxySQL_RESTAPI_Server.cpp | 44 +++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/lib/ProxySQL_RESTAPI_Server.cpp b/lib/ProxySQL_RESTAPI_Server.cpp index 30b278074..70b638901 100644 --- a/lib/ProxySQL_RESTAPI_Server.cpp +++ b/lib/ProxySQL_RESTAPI_Server.cpp @@ -15,12 +15,45 @@ using namespace httpserver; class hello_world_resource : public http_resource { public: - const std::shared_ptr render_GET(const http_request&) { - return std::shared_ptr(new string_response("GET: Hello, World!")); + const std::shared_ptr render_GET(const http_request& req) { + return std::shared_ptr(new string_response("GET: Hello, World!\n")); } - const std::shared_ptr render(const http_request&) { - return std::shared_ptr(new string_response("OTHER: Hello, World!")); + const std::shared_ptr render_POST(const http_request& req) { + //TODO : validate json correctness in the req + + int pipefd[2]; + if (pipe(pipefd) == -1) { + return std::shared_ptr(new string_response("{\"error\":\"Cannot create pipe.\"}")); + } + + pid_t pid; + if ((pid=fork()) == -1) { + return std::shared_ptr(new string_response("{\"error\":\"Cannot fork.\"}")); + } + + char buf[1024]; + if (pid == 0) { + dup2(pipefd[1], STDOUT_FILENO); + close(pipefd[0]); + close(pipefd[1]); + char* args[] = {"a", (char*)req.get_content().data(), NULL}; + if (execve("/home/val/workspace/script.py", args, NULL) == -1) { + return std::shared_ptr(new string_response("{\"error\":\"Error calling execve().\"}")); + } + exit(EXIT_SUCCESS); + } + else { + close(pipefd[1]); + int nbytes = read(pipefd[0], buf, sizeof(buf) - 1); + if (nbytes == -1) { + return std::shared_ptr(new string_response("{\"error\":\"Error reading pipe.\"}")); + } + //TODO : validate json correctness in the buf + close(pipefd[0]); + wait(NULL); + } + return std::shared_ptr(new string_response(buf)); } }; @@ -34,13 +67,14 @@ ProxySQL_RESTAPI_Server::ProxySQL_RESTAPI_Server(int p) { // for now, this is COMPLETELY DISABLED // just adding a POC - return; +// return; //ws = NULL; port = p; ws = new webserver(create_webserver(p)); //hello_world_resource hwr; hr = new hello_world_resource(); + //ws->register_resource("/hello", &hwr); ws->register_resource("/hello", hr); if (pthread_create(&thread_id, NULL, restapi_server_thread, ws) !=0 ) {