10 #include "httpdclient.h"
12 #include "vdrclient.h"
14 #define POSTBUFFERSIZE 512
16 std::shared_ptr<spd::logger> HTTPDClient::logger;
17 struct MHD_Daemon* HTTPDClient::httpdserver = NULL;
18 std::string HTTPDClient::docRoot;
19 std::string HTTPDClient::configDir;
21 bool HTTPDClient::StartServer(std::string _docRoot, int port, const char* _configDir)
24 configDir = std::string(_configDir);
26 logger = spd::get("jsonserver_spdlog");
28 httpdserver = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, port, NULL, NULL,
29 &HTTPDClient::handle_connection, NULL,
30 MHD_OPTION_NOTIFY_CONNECTION, &HTTPDClient::connection_notify, NULL,
31 MHD_OPTION_NOTIFY_COMPLETED, &HTTPDClient::request_completed, NULL,
32 MHD_OPTION_CONNECTION_TIMEOUT, 70,
34 if (httpdserver == NULL) { logger.reset(); return false; }
35 logger->info("HTTPDClient: Started");
39 void HTTPDClient::StopServer()
41 if (httpdserver) MHD_stop_daemon(httpdserver);
46 // Now for the libmicrohttpd callbacks
48 int HTTPDClient::uri_key_value(void *cls, enum MHD_ValueKind kind, const char* key, const char* value)
50 if (kind != MHD_GET_ARGUMENT_KIND) return MHD_NO;
51 HTTPDClient* httpdclient = (HTTPDClient*)cls;
52 httpdclient->addGetVar(key, value);
56 int HTTPDClient::iterate_post(void *clientIdentifier, enum MHD_ValueKind kind, const char *key,
57 const char *filename, const char* content_type,
58 const char *transfer_encoding, const char *data, uint64_t off, size_t size)
60 // logger->info("HTTPDClient: add post field: {} {} {}", key, data, size);
61 HTTPDClient* httpdclient = (HTTPDClient*)clientIdentifier;
62 httpdclient->addPostField(key, data, size);
63 return MHD_YES; //Return MHD_YES to continue iterating, MHD_NO to abort the iteration.
66 void HTTPDClient::request_completed(void *cls, struct MHD_Connection *mhd_connection,
67 void **unused, enum MHD_RequestTerminationCode toe)
69 const MHD_ConnectionInfo* mhdc = MHD_get_connection_info(mhd_connection, MHD_CONNECTION_INFO_SOCKET_CONTEXT);
70 HTTPDClient* httpdclient = (HTTPDClient*)mhdc->socket_context;
71 if (!httpdclient) return;
72 httpdclient->requestComplete();
75 void HTTPDClient::connection_notify(void *cls, struct MHD_Connection* mhd_connection,
76 void **socket_context, enum MHD_ConnectionNotificationCode toe)
78 if (toe == MHD_CONNECTION_NOTIFY_STARTED)
80 *socket_context = (void*)new HTTPDClient(mhd_connection, configDir);
82 else if (toe == MHD_CONNECTION_NOTIFY_CLOSED)
84 HTTPDClient* httpdclient = (HTTPDClient*)*socket_context;
85 if (!httpdclient) return;
87 *socket_context = NULL;
91 int HTTPDClient::handle_connection(void* cls, struct MHD_Connection* mhd_connection,
92 const char* url, const char* method,
93 const char* version, const char* upload_data,
94 size_t* upload_data_size, void** userData)
97 logger->debug("handle_connection called");
98 logger->debug("hc: cls {}", (void*)cls);
99 logger->debug("hc: mhd_connection {}", (void*)mhd_connection);
100 logger->debug("hc: url {}", (void*)url);
101 if (url) logger->debug("hc: url: {}", url);
102 logger->debug("hc: method {}", (void*)method);
103 if (url) logger->debug("hc: method: {}", method);
104 logger->debug("hc: version {}", (void*)version);
105 if (url) logger->debug("hc: version: {}", version);
106 logger->debug("hc: upload_data {}", (void*)upload_data);
107 logger->debug("hc: upload_data_size {}", *upload_data_size);
108 logger->debug("hc: userData {}", (void*)*userData);
111 const MHD_ConnectionInfo* mhdc = MHD_get_connection_info(mhd_connection, MHD_CONNECTION_INFO_SOCKET_CONTEXT);
113 HTTPDClient* httpdclient = (HTTPDClient*)mhdc->socket_context;
115 // Now we are going to use userData as a flag to say first run or not
117 if (!*userData) // new request
119 *userData = (void*)1;
120 httpdclient->setUrl(url);
122 if (!strcmp(method, "POST"))
124 MHD_get_connection_values(mhd_connection, MHD_GET_ARGUMENT_KIND, HTTPDClient::uri_key_value, (void*)httpdclient);
126 // The following returns NULL if there are no POST fields to come
127 httpdclient->postprocessor = MHD_create_post_processor(mhd_connection, POSTBUFFERSIZE,
128 HTTPDClient::iterate_post, (void*)httpdclient);
130 else if (!strcmp(method, "GET"))
132 // OK, nothing else to do here
142 // Not first go at this request
144 if (!strcmp(method, "GET"))
146 return httpdclient->processGET();
148 else if (!strcmp(method, "POST"))
150 // HC will be called at least three times. Once above to create the HTTPDClient object (above).
151 // Here the middle calls will be called with upload_data_size > 0
152 // The last call is with upload_data_size == 0 and signals the end, a response must be queued
154 if (*upload_data_size != 0) // There is more to process, and signal run again
156 MHD_post_process(httpdclient->postprocessor, upload_data, *upload_data_size);
157 *upload_data_size = 0;
162 // printf("hc: zero post provided, end of upload\n");
163 return httpdclient->processPOST();
168 return httpdclient->sendStockResponse(405);
172 // End of static callbacks, now for the client object itself
174 HTTPDClient::HTTPDClient(struct MHD_Connection* _mhd_connection, const std::string& _configDir)
175 : postprocessor(NULL), url(NULL), mhd_connection(_mhd_connection), vdrclient(_configDir)
177 // printf("HTTPDClient created %p\n", this);
180 HTTPDClient::~HTTPDClient()
182 // printf("%p HTTPDClient destructor\n", this);
186 void HTTPDClient::requestComplete()
188 // printf("%p HTTPDClient request complete\n", this);
192 MHD_destroy_post_processor(postprocessor);
193 postprocessor = NULL;
197 void HTTPDClient::setUrl(const char* _url)
199 int size __attribute__((unused)) = asprintf(&url, "%s", _url);
202 void HTTPDClient::addGetVar(const char* key, const char* value)
204 if (strlen(key) > 50) return;
205 if (value && (strlen(value) > 1000)) return;
207 getVars[std::string(key)] = std::string(value);
209 for(auto gv : getVars)
211 printf("%s %s\n", gv.first.c_str(), gv.second.c_str());
216 void HTTPDClient::addPostField(const char* key, const char* value, int valueLength)
218 if (strlen(key) > 50) return;
219 if (strlen(value) > 1000) return;
221 postFields[std::string(key)] = std::string(value, valueLength);
224 for(auto pf : postFields)
226 printf("%s %s\n", pf.first.c_str(), pf.second.c_str());
231 int HTTPDClient::processGET()
233 const char* defaultfilename = "index.html";
235 if (url == NULL) return MHD_NO;
236 if (strstr(url, "..")) return MHD_NO; // MHD deals with these already and limits it. If it occurs here, error.
238 int size __attribute__((unused));
240 int slen = strlen(url);
242 if (url[slen-1] == '/')
243 size = asprintf(&fullpath, "%s%s%s", docRoot.c_str(), url, defaultfilename);
245 size = asprintf(&fullpath, "%s%s", docRoot.c_str(), url);
247 //printf("FILENAME: '%s'\n", fullpath);
250 if ( (stat(fullpath, &sbuf) == -1) // failed to stat
251 || ((sbuf.st_mode & S_IFMT) != S_IFREG) ) // must be regular file
254 return sendStockResponse(404);
257 int fd = open(fullpath, O_RDONLY);
260 if (fd == -1) return MHD_NO;
262 struct MHD_Response* response = MHD_create_response_from_fd(sbuf.st_size, fd);
263 int ret = MHD_queue_response(mhd_connection, MHD_HTTP_OK, response);
267 MHD_destroy_response(response);
272 int HTTPDClient::processPOST()
274 // printf("Process POST:\n");
275 //printf("REQ: %s\n", getVars["req"].c_str());
277 if (strcmp(url, "/jsonserver")) return sendStockResponse(404);
278 if (getVars["req"].empty()) return sendStockResponse(400);
280 std::string returnData;
282 bool success = vdrclient.process(getVars["req"], postFields, returnData);
283 if (!success) return sendStockResponse(500);
285 struct MHD_Response* response = MHD_create_response_from_buffer(strlen(returnData.c_str()), (void *)returnData.c_str(), MHD_RESPMEM_MUST_COPY);
286 MHD_add_response_header(response, "Content-Type", "application/json");
287 int ret = MHD_queue_response(mhd_connection, MHD_HTTP_OK, response);
291 MHD_destroy_response(response);
295 int HTTPDClient::sendStockResponse(int code)
297 const char *page400 = "<html><body>Bad request</body></html>\n";
298 const char *page404 = "<html><body>File not found</body></html>\n";
299 const char *page405 = "<html><body>Method not allowed</body></html>\n";
300 const char *page500 = "<html><body>Internal server error</body></html>\n";
302 if (code == 400) page = page400;
303 else if (code == 404) page = page404;
304 else if (code == 405) page = page405;
305 else if (code == 500) page = page500;
308 struct MHD_Response* response = MHD_create_response_from_buffer(strlen(page), (void *)page, MHD_RESPMEM_PERSISTENT);
309 int ret = MHD_queue_response(mhd_connection, code, response);
313 MHD_destroy_response(response);