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