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