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