afb-hsrv: Adapt to next version of libmicrohttpd
[src/app-framework-binder.git] / src / afb-hsrv.c
1 /*
2  * Copyright (C) 2016, 2017, 2018 "IoT.bzh"
3  * Author: José Bollo <jose.bollo@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #define _GNU_SOURCE
19
20 #include <stdint.h>
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <assert.h>
25 #include <poll.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <sys/stat.h>
29
30 #include <json-c/json.h>
31 #include <microhttpd.h>
32 #if MHD_VERSION < 0x00095206
33 # define MHD_ALLOW_SUSPEND_RESUME MHD_USE_SUSPEND_RESUME
34 #endif
35
36 #include "afb-method.h"
37 #include "afb-context.h"
38 #include "afb-xreq.h"
39 #include "afb-hreq.h"
40 #include "afb-hsrv.h"
41 #include "afb-fdev.h"
42 #include "fdev.h"
43 #include "verbose.h"
44 #include "locale-root.h"
45
46 #include "afb-systemd.h"
47 #include "jobs.h"
48
49 #define JSON_CONTENT  "application/json"
50 #define FORM_CONTENT  MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
51
52
53 struct hsrv_handler {
54         struct hsrv_handler *next;
55         const char *prefix;
56         size_t length;
57         int (*handler) (struct afb_hreq *, void *);
58         void *data;
59         int priority;
60 };
61
62 struct hsrv_alias {
63         struct locale_root *root;
64         int relax;
65 };
66
67 struct afb_hsrv {
68         unsigned refcount;
69         struct hsrv_handler *handlers;
70         struct MHD_Daemon *httpd;
71         struct fdev *fdev;
72         char *cache_to;
73 };
74
75 static void reply_error(struct MHD_Connection *connection, unsigned int status)
76 {
77         struct MHD_Response *response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
78         MHD_queue_response(connection, status, response);
79         MHD_destroy_response(response);
80 }
81
82 static int postproc(void *cls,
83                     enum MHD_ValueKind kind,
84                     const char *key,
85                     const char *filename,
86                     const char *content_type,
87                     const char *transfer_encoding,
88                     const char *data,
89                     uint64_t off,
90                     size_t size)
91 {
92         struct afb_hreq *hreq = cls;
93         if (filename != NULL)
94                 return afb_hreq_post_add_file(hreq, key, filename, data, size);
95         else
96                 return afb_hreq_post_add(hreq, key, data, size);
97 }
98
99 static int access_handler(
100                 void *cls,
101                 struct MHD_Connection *connection,
102                 const char *url,
103                 const char *methodstr,
104                 const char *version,
105                 const char *upload_data,
106                 size_t *upload_data_size,
107                 void **recordreq)
108 {
109         int rc;
110         struct afb_hreq *hreq;
111         enum afb_method method;
112         struct afb_hsrv *hsrv;
113         struct hsrv_handler *iter;
114         const char *type;
115         enum json_tokener_error jerr;
116
117         hsrv = cls;
118         hreq = *recordreq;
119         if (hreq == NULL) {
120                 /* get the method */
121                 method = get_method(methodstr);
122                 method &= afb_method_get | afb_method_post;
123                 if (method == afb_method_none) {
124                         WARNING("Unsupported HTTP operation %s", methodstr);
125                         reply_error(connection, MHD_HTTP_BAD_REQUEST);
126                         return MHD_YES;
127                 }
128
129                 /* create the request */
130                 hreq = afb_hreq_create();
131                 if (hreq == NULL) {
132                         ERROR("Can't allocate 'hreq'");
133                         reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
134                         return MHD_YES;
135                 }
136
137                 /* init the request */
138                 hreq->hsrv = hsrv;
139                 hreq->cacheTimeout = hsrv->cache_to;
140                 hreq->connection = connection;
141                 hreq->method = method;
142                 hreq->version = version;
143                 hreq->lang = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_ACCEPT_LANGUAGE);
144                 hreq->tail = hreq->url = url;
145                 hreq->lentail = hreq->lenurl = strlen(url);
146                 *recordreq = hreq;
147
148                 /* init the post processing */
149                 if (method == afb_method_post) {
150                         type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
151                         if (type == NULL) {
152                                 /* an empty post, let's process it as a get */
153                                 hreq->method = afb_method_get;
154                         } else if (strcasestr(type, FORM_CONTENT) != NULL) {
155                                 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
156                                 if (hreq->postform == NULL) {
157                                         ERROR("Can't create POST processor");
158                                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
159                                 }
160                                 return MHD_YES;
161                         } else if (strcasestr(type, JSON_CONTENT) != NULL) {
162                                 hreq->tokener = json_tokener_new();
163                                 if (hreq->tokener == NULL) {
164                                         ERROR("Can't create tokener for POST");
165                                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
166                                 }
167                                 return MHD_YES;
168                         } else {
169                                 WARNING("Unsupported media type %s", type);
170                                 afb_hreq_reply_error(hreq, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
171                                 return MHD_YES;
172                         }
173                 }
174         }
175
176         /* process further data */
177         if (*upload_data_size) {
178                 if (hreq->postform != NULL) {
179                         if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size)) {
180                                 ERROR("error in POST processor");
181                                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
182                                 return MHD_YES;
183                         }
184                 } else if (hreq->tokener) {
185                         hreq->json = json_tokener_parse_ex(hreq->tokener, upload_data, (int)*upload_data_size);
186                         jerr = json_tokener_get_error(hreq->tokener);
187                         if (jerr == json_tokener_continue) {
188                                 hreq->json = json_tokener_parse_ex(hreq->tokener, "", 1);
189                                 jerr = json_tokener_get_error(hreq->tokener);
190                         }
191                         if (jerr != json_tokener_success) {
192                                 ERROR("error in POST json: %s", json_tokener_error_desc(jerr));
193                                 afb_hreq_reply_error(hreq, MHD_HTTP_BAD_REQUEST);
194                                 return MHD_YES;
195                         }
196                 }
197                 *upload_data_size = 0;
198                 return MHD_YES;
199         }
200
201         /* flush the data */
202         if (hreq->postform != NULL) {
203                 rc = MHD_destroy_post_processor(hreq->postform);
204                 hreq->postform = NULL;
205                 if (rc == MHD_NO) {
206                         ERROR("error detected in POST processing");
207                         afb_hreq_reply_error(hreq, MHD_HTTP_BAD_REQUEST);
208                         return MHD_YES;
209                 }
210         }
211         if (hreq->tokener != NULL) {
212                 json_tokener_free(hreq->tokener);
213                 hreq->tokener = NULL;
214         }
215
216         if (hreq->scanned != 0) {
217                 if (hreq->replied == 0 && hreq->suspended == 0) {
218                         MHD_suspend_connection (connection);
219                         hreq->suspended = 1;
220                 }
221                 return MHD_YES;
222         }
223
224         /* search an handler for the request */
225         hreq->scanned = 1;
226         iter = hsrv->handlers;
227         while (iter) {
228                 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
229                         if (iter->handler(hreq, iter->data)) {
230                                 if (hreq->replied == 0 && hreq->suspended == 0) {
231                                         MHD_suspend_connection (connection);
232                                         hreq->suspended = 1;
233                                 }
234                                 return MHD_YES;
235                         }
236                         hreq->tail = hreq->url;
237                         hreq->lentail = hreq->lenurl;
238                 }
239                 iter = iter->next;
240         }
241
242         /* no handler */
243         NOTICE("Unhandled request to %s", hreq->url);
244         afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
245         return MHD_YES;
246 }
247
248 /* Because of POST call multiple time requestApi we need to free POST handle here */
249 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
250                         enum MHD_RequestTerminationCode toe)
251 {
252         struct afb_hreq *hreq;
253
254         hreq = *recordreq;
255         if (hreq) {
256                 afb_hreq_unref(hreq);
257         }
258 }
259
260 static void do_run(int signum, void *arg)
261 {
262         MHD_UNSIGNED_LONG_LONG to;
263         struct afb_hsrv *hsrv = arg;
264
265         if (!signum) {
266                 do { MHD_run(hsrv->httpd); } while(MHD_get_timeout(hsrv->httpd, &to) == MHD_YES && !to);
267         }
268         fdev_set_events(hsrv->fdev, EPOLLIN);
269 }
270
271 void afb_hsrv_run(struct afb_hsrv *hsrv)
272 {
273         fdev_set_events(hsrv->fdev, 0);
274         if (jobs_queue(hsrv, 0, do_run, hsrv) < 0)
275                 do_run(0, hsrv);
276 }
277
278 static void listen_callback(void *hsrv, uint32_t revents, struct fdev *fdev)
279 {
280         afb_hsrv_run(hsrv);
281 }
282
283 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
284 {
285         return MHD_YES;
286 }
287
288 static struct hsrv_handler *new_handler(
289                 struct hsrv_handler *head,
290                 const char *prefix,
291                 int (*handler) (struct afb_hreq *, void *),
292                 void *data,
293                 int priority)
294 {
295         struct hsrv_handler *link, *iter, *previous;
296         size_t length;
297
298         /* get the length of the prefix without its leading / */
299         length = strlen(prefix);
300         while (length && prefix[length - 1] == '/')
301                 length--;
302
303         /* allocates the new link */
304         link = malloc(sizeof *link);
305         if (link == NULL)
306                 return NULL;
307
308         /* initialize it */
309         link->prefix = prefix;
310         link->length = length;
311         link->handler = handler;
312         link->data = data;
313         link->priority = priority;
314
315         /* adds it */
316         previous = NULL;
317         iter = head;
318         while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
319                 previous = iter;
320                 iter = iter->next;
321         }
322         link->next = iter;
323         if (previous == NULL)
324                 return link;
325         previous->next = link;
326         return head;
327 }
328
329 static int handle_alias(struct afb_hreq *hreq, void *data)
330 {
331         int rc;
332         struct hsrv_alias *da = data;
333         struct locale_search *search;
334
335         if (hreq->method != afb_method_get) {
336                 if (da->relax)
337                         return 0;
338                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
339                 return 1;
340         }
341
342         search = locale_root_search(da->root, hreq->lang, 0);
343         rc = afb_hreq_reply_locale_file_if_exist(hreq, search, &hreq->tail[1]);
344         locale_search_unref(search);
345         if (rc == 0) {
346                 if (da->relax)
347                         return 0;
348                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
349         }
350         return 1;
351 }
352
353 int afb_hsrv_add_handler(
354                 struct afb_hsrv *hsrv,
355                 const char *prefix,
356                 int (*handler) (struct afb_hreq *, void *),
357                 void *data,
358                 int priority)
359 {
360         struct hsrv_handler *head;
361
362         head = new_handler(hsrv->handlers, prefix, handler, data, priority);
363         if (head == NULL)
364                 return 0;
365         hsrv->handlers = head;
366         return 1;
367 }
368
369 int afb_hsrv_add_alias_root(struct afb_hsrv *hsrv, const char *prefix, struct locale_root *root, int priority, int relax)
370 {
371         struct hsrv_alias *da;
372
373         da = malloc(sizeof *da);
374         if (da != NULL) {
375                 da->root = root;
376                 da->relax = relax;
377                 if (afb_hsrv_add_handler(hsrv, prefix, handle_alias, da, priority)) {
378                         locale_root_addref(root);
379                         return 1;
380                 }
381                 free(da);
382         }
383         return 0;
384 }
385
386 int afb_hsrv_add_alias(struct afb_hsrv *hsrv, const char *prefix, int dirfd, const char *alias, int priority, int relax)
387 {
388         struct locale_root *root;
389         int rc;
390
391         root = locale_root_create_at(dirfd, alias);
392         if (root == NULL) {
393                 ERROR("can't connect to directory %s: %m", alias);
394                 rc = 0;
395         } else {
396                 rc = afb_hsrv_add_alias_root(hsrv, prefix, root, priority, relax);
397                 locale_root_unref(root);
398         }
399         return rc;
400 }
401
402 int afb_hsrv_set_cache_timeout(struct afb_hsrv *hsrv, int duration)
403 {
404         int rc;
405         char *dur;
406
407         rc = asprintf(&dur, "%d", duration);
408         if (rc < 0)
409                 return 0;
410
411         free(hsrv->cache_to);
412         hsrv->cache_to = dur;
413         return 1;
414 }
415
416 int afb_hsrv_start(struct afb_hsrv *hsrv, uint16_t port, unsigned int connection_timeout)
417 {
418         struct fdev *fdev;
419         struct MHD_Daemon *httpd;
420         const union MHD_DaemonInfo *info;
421
422         httpd = MHD_start_daemon(
423                 MHD_USE_EPOLL | MHD_ALLOW_UPGRADE | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_ALLOW_SUSPEND_RESUME,
424                 port,                           /* port */
425                 new_client_handler, NULL,       /* Tcp Accept call back + extra attribute */
426                 access_handler, hsrv,   /* Http Request Call back + extra attribute */
427                 MHD_OPTION_NOTIFY_COMPLETED, end_handler, hsrv,
428                 MHD_OPTION_CONNECTION_TIMEOUT, connection_timeout,
429                 MHD_OPTION_END);        /* options-end */
430
431         if (httpd == NULL) {
432                 ERROR("httpStart invalid httpd port: %d", (int)port);
433                 return 0;
434         }
435
436         info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
437         if (info == NULL) {
438                 MHD_stop_daemon(httpd);
439                 ERROR("httpStart no pollfd");
440                 return 0;
441         }
442
443         fdev = afb_fdev_create(info->listen_fd);
444         if (fdev == NULL) {
445                 MHD_stop_daemon(httpd);
446                 ERROR("connection to events for httpd failed");
447                 return 0;
448         }
449         fdev_set_autoclose(fdev, 0);
450         fdev_set_events(fdev, EPOLLIN);
451         fdev_set_callback(fdev, listen_callback, hsrv);
452
453         hsrv->httpd = httpd;
454         hsrv->fdev = fdev;
455         return 1;
456 }
457
458 void afb_hsrv_stop(struct afb_hsrv *hsrv)
459 {
460         if (hsrv->fdev != NULL) {
461                 fdev_unref(hsrv->fdev);
462                 hsrv->fdev = NULL;
463         }
464         if (hsrv->httpd != NULL)
465                 MHD_stop_daemon(hsrv->httpd);
466         hsrv->httpd = NULL;
467 }
468
469 struct afb_hsrv *afb_hsrv_create()
470 {
471         struct afb_hsrv *result = calloc(1, sizeof(struct afb_hsrv));
472         if (result != NULL)
473                 result->refcount = 1;
474         return result;
475 }
476
477 void afb_hsrv_put(struct afb_hsrv *hsrv)
478 {
479         assert(hsrv->refcount != 0);
480         if (!--hsrv->refcount) {
481                 afb_hsrv_stop(hsrv);
482                 free(hsrv);
483         }
484 }
485