]> git.vomp.tv Git - jsonserver.git/blob - httpdclient.c
JSON: Switch from StyledWriter to StreamWriterBuilder
[jsonserver.git] / httpdclient.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <malloc.h>
4 #include <sys/stat.h>
5 #include <unistd.h>
6 #include <fcntl.h>
7
8 #include <memory>
9
10 #include "httpdclient.h"
11
12 #include "vdrclient.h"
13
14 #define POSTBUFFERSIZE  512
15
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;
20
21 bool HTTPDClient::StartServer(std::string _docRoot, int port, const char* _configDir)
22 {
23   docRoot = _docRoot;
24   configDir = std::string(_configDir);
25
26   logger = spd::get("jsonserver_spdlog");
27
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,
33                            MHD_OPTION_END);
34   if (httpdserver == NULL) { logger.reset(); return false; }
35   logger->info("HTTPDClient: Started");
36   return true;
37 }
38
39 void HTTPDClient::StopServer()
40 {
41   if (httpdserver) MHD_stop_daemon(httpdserver);
42   httpdserver = NULL;
43   logger.reset();
44 }
45
46 // Now for the libmicrohttpd callbacks
47
48 int HTTPDClient::uri_key_value(void *cls, enum MHD_ValueKind kind, const char* key, const char* value)
49 {
50   if (kind != MHD_GET_ARGUMENT_KIND) return MHD_NO;
51   HTTPDClient* httpdclient = (HTTPDClient*)cls;
52   httpdclient->addGetVar(key, value);
53   return MHD_YES;
54 }
55
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)
59 {
60   if (size == 0) return MHD_NO;
61
62   HTTPDClient* httpdclient = (HTTPDClient*)clientIdentifier;
63   httpdclient->addPostField(key, data, size);
64   return MHD_YES;
65
66   //Return MHD_YES to continue iterating, MHD_NO to abort the iteration.
67 }
68
69 void HTTPDClient::request_completed(void *cls, struct MHD_Connection *mhd_connection,
70                                     void **unused, enum MHD_RequestTerminationCode toe)
71 {
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();
76 }
77
78 void HTTPDClient::connection_notify(void *cls, struct MHD_Connection* mhd_connection,
79                                     void **socket_context, enum MHD_ConnectionNotificationCode toe)
80 {
81   if (toe == MHD_CONNECTION_NOTIFY_STARTED)
82   {
83     *socket_context = (void*)new HTTPDClient(mhd_connection, configDir);
84   }
85   else if (toe == MHD_CONNECTION_NOTIFY_CLOSED)
86   {
87     HTTPDClient* httpdclient = (HTTPDClient*)*socket_context;
88     if (!httpdclient) return;
89     delete httpdclient;
90     *socket_context = NULL;
91   }
92 }
93
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)
98 {
99 /*
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);
112 */
113
114   const MHD_ConnectionInfo* mhdc = MHD_get_connection_info(mhd_connection, MHD_CONNECTION_INFO_SOCKET_CONTEXT);
115
116   HTTPDClient* httpdclient = (HTTPDClient*)mhdc->socket_context;
117
118   // Now we are going to use userData as a flag to say first run or not
119
120   if (!*userData) // new request
121   {
122     *userData = (void*)1;
123     httpdclient->setUrl(url);
124
125     if (!strcmp(method, "POST"))
126     {
127       MHD_get_connection_values(mhd_connection, MHD_GET_ARGUMENT_KIND, HTTPDClient::uri_key_value, (void*)httpdclient);
128
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);
132     }
133     else if (!strcmp(method, "GET"))
134     {
135       // OK, nothing else to do here
136     }
137     else
138     {
139       return MHD_NO;
140     }
141
142     return MHD_YES;
143   }
144
145   // Not first go at this request
146
147   if (!strcmp(method, "GET"))
148   {
149     return httpdclient->processGET();
150   }
151   else if (!strcmp(method, "POST"))
152   {
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
156
157     if (*upload_data_size != 0) // There is more to process, and signal run again
158     {
159       MHD_post_process(httpdclient->postprocessor, upload_data, *upload_data_size);
160       *upload_data_size = 0;
161       return MHD_YES;
162     }
163     else
164     {
165 //      printf("hc: zero post provided, end of upload\n");
166       return httpdclient->processPOST();
167     }
168   }
169   else
170   {
171     return httpdclient->sendStockResponse(405);
172   }
173 }
174
175 // End of static callbacks, now for the client object itself
176
177 HTTPDClient::HTTPDClient(struct MHD_Connection* _mhd_connection, const std::string& _configDir)
178 : postprocessor(NULL), url(NULL), mhd_connection(_mhd_connection), vdrclient(_configDir)
179 {
180 //  printf("HTTPDClient created %p\n", this);
181 }
182
183 HTTPDClient::~HTTPDClient()
184 {
185 //  printf("%p HTTPDClient destructor\n", this);
186   if (url) free(url);
187 }
188
189 void HTTPDClient::requestComplete()
190 {
191 //  printf("%p HTTPDClient request complete\n", this);
192   if (postprocessor)
193   {
194 //    printf("here\n");
195     MHD_destroy_post_processor(postprocessor);
196     postprocessor = NULL;
197   }
198 }
199
200 void HTTPDClient::setUrl(const char* _url)
201 {
202   int size __attribute__((unused)) = asprintf(&url, "%s", _url);
203 }
204
205 void HTTPDClient::addGetVar(const char* key, const char* value)
206 {
207   if (strlen(key) > 50) return;
208   if (value && (strlen(value) > 1000)) return;
209
210   getVars[std::string(key)] = std::string(value);
211 /*
212   for(auto gv : getVars)
213   {
214     printf("%s %s\n", gv.first.c_str(), gv.second.c_str());
215   }
216   */
217 }
218
219 void HTTPDClient::addPostField(const char* key, const char* value, int valueLength)
220 {
221   if (strlen(key) > 50) return;
222   if (strlen(value) > 1000) return;
223
224   postFields[std::string(key)] = std::string(value, valueLength);
225
226   /*
227   for(auto pf : postFields)
228   {
229     printf("%s %s\n", pf.first.c_str(), pf.second.c_str());
230   }
231   */
232 }
233
234 int HTTPDClient::processGET()
235 {
236   const char* defaultfilename = "index.html";
237
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.
240
241   int size  __attribute__((unused));
242
243   int slen = strlen(url);
244   char* fullpath;
245   if (url[slen-1] == '/')
246     size = asprintf(&fullpath, "%s%s%s", docRoot.c_str(), url, defaultfilename);
247   else
248     size = asprintf(&fullpath, "%s%s", docRoot.c_str(), url);
249
250   //printf("FILENAME: '%s'\n", fullpath);
251
252   struct stat sbuf;
253   if (   (stat(fullpath, &sbuf) == -1)               // failed to stat
254       || ((sbuf.st_mode & S_IFMT) != S_IFREG)  )     // must be regular file
255   {
256     free(fullpath);
257     return sendStockResponse(404);
258   }
259
260   int fd = open(fullpath, O_RDONLY);
261   free(fullpath);
262
263   if (fd == -1) return MHD_NO;
264
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);
268
269   return ret;
270 }
271
272 int HTTPDClient::processPOST()
273 {
274  // printf("Process POST:\n");
275   //printf("REQ: %s\n", getVars["req"].c_str());
276
277   if (strcmp(url, "/jsonserver")) return sendStockResponse(404);
278   if (getVars["req"].empty()) return sendStockResponse(400);
279
280   std::string returnData;
281
282   bool success = vdrclient.process(getVars["req"], postFields, returnData);
283   if (!success) return sendStockResponse(500);
284
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);
289   return ret;
290 }
291
292 int HTTPDClient::sendStockResponse(int code)
293 {
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";
298   const char* page;
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;
303   else return MHD_NO;
304
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);
308   return ret;
309 }