]> git.vomp.tv Git - jsonserver.git/blob - httpdclient.c
Switch to libmicrohttpd. Rewrite handler.
[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
20 bool HTTPDClient::StartServer(std::string _docRoot, int port)
21 {
22   docRoot = _docRoot;
23
24   logger = spd::get("jsonserver_spdlog");
25
26   httpdserver = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, port, NULL, NULL,
27                            &HTTPDClient::handle_connection, NULL,
28                            MHD_OPTION_NOTIFY_CONNECTION, &HTTPDClient::connection_notify, NULL,
29                            MHD_OPTION_NOTIFY_COMPLETED, &HTTPDClient::request_completed, NULL,
30                            MHD_OPTION_END);
31   if (httpdserver == NULL) { logger.reset(); return false; }
32   logger->info("HTTPDClient: Started");
33   return true;
34 }
35
36 void HTTPDClient::StopServer()
37 {
38   if (httpdserver) MHD_stop_daemon(httpdserver);
39   httpdserver = NULL;
40   logger.reset();
41 }
42
43 // Now for the libmicrohttpd callbacks
44
45 int HTTPDClient::uri_key_value(void *cls, enum MHD_ValueKind kind, const char* key, const char* value)
46 {
47   if (kind != MHD_GET_ARGUMENT_KIND) return MHD_NO;
48   HTTPDClient* httpdclient = (HTTPDClient*)cls;
49   httpdclient->addGetVar(key, value);
50   return MHD_YES;
51 }
52
53 int HTTPDClient::iterate_post(void *clientIdentifier, enum MHD_ValueKind kind, const char *key,
54               const char *filename, const char* content_type,
55               const char *transfer_encoding, const char *data, uint64_t off, size_t size)
56 {
57   if (size == 0) return MHD_NO;
58
59   HTTPDClient* httpdclient = (HTTPDClient*)clientIdentifier;
60   httpdclient->addPostField(key, data, size);
61   return MHD_YES;
62
63   //Return MHD_YES to continue iterating, MHD_NO to abort the iteration.
64 }
65
66 void HTTPDClient::request_completed(void *cls, struct MHD_Connection *mhd_connection,
67                                     void **unused, enum MHD_RequestTerminationCode toe)
68 {
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();
73 }
74
75 void HTTPDClient::connection_notify(void *cls, struct MHD_Connection* mhd_connection,
76                                     void **socket_context, enum MHD_ConnectionNotificationCode toe)
77 {
78   if (toe == MHD_CONNECTION_NOTIFY_STARTED)
79   {
80     *socket_context = (void*)new HTTPDClient(mhd_connection);
81   }
82   else if (toe == MHD_CONNECTION_NOTIFY_CLOSED)
83   {
84     HTTPDClient* httpdclient = (HTTPDClient*)*socket_context;
85     if (!httpdclient) return;
86     delete httpdclient;
87     *socket_context = NULL;
88   }
89 }
90
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)
95 {
96 /*
97   printf("handle_connection called\n");
98   printf("hc: cls %p\n", cls);
99   printf("hc: mhd_connection %p\n", mhd_connection);
100   printf("hc: url %p\n", url);
101   if (url) printf("hc: url: %s\n", url);
102   printf("hc: method %p\n", method);
103   if (url) printf("hc: method: %s\n",  method);
104   printf("hc: version %p\n", version);
105   if (url) printf("hc: version: %s\n",  version);
106   printf("hc: upload_data %p\n", upload_data);
107   printf("hc: upload_data_size %lu\n", *upload_data_size);
108   printf("hc: userData %p\n", *userData);
109 */
110
111   const MHD_ConnectionInfo* mhdc = MHD_get_connection_info(mhd_connection, MHD_CONNECTION_INFO_SOCKET_CONTEXT);
112
113   HTTPDClient* httpdclient = (HTTPDClient*)mhdc->socket_context;
114
115   // Now we are going to use userData as a flag to say first run or not
116
117   if (!*userData) // new request
118   {
119     *userData = (void*)1;
120     httpdclient->setUrl(url);
121
122     if (!strcmp(method, "POST"))
123     {
124       MHD_get_connection_values(mhd_connection, MHD_GET_ARGUMENT_KIND, HTTPDClient::uri_key_value, (void*)httpdclient);
125
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);
129     }
130     else if (!strcmp(method, "GET"))
131     {
132       // OK, nothing else to do here
133     }
134     else
135     {
136       return MHD_NO;
137     }
138
139     return MHD_YES;
140   }
141
142   // Not first go at this request
143
144   if (!strcmp(method, "GET"))
145   {
146     return httpdclient->processGET();
147   }
148   else if (!strcmp(method, "POST"))
149   {
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
153
154     if (*upload_data_size != 0) // There is more to process, and signal run again
155     {
156       MHD_post_process(httpdclient->postprocessor, upload_data, *upload_data_size);
157       *upload_data_size = 0;
158       return MHD_YES;
159     }
160     else
161     {
162 //      printf("hc: zero post provided, end of upload\n");
163       return httpdclient->processPOST();
164     }
165   }
166   else
167   {
168     return httpdclient->sendStockResponse(405);
169   }
170 }
171
172 // End of static callbacks, now for the client object itself
173
174 HTTPDClient::HTTPDClient(struct MHD_Connection* _mhd_connection)
175 : postprocessor(NULL), url(NULL), mhd_connection(_mhd_connection)
176 {
177 //  printf("HTTPDClient created %p\n", this);
178 }
179
180 HTTPDClient::~HTTPDClient()
181 {
182 //  printf("%p HTTPDClient destructor\n", this);
183   if (url) free(url);
184 }
185
186 void HTTPDClient::requestComplete()
187 {
188 //  printf("%p HTTPDClient request complete\n", this);
189   if (postprocessor)
190   {
191 //    printf("here\n");
192     MHD_destroy_post_processor(postprocessor);
193     postprocessor = NULL;
194   }
195 }
196
197 void HTTPDClient::setUrl(const char* _url)
198 {
199   int size __attribute__((unused)) = asprintf(&url, "%s", _url);
200 }
201
202 void HTTPDClient::addGetVar(const char* key, const char* value)
203 {
204   if (strlen(key) > 50) return;
205   if (value && (strlen(value) > 1000)) return;
206
207   getVars[std::string(key)] = std::string(value);
208 /*
209   for(auto gv : getVars)
210   {
211     printf("%s %s\n", gv.first.c_str(), gv.second.c_str());
212   }
213   */
214 }
215
216 void HTTPDClient::addPostField(const char* key, const char* value, int valueLength)
217 {
218   if (strlen(key) > 50) return;
219   if (strlen(value) > 1000) return;
220
221   postFields[std::string(key)] = std::string(value, valueLength);
222
223   /*
224   for(auto pf : postFields)
225   {
226     printf("%s %s\n", pf.first.c_str(), pf.second.c_str());
227   }
228   */
229 }
230
231 int HTTPDClient::processGET()
232 {
233   const char* defaultfilename = "index.html";
234
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.
237
238   int size  __attribute__((unused));
239
240   int slen = strlen(url);
241   char* fullpath;
242   if (url[slen-1] == '/')
243     size = asprintf(&fullpath, "%s%s%s", docRoot.c_str(), url, defaultfilename);
244   else
245     size = asprintf(&fullpath, "%s%s", docRoot.c_str(), url);
246
247   //printf("FILENAME: '%s'\n", fullpath);
248
249   struct stat sbuf;
250   if (   (stat(fullpath, &sbuf) == -1)               // failed to stat
251       || ((sbuf.st_mode & S_IFMT) != S_IFREG)  )     // must be regular file
252   {
253     free(fullpath);
254     return sendStockResponse(404);
255   }
256
257   int fd = open(fullpath, O_RDONLY);
258   free(fullpath);
259
260   if (fd == -1) return MHD_NO;
261
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);
264   MHD_destroy_response(response);
265
266   return ret;
267 }
268
269 int HTTPDClient::processPOST()
270 {
271  // printf("Process POST:\n");
272   //printf("REQ: %s\n", getVars["req"].c_str());
273
274   if (strcmp(url, "/jsonserver")) return sendStockResponse(404);
275   if (getVars["req"].empty()) return sendStockResponse(400);
276
277   std::string returnData;
278
279   bool success = vdrclient.process(getVars["req"], postFields, returnData);
280   if (!success) return sendStockResponse(500);
281
282   struct MHD_Response* response = MHD_create_response_from_buffer(strlen(returnData.c_str()), (void *)returnData.c_str(), MHD_RESPMEM_MUST_COPY);
283   int ret = MHD_queue_response(mhd_connection, MHD_HTTP_OK, response);
284   MHD_destroy_response(response);
285   return ret;
286 }
287
288 int HTTPDClient::sendStockResponse(int code)
289 {
290   const char *page400 = "<html><body>Bad request</body></html>\n";
291   const char *page404 = "<html><body>File not found</body></html>\n";
292   const char *page405 = "<html><body>Method not allowed</body></html>\n";
293   const char *page500 = "<html><body>Internal server error</body></html>\n";
294   const char* page;
295   if      (code == 400) page = page400;
296   else if (code == 404) page = page404;
297   else if (code == 405) page = page405;
298   else if (code == 500) page = page500;
299   else return MHD_NO;
300
301   struct MHD_Response* response = MHD_create_response_from_buffer(strlen(page), (void *)page, MHD_RESPMEM_PERSISTENT);
302   int ret = MHD_queue_response(mhd_connection, code, response);
303   MHD_destroy_response(response);
304   return ret;
305 }