Allow to remove libmicrohttpd (HTTP server)
[src/app-framework-binder.git] / src / afb-hsrv.c
1 /*
2  * Copyright (C) 2016-2019 "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 #if WITH_LIBMICROHTTPD
19
20 #define _GNU_SOURCE
21
22 #include <stdint.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <assert.h>
27 #include <poll.h>
28 #include <fcntl.h>
29 #include <errno.h>
30 #include <netdb.h>
31 #include <sys/socket.h>
32 #include <sys/stat.h>
33
34 #include <json-c/json.h>
35 #include <microhttpd.h>
36 #if MHD_VERSION < 0x00095206
37 # define MHD_ALLOW_SUSPEND_RESUME MHD_USE_SUSPEND_RESUME
38 #endif
39
40 #include "afb-method.h"
41 #include "afb-context.h"
42 #include "afb-xreq.h"
43 #include "afb-hreq.h"
44 #include "afb-hsrv.h"
45 #include "afb-fdev.h"
46 #include "afb-socket.h"
47
48 #include "fdev.h"
49 #include "verbose.h"
50 #include "locale-root.h"
51 #include "systemd.h"
52 #include "jobs.h"
53
54 #define JSON_CONTENT  "application/json"
55 #define FORM_CONTENT  MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
56
57 struct hsrv_itf {
58         struct hsrv_itf *next;
59         struct afb_hsrv *hsrv;
60         struct fdev *fdev;
61         char uri[1];
62 };
63
64 struct hsrv_handler {
65         struct hsrv_handler *next;
66         const char *prefix;
67         size_t length;
68         int (*handler) (struct afb_hreq *, void *);
69         void *data;
70         int priority;
71 };
72
73 struct hsrv_alias {
74         struct locale_root *root;
75         int relax;
76 };
77
78 struct afb_hsrv {
79         unsigned refcount;
80         struct hsrv_handler *handlers;
81         struct hsrv_itf *interfaces;
82         struct MHD_Daemon *httpd;
83         struct fdev *fdev;
84         char *cache_to;
85 };
86
87 static void reply_error(struct MHD_Connection *connection, unsigned int status)
88 {
89         struct MHD_Response *response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
90         MHD_queue_response(connection, status, response);
91         MHD_destroy_response(response);
92 }
93
94 static int postproc(void *cls,
95                     enum MHD_ValueKind kind,
96                     const char *key,
97                     const char *filename,
98                     const char *content_type,
99                     const char *transfer_encoding,
100                     const char *data,
101                     uint64_t off,
102                     size_t size)
103 {
104         struct afb_hreq *hreq = cls;
105         if (filename != NULL)
106                 return afb_hreq_post_add_file(hreq, key, filename, data, size);
107         else
108                 return afb_hreq_post_add(hreq, key, data, size);
109 }
110
111 static int access_handler(
112                 void *cls,
113                 struct MHD_Connection *connection,
114                 const char *url,
115                 const char *methodstr,
116                 const char *version,
117                 const char *upload_data,
118                 size_t *upload_data_size,
119                 void **recordreq)
120 {
121         int rc;
122         struct afb_hreq *hreq;
123         enum afb_method method;
124         struct afb_hsrv *hsrv;
125         struct hsrv_handler *iter;
126         const char *type;
127         enum json_tokener_error jerr;
128
129         hsrv = cls;
130         hreq = *recordreq;
131         if (hreq == NULL) {
132                 /* get the method */
133                 method = get_method(methodstr);
134                 method &= afb_method_get | afb_method_post;
135                 if (method == afb_method_none) {
136                         WARNING("Unsupported HTTP operation %s", methodstr);
137                         reply_error(connection, MHD_HTTP_BAD_REQUEST);
138                         return MHD_YES;
139                 }
140
141                 /* create the request */
142                 hreq = afb_hreq_create();
143                 if (hreq == NULL) {
144                         ERROR("Can't allocate 'hreq'");
145                         reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
146                         return MHD_YES;
147                 }
148
149                 /* init the request */
150                 hreq->hsrv = hsrv;
151                 hreq->cacheTimeout = hsrv->cache_to;
152                 hreq->connection = connection;
153                 hreq->method = method;
154                 hreq->version = version;
155                 hreq->lang = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_ACCEPT_LANGUAGE);
156                 hreq->tail = hreq->url = url;
157                 hreq->lentail = hreq->lenurl = strlen(url);
158                 *recordreq = hreq;
159
160                 /* init the post processing */
161                 if (method == afb_method_post) {
162                         type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
163                         if (type == NULL) {
164                                 /* an empty post, let's process it as a get */
165                                 hreq->method = afb_method_get;
166                         } else if (strcasestr(type, FORM_CONTENT) != NULL) {
167                                 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
168                                 if (hreq->postform == NULL) {
169                                         ERROR("Can't create POST processor");
170                                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
171                                 }
172                                 return MHD_YES;
173                         } else if (strcasestr(type, JSON_CONTENT) != NULL) {
174                                 hreq->tokener = json_tokener_new();
175                                 if (hreq->tokener == NULL) {
176                                         ERROR("Can't create tokener for POST");
177                                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
178                                 }
179                                 return MHD_YES;
180                         } else {
181                                 WARNING("Unsupported media type %s", type);
182                                 afb_hreq_reply_error(hreq, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
183                                 return MHD_YES;
184                         }
185                 }
186         }
187
188         /* process further data */
189         if (*upload_data_size) {
190                 if (hreq->postform != NULL) {
191                         if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size)) {
192                                 ERROR("error in POST processor");
193                                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
194                                 return MHD_YES;
195                         }
196                 } else if (hreq->tokener) {
197                         hreq->json = json_tokener_parse_ex(hreq->tokener, upload_data, (int)*upload_data_size);
198                         jerr = json_tokener_get_error(hreq->tokener);
199                         if (jerr == json_tokener_continue) {
200                                 hreq->json = json_tokener_parse_ex(hreq->tokener, "", 1);
201                                 jerr = json_tokener_get_error(hreq->tokener);
202                         }
203                         if (jerr != json_tokener_success) {
204                                 ERROR("error in POST json: %s", json_tokener_error_desc(jerr));
205                                 afb_hreq_reply_error(hreq, MHD_HTTP_BAD_REQUEST);
206                                 return MHD_YES;
207                         }
208                 }
209                 *upload_data_size = 0;
210                 return MHD_YES;
211         }
212
213         /* flush the data */
214         if (hreq->postform != NULL) {
215                 rc = MHD_destroy_post_processor(hreq->postform);
216                 hreq->postform = NULL;
217                 if (rc == MHD_NO) {
218                         ERROR("error detected in POST processing");
219                         afb_hreq_reply_error(hreq, MHD_HTTP_BAD_REQUEST);
220                         return MHD_YES;
221                 }
222         }
223         if (hreq->tokener != NULL) {
224                 json_tokener_free(hreq->tokener);
225                 hreq->tokener = NULL;
226         }
227
228         if (hreq->scanned != 0) {
229                 if (hreq->replied == 0 && hreq->suspended == 0) {
230                         MHD_suspend_connection (connection);
231                         hreq->suspended = 1;
232                 }
233                 return MHD_YES;
234         }
235
236         /* search an handler for the request */
237         hreq->scanned = 1;
238         iter = hsrv->handlers;
239         while (iter) {
240                 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
241                         if (iter->handler(hreq, iter->data)) {
242                                 if (hreq->replied == 0 && hreq->suspended == 0) {
243                                         MHD_suspend_connection (connection);
244                                         hreq->suspended = 1;
245                                 }
246                                 return MHD_YES;
247                         }
248                         hreq->tail = hreq->url;
249                         hreq->lentail = hreq->lenurl;
250                 }
251                 iter = iter->next;
252         }
253
254         /* no handler */
255         NOTICE("Unhandled request to %s", hreq->url);
256         afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
257         return MHD_YES;
258 }
259
260 /* Because of POST call multiple time requestApi we need to free POST handle here */
261 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
262                         enum MHD_RequestTerminationCode toe)
263 {
264         struct afb_hreq *hreq;
265
266         hreq = *recordreq;
267         if (hreq) {
268                 afb_hreq_unref(hreq);
269         }
270 }
271
272 static void do_run(int signum, void *arg)
273 {
274         MHD_UNSIGNED_LONG_LONG to;
275         struct afb_hsrv *hsrv = arg;
276
277         if (!signum) {
278                 do { MHD_run(hsrv->httpd); } while(MHD_get_timeout(hsrv->httpd, &to) == MHD_YES && !to);
279         }
280         fdev_set_events(hsrv->fdev, EPOLLIN);
281 }
282
283 void afb_hsrv_run(struct afb_hsrv *hsrv)
284 {
285         fdev_set_events(hsrv->fdev, 0);
286         if (jobs_queue(hsrv, 0, do_run, hsrv) < 0)
287                 do_run(0, hsrv);
288 }
289
290 static void listen_callback(void *hsrv, uint32_t revents, struct fdev *fdev)
291 {
292         afb_hsrv_run(hsrv);
293 }
294
295 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
296 {
297         return MHD_YES;
298 }
299
300 static struct hsrv_handler *new_handler(
301                 struct hsrv_handler *head,
302                 const char *prefix,
303                 int (*handler) (struct afb_hreq *, void *),
304                 void *data,
305                 int priority)
306 {
307         struct hsrv_handler *link, *iter, *previous;
308         size_t length;
309
310         /* get the length of the prefix without its leading / */
311         length = strlen(prefix);
312         while (length && prefix[length - 1] == '/')
313                 length--;
314
315         /* allocates the new link */
316         link = malloc(sizeof *link);
317         if (link == NULL)
318                 return NULL;
319
320         /* initialize it */
321         link->prefix = prefix;
322         link->length = length;
323         link->handler = handler;
324         link->data = data;
325         link->priority = priority;
326
327         /* adds it */
328         previous = NULL;
329         iter = head;
330         while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
331                 previous = iter;
332                 iter = iter->next;
333         }
334         link->next = iter;
335         if (previous == NULL)
336                 return link;
337         previous->next = link;
338         return head;
339 }
340
341 static int handle_alias(struct afb_hreq *hreq, void *data)
342 {
343         int rc;
344         struct hsrv_alias *da = data;
345         struct locale_search *search;
346
347         if (hreq->method != afb_method_get) {
348                 if (da->relax)
349                         return 0;
350                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
351                 return 1;
352         }
353
354         search = locale_root_search(da->root, hreq->lang, 0);
355         rc = afb_hreq_reply_locale_file_if_exist(hreq, search, &hreq->tail[1]);
356         locale_search_unref(search);
357         if (rc == 0) {
358                 if (da->relax)
359                         return 0;
360                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
361         }
362         return 1;
363 }
364
365 int afb_hsrv_add_handler(
366                 struct afb_hsrv *hsrv,
367                 const char *prefix,
368                 int (*handler) (struct afb_hreq *, void *),
369                 void *data,
370                 int priority)
371 {
372         struct hsrv_handler *head;
373
374         head = new_handler(hsrv->handlers, prefix, handler, data, priority);
375         if (head == NULL)
376                 return 0;
377         hsrv->handlers = head;
378         return 1;
379 }
380
381 int afb_hsrv_add_alias_root(struct afb_hsrv *hsrv, const char *prefix, struct locale_root *root, int priority, int relax)
382 {
383         struct hsrv_alias *da;
384
385         da = malloc(sizeof *da);
386         if (da != NULL) {
387                 da->root = root;
388                 da->relax = relax;
389                 if (afb_hsrv_add_handler(hsrv, prefix, handle_alias, da, priority)) {
390                         locale_root_addref(root);
391                         return 1;
392                 }
393                 free(da);
394         }
395         return 0;
396 }
397
398 int afb_hsrv_add_alias(struct afb_hsrv *hsrv, const char *prefix, int dirfd, const char *alias, int priority, int relax)
399 {
400         struct locale_root *root;
401         int rc;
402
403         root = locale_root_create_at(dirfd, alias);
404         if (root == NULL) {
405                 ERROR("can't connect to directory %s: %m", alias);
406                 rc = 0;
407         } else {
408                 rc = afb_hsrv_add_alias_root(hsrv, prefix, root, priority, relax);
409                 locale_root_unref(root);
410         }
411         return rc;
412 }
413
414 int afb_hsrv_set_cache_timeout(struct afb_hsrv *hsrv, int duration)
415 {
416         int rc;
417         char *dur;
418
419         rc = asprintf(&dur, "%d", duration);
420         if (rc < 0)
421                 return 0;
422
423         free(hsrv->cache_to);
424         hsrv->cache_to = dur;
425         return 1;
426 }
427
428 int afb_hsrv_start(struct afb_hsrv *hsrv, unsigned int connection_timeout)
429 {
430         struct fdev *fdev;
431         struct MHD_Daemon *httpd;
432         const union MHD_DaemonInfo *info;
433
434         httpd = MHD_start_daemon(
435                         MHD_USE_EPOLL
436                         | MHD_ALLOW_UPGRADE
437                         | MHD_USE_TCP_FASTOPEN
438                         | MHD_USE_NO_LISTEN_SOCKET
439                         | MHD_USE_DEBUG
440                         | MHD_ALLOW_SUSPEND_RESUME,
441                         0,                              /* port */
442                         new_client_handler, NULL,       /* Tcp Accept call back + extra attribute */
443                         access_handler, hsrv,   /* Http Request Call back + extra attribute */
444                         MHD_OPTION_NOTIFY_COMPLETED, end_handler, hsrv,
445                         MHD_OPTION_CONNECTION_TIMEOUT, connection_timeout,
446                         MHD_OPTION_END);        /* options-end */
447
448         if (httpd == NULL) {
449                 ERROR("httpStart invalid httpd");
450                 return 0;
451         }
452
453         info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD);
454         if (info == NULL) {
455                 MHD_stop_daemon(httpd);
456                 ERROR("httpStart no pollfd");
457                 return 0;
458         }
459
460         fdev = afb_fdev_create(info->epoll_fd);
461         if (fdev == NULL) {
462                 MHD_stop_daemon(httpd);
463                 ERROR("connection to events for httpd failed");
464                 return 0;
465         }
466         fdev_set_autoclose(fdev, 0);
467         fdev_set_events(fdev, EPOLLIN);
468         fdev_set_callback(fdev, listen_callback, hsrv);
469
470         hsrv->httpd = httpd;
471         hsrv->fdev = fdev;
472         return 1;
473 }
474
475 void afb_hsrv_stop(struct afb_hsrv *hsrv)
476 {
477         if (hsrv->fdev != NULL) {
478                 fdev_unref(hsrv->fdev);
479                 hsrv->fdev = NULL;
480         }
481         if (hsrv->httpd != NULL)
482                 MHD_stop_daemon(hsrv->httpd);
483         hsrv->httpd = NULL;
484 }
485
486 struct afb_hsrv *afb_hsrv_create()
487 {
488         struct afb_hsrv *result = calloc(1, sizeof(struct afb_hsrv));
489         if (result != NULL)
490                 result->refcount = 1;
491         return result;
492 }
493
494 void afb_hsrv_put(struct afb_hsrv *hsrv)
495 {
496         assert(hsrv->refcount != 0);
497         if (!--hsrv->refcount) {
498                 afb_hsrv_stop(hsrv);
499                 free(hsrv);
500         }
501 }
502
503 static int hsrv_itf_connect(struct hsrv_itf *itf);
504
505 static void hsrv_itf_callback(void *closure, uint32_t revents, struct fdev *fdev)
506 {
507         struct hsrv_itf *itf = closure;
508         int fd, sts;
509         struct sockaddr addr;
510         socklen_t lenaddr;
511
512         if ((revents & EPOLLHUP) != 0) {
513                 ERROR("disconnection for server %s: %m", itf->uri);
514                 hsrv_itf_connect(itf);
515                 fdev_unref(fdev);
516         } else if ((revents & EPOLLIN) != 0) {
517                 lenaddr = (socklen_t)sizeof addr;
518                 fd = accept(fdev_fd(fdev), &addr, &lenaddr);
519                 if (fd < 0)
520                         ERROR("can't accept connection to %s: %m", itf->uri);
521                 else {
522                         sts = MHD_add_connection(itf->hsrv->httpd, fd, &addr, lenaddr);
523                         if (sts != MHD_YES) {
524                                 ERROR("can't add incoming connection to %s: %m", itf->uri);
525                                 close(fd);
526                         }
527                 }
528         }
529 }
530
531 static int hsrv_itf_connect(struct hsrv_itf *itf)
532 {
533         struct sockaddr addr;
534         socklen_t lenaddr;
535         char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
536         int rgni;
537
538         itf->fdev = afb_socket_open_fdev(itf->uri, 1);
539         if (!itf->fdev) {
540                 ERROR("can't create socket %s", itf->uri);
541                 return 0;
542         }
543         fdev_set_events(itf->fdev, EPOLLIN);
544         fdev_set_callback(itf->fdev, hsrv_itf_callback, itf);
545         memset(&addr, 0, sizeof addr);
546         lenaddr = (socklen_t)sizeof addr;
547         getsockname(fdev_fd(itf->fdev), &addr, &lenaddr);
548         if (addr.sa_family == AF_INET && !((struct sockaddr_in*)&addr)->sin_addr.s_addr) {
549                 strncpy(hbuf, "*", NI_MAXHOST);
550                 sprintf(sbuf, "%d", (int)ntohs(((struct sockaddr_in*)&addr)->sin_port));
551         } else {
552                 rgni = getnameinfo(&addr, lenaddr, hbuf, sizeof hbuf, sbuf, sizeof sbuf, NI_NUMERICSERV);
553                 if (rgni != 0) {
554                         ERROR("getnameinfo returned %d: %s", rgni, gai_strerror(rgni));
555                         hbuf[0] = sbuf[0] = '?';
556                         hbuf[1] = sbuf[1] = 0;
557                 }
558         }
559         NOTICE("Listening interface %s:%s", hbuf, sbuf);
560         return 1;
561 }
562
563 int afb_hsrv_add_interface(struct afb_hsrv *hsrv, const char *uri)
564 {
565         struct hsrv_itf *itf;
566
567         itf = malloc(sizeof *itf + strlen(uri));
568         if (itf == NULL)
569                 return -1;
570
571         itf->hsrv = hsrv;
572         itf->fdev = NULL;
573         strcpy(itf->uri, uri);
574         itf->next = hsrv->interfaces;
575         hsrv->interfaces = itf;
576         return hsrv_itf_connect(itf);
577 }
578
579 int afb_hsrv_add_interface_tcp(struct afb_hsrv *hsrv, const char *itf, uint16_t port)
580 {
581         int rc;
582         char buffer[1024];
583
584         if (itf == NULL) {
585                 itf = "*"; /* awaiting getifaddrs impl */
586         }
587         rc = snprintf(buffer, sizeof buffer, "tcp:%s:%d", itf, (int)port);
588         if (rc < 0 || rc >= (int)sizeof buffer) {
589                 if (rc > 0)
590                         errno = EINVAL;
591                 return 0;
592         }
593         return afb_hsrv_add_interface(hsrv, buffer);
594 }
595
596 #endif