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