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