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