fix SEGFLT when unhendled request
[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) {
242                 if (hreq->upgrade)
243                         MHD_suspend_connection (connection);
244                 afb_hreq_unref(hreq);
245         }
246 }
247
248 void run_micro_httpd(struct afb_hsrv *hsrv)
249 {
250         if (hsrv->in_run != 0)
251                 hsrv->in_run = 2;
252         else {
253                 sd_event_source_set_io_events(hsrv->evsrc, 0);
254                 do {
255                         hsrv->in_run = 1;
256                         MHD_run(hsrv->httpd);
257                 } while(hsrv->in_run == 2);
258                 hsrv->in_run = 0;
259                 sd_event_source_set_io_events(hsrv->evsrc, EPOLLIN);
260         }
261 }
262
263 static int io_event_callback(sd_event_source *src, int fd, uint32_t revents, void *hsrv)
264 {
265         run_micro_httpd(hsrv);
266         return 0;
267 }
268
269 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
270 {
271         return MHD_YES;
272 }
273
274 static struct hsrv_handler *new_handler(
275                 struct hsrv_handler *head,
276                 const char *prefix,
277                 int (*handler) (struct afb_hreq *, void *),
278                 void *data,
279                 int priority)
280 {
281         struct hsrv_handler *link, *iter, *previous;
282         size_t length;
283
284         /* get the length of the prefix without its leading / */
285         length = strlen(prefix);
286         while (length && prefix[length - 1] == '/')
287                 length--;
288
289         /* allocates the new link */
290         link = malloc(sizeof *link);
291         if (link == NULL)
292                 return NULL;
293
294         /* initialize it */
295         link->prefix = prefix;
296         link->length = length;
297         link->handler = handler;
298         link->data = data;
299         link->priority = priority;
300
301         /* adds it */
302         previous = NULL;
303         iter = head;
304         while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
305                 previous = iter;
306                 iter = iter->next;
307         }
308         link->next = iter;
309         if (previous == NULL)
310                 return link;
311         previous->next = link;
312         return head;
313 }
314
315 static int handle_alias(struct afb_hreq *hreq, void *data)
316 {
317         int rc;
318         struct hsrv_alias *da = data;
319         struct locale_search *search;
320
321         if (hreq->method != afb_method_get) {
322                 if (da->relax)
323                         return 0;
324                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
325                 return 1;
326         }
327
328         search = locale_root_search(da->root, hreq->lang, 0);
329         rc = afb_hreq_reply_locale_file_if_exist(hreq, search, &hreq->tail[1]);
330         locale_search_unref(search);
331         if (rc == 0) {
332                 if (da->relax)
333                         return 0;
334                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
335         }
336         return 1;
337 }
338
339 int afb_hsrv_add_handler(
340                 struct afb_hsrv *hsrv,
341                 const char *prefix,
342                 int (*handler) (struct afb_hreq *, void *),
343                 void *data,
344                 int priority)
345 {
346         struct hsrv_handler *head;
347
348         head = new_handler(hsrv->handlers, prefix, handler, data, priority);
349         if (head == NULL)
350                 return 0;
351         hsrv->handlers = head;
352         return 1;
353 }
354
355 int afb_hsrv_add_alias_root(struct afb_hsrv *hsrv, const char *prefix, struct locale_root *root, int priority, int relax)
356 {
357         struct hsrv_alias *da;
358
359         da = malloc(sizeof *da);
360         if (da != NULL) {
361                 da->root = root;
362                 da->relax = relax;
363                 if (afb_hsrv_add_handler(hsrv, prefix, handle_alias, da, priority)) {
364                         locale_root_addref(root);
365                         return 1;
366                 }
367                 free(da);
368         }
369         return 0;
370 }
371
372 int afb_hsrv_add_alias(struct afb_hsrv *hsrv, const char *prefix, int dirfd, const char *alias, int priority, int relax)
373 {
374         struct locale_root *root;
375         int rc;
376
377         root = locale_root_create_at(dirfd, alias);
378         if (root == NULL) {
379                 ERROR("can't connect to directory %s: %m", alias);
380                 rc = 0;
381         } else {
382                 rc = afb_hsrv_add_alias_root(hsrv, prefix, root, priority, relax);
383                 locale_root_unref(root);
384         }
385         return rc;
386 }
387
388 int afb_hsrv_set_cache_timeout(struct afb_hsrv *hsrv, int duration)
389 {
390         int rc;
391         char *dur;
392
393         rc = asprintf(&dur, "%d", duration);
394         if (rc < 0)
395                 return 0;
396
397         free(hsrv->cache_to);
398         hsrv->cache_to = dur;
399         return 1;
400 }
401
402 int afb_hsrv_start(struct afb_hsrv *hsrv, uint16_t port, unsigned int connection_timeout)
403 {
404         sd_event_source *evsrc;
405         int rc;
406         struct MHD_Daemon *httpd;
407         const union MHD_DaemonInfo *info;
408
409         httpd = MHD_start_daemon(
410                 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
411                 port,                           /* port */
412                 new_client_handler, NULL,       /* Tcp Accept call back + extra attribute */
413                 access_handler, hsrv,   /* Http Request Call back + extra attribute */
414                 MHD_OPTION_NOTIFY_COMPLETED, end_handler, hsrv,
415                 MHD_OPTION_CONNECTION_TIMEOUT, connection_timeout,
416                 MHD_OPTION_END);        /* options-end */
417
418         if (httpd == NULL) {
419                 ERROR("httpStart invalid httpd port: %d", (int)port);
420                 return 0;
421         }
422
423         info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
424         if (info == NULL) {
425                 MHD_stop_daemon(httpd);
426                 ERROR("httpStart no pollfd");
427                 return 0;
428         }
429
430         rc = sd_event_add_io(afb_common_get_event_loop(), &evsrc, info->listen_fd, EPOLLIN, io_event_callback, hsrv);
431         if (rc < 0) {
432                 MHD_stop_daemon(httpd);
433                 errno = -rc;
434                 ERROR("connection to events for httpd failed");
435                 return 0;
436         }
437
438         hsrv->httpd = httpd;
439         hsrv->evsrc = evsrc;
440         return 1;
441 }
442
443 void afb_hsrv_stop(struct afb_hsrv *hsrv)
444 {
445         if (hsrv->evsrc != NULL) {
446                 sd_event_source_unref(hsrv->evsrc);
447                 hsrv->evsrc = NULL;
448         }
449         if (hsrv->httpd != NULL)
450                 MHD_stop_daemon(hsrv->httpd);
451         hsrv->httpd = NULL;
452 }
453
454 struct afb_hsrv *afb_hsrv_create()
455 {
456         struct afb_hsrv *result = calloc(1, sizeof(struct afb_hsrv));
457         if (result != NULL)
458                 result->refcount = 1;
459         return result;
460 }
461
462 void afb_hsrv_put(struct afb_hsrv *hsrv)
463 {
464         assert(hsrv->refcount != 0);
465         if (!--hsrv->refcount) {
466                 afb_hsrv_stop(hsrv);
467                 free(hsrv);
468         }
469 }
470