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 if (size == 0) return MHD_NO;
62 HTTPDClient* httpdclient = (HTTPDClient*)clientIdentifier;
63 httpdclient->addPostField(key, data, size);
66 //Return MHD_YES to continue iterating, MHD_NO to abort the iteration.
69 void HTTPDClient::request_completed(void *cls, struct MHD_Connection *mhd_connection,
70 void **unused, enum MHD_RequestTerminationCode toe)
72 const MHD_ConnectionInfo* mhdc = MHD_get_connection_info(mhd_connection, MHD_CONNECTION_INFO_SOCKET_CONTEXT);
73 HTTPDClient* httpdclient = (HTTPDClient*)mhdc->socket_context;
74 if (!httpdclient) return;
75 httpdclient->requestComplete();
78 void HTTPDClient::connection_notify(void *cls, struct MHD_Connection* mhd_connection,
79 void **socket_context, enum MHD_ConnectionNotificationCode toe)
81 if (toe == MHD_CONNECTION_NOTIFY_STARTED)
83 *socket_context = (void*)new HTTPDClient(mhd_connection, configDir);
85 else if (toe == MHD_CONNECTION_NOTIFY_CLOSED)
87 HTTPDClient* httpdclient = (HTTPDClient*)*socket_context;
88 if (!httpdclient) return;
90 *socket_context = NULL;
94 int HTTPDClient::handle_connection(void* cls, struct MHD_Connection* mhd_connection,
95 const char* url, const char* method,
96 const char* version, const char* upload_data,
97 size_t* upload_data_size, void** userData)
100 printf("handle_connection called\n");
101 printf("hc: cls %p\n", cls);
102 printf("hc: mhd_connection %p\n", mhd_connection);
103 printf("hc: url %p\n", url);
104 if (url) printf("hc: url: %s\n", url);
105 printf("hc: method %p\n", method);
106 if (url) printf("hc: method: %s\n", method);
107 printf("hc: version %p\n", version);
108 if (url) printf("hc: version: %s\n", version);
109 printf("hc: upload_data %p\n", upload_data);
110 printf("hc: upload_data_size %lu\n", *upload_data_size);
111 printf("hc: userData %p\n", *userData);
114 const MHD_ConnectionInfo* mhdc = MHD_get_connection_info(mhd_connection, MHD_CONNECTION_INFO_SOCKET_CONTEXT);
116 HTTPDClient* httpdclient = (HTTPDClient*)mhdc->socket_context;
118 // Now we are going to use userData as a flag to say first run or not
120 if (!*userData) // new request
122 *userData = (void*)1;
123 httpdclient->setUrl(url);
125 if (!strcmp(method, "POST"))
127 MHD_get_connection_values(mhd_connection, MHD_GET_ARGUMENT_KIND, HTTPDClient::uri_key_value, (void*)httpdclient);
129 // The following returns NULL if there are no POST fields to come
130 httpdclient->postprocessor = MHD_create_post_processor(mhd_connection, POSTBUFFERSIZE,
131 HTTPDClient::iterate_post, (void*)httpdclient);
133 else if (!strcmp(method, "GET"))
135 // OK, nothing else to do here
145 // Not first go at this request
147 if (!strcmp(method, "GET"))
149 return httpdclient->processGET();
151 else if (!strcmp(method, "POST"))
153 // HC will be called at least three times. Once above to create the HTTPDClient object (above).
154 // Here the middle calls will be called with upload_data_size > 0
155 // The last call is with upload_data_size == 0 and signals the end, a response must be queued
157 if (*upload_data_size != 0) // There is more to process, and signal run again
159 MHD_post_process(httpdclient->postprocessor, upload_data, *upload_data_size);
160 *upload_data_size = 0;
165 // printf("hc: zero post provided, end of upload\n");
166 return httpdclient->processPOST();
171 return httpdclient->sendStockResponse(405);
175 // End of static callbacks, now for the client object itself
177 HTTPDClient::HTTPDClient(struct MHD_Connection* _mhd_connection, const std::string& _configDir)
178 : postprocessor(NULL), url(NULL), mhd_connection(_mhd_connection), vdrclient(_configDir)
180 // printf("HTTPDClient created %p\n", this);
183 HTTPDClient::~HTTPDClient()
185 // printf("%p HTTPDClient destructor\n", this);
189 void HTTPDClient::requestComplete()
191 // printf("%p HTTPDClient request complete\n", this);
195 MHD_destroy_post_processor(postprocessor);
196 postprocessor = NULL;
200 void HTTPDClient::setUrl(const char* _url)
202 int size __attribute__((unused)) = asprintf(&url, "%s", _url);
205 void HTTPDClient::addGetVar(const char* key, const char* value)
207 if (strlen(key) > 50) return;
208 if (value && (strlen(value) > 1000)) return;
210 getVars[std::string(key)] = std::string(value);
212 for(auto gv : getVars)
214 printf("%s %s\n", gv.first.c_str(), gv.second.c_str());
219 void HTTPDClient::addPostField(const char* key, const char* value, int valueLength)
221 if (strlen(key) > 50) return;
222 if (strlen(value) > 1000) return;
224 postFields[std::string(key)] = std::string(value, valueLength);
227 for(auto pf : postFields)
229 printf("%s %s\n", pf.first.c_str(), pf.second.c_str());
234 int HTTPDClient::processGET()
236 const char* defaultfilename = "index.html";
238 if (url == NULL) return MHD_NO;
239 if (strstr(url, "..")) return MHD_NO; // MHD deals with these already and limits it. If it occurs here, error.
241 int size __attribute__((unused));
243 int slen = strlen(url);
245 if (url[slen-1] == '/')
246 size = asprintf(&fullpath, "%s%s%s", docRoot.c_str(), url, defaultfilename);
248 size = asprintf(&fullpath, "%s%s", docRoot.c_str(), url);
250 //printf("FILENAME: '%s'\n", fullpath);
253 if ( (stat(fullpath, &sbuf) == -1) // failed to stat
254 || ((sbuf.st_mode & S_IFMT) != S_IFREG) ) // must be regular file
257 return sendStockResponse(404);
260 int fd = open(fullpath, O_RDONLY);
263 if (fd == -1) return MHD_NO;
265 struct MHD_Response* response = MHD_create_response_from_fd(sbuf.st_size, fd);
266 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);
288 MHD_destroy_response(response);
292 int HTTPDClient::sendStockResponse(int code)
294 const char *page400 = "<html><body>Bad request</body></html>\n";
295 const char *page404 = "<html><body>File not found</body></html>\n";
296 const char *page405 = "<html><body>Method not allowed</body></html>\n";
297 const char *page500 = "<html><body>Internal server error</body></html>\n";
299 if (code == 400) page = page400;
300 else if (code == 404) page = page404;
301 else if (code == 405) page = page405;
302 else if (code == 500) page = page500;
305 struct MHD_Response* response = MHD_create_response_from_buffer(strlen(page), (void *)page, MHD_RESPMEM_PERSISTENT);
306 int ret = MHD_queue_response(mhd_connection, code, response);
307 MHD_destroy_response(response);