locale-root: improves the API
[src/app-framework-binder.git] / src / afb-hsrv.c
1 /*
2  * Copyright (C) 2016 "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                         reply_error(connection, MHD_HTTP_BAD_REQUEST);
122                         return MHD_YES;
123                 }
124
125                 /* create the request */
126                 hreq = calloc(1, sizeof *hreq);
127                 if (hreq == NULL) {
128                         reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
129                         return MHD_YES;
130                 }
131
132                 /* init the request */
133                 hreq->refcount = 1;
134                 hreq->hsrv = hsrv;
135                 hreq->cacheTimeout = hsrv->cache_to;
136                 hreq->reqid = ++global_reqids;
137                 hreq->scanned = 0;
138                 hreq->suspended = 0;
139                 hreq->replied = 0;
140                 hreq->connection = connection;
141                 hreq->method = method;
142                 hreq->version = version;
143                 hreq->lang = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_ACCEPT_LANGUAGE);
144                 hreq->tail = hreq->url = url;
145                 hreq->lentail = hreq->lenurl = strlen(url);
146                 *recordreq = hreq;
147
148                 /* init the post processing */
149                 if (method == afb_method_post) {
150                         type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
151                         if (type == NULL) {
152                                 /* an empty post, let's process it as a get */
153                                 hreq->method = afb_method_get;
154                         } else if (strcasestr(type, FORM_CONTENT) != NULL) {
155                                 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
156                                 if (hreq->postform == NULL)
157                                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
158                                 return MHD_YES;
159                         } else if (strcasestr(type, JSON_CONTENT) != NULL) {
160                                 return MHD_YES;
161                         } else {
162                                 afb_hreq_reply_error(hreq, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
163                                 return MHD_YES;
164                         }
165                 }
166         }
167
168         /* process further data */
169         if (*upload_data_size) {
170                 if (hreq->postform != NULL) {
171                         if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size)) {
172                                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
173                                 return MHD_YES;
174                         }
175                 } else {
176                         if (!afb_hreq_post_add(hreq, "", upload_data, *upload_data_size)) {
177                                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
178                                 return MHD_YES;
179                         }
180                 }
181                 *upload_data_size = 0;
182                 return MHD_YES;
183         }
184
185         /* flush the data */
186         if (hreq->postform != NULL) {
187                 rc = MHD_destroy_post_processor(hreq->postform);
188                 hreq->postform = NULL;
189                 if (rc == MHD_NO) {
190                         afb_hreq_reply_error(hreq, MHD_HTTP_BAD_REQUEST);
191                         return MHD_YES;
192                 }
193         }
194
195         if (hreq->scanned != 0) {
196                 if (hreq->replied == 0 && hreq->suspended == 0) {
197                         MHD_suspend_connection (connection);
198                         hreq->suspended = 1;
199                 }
200                 return MHD_YES;
201         }
202
203         /* search an handler for the request */
204         hreq->scanned = 1;
205         iter = hsrv->handlers;
206         while (iter) {
207                 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
208                         if (iter->handler(hreq, iter->data)) {
209                                 if (hreq->replied == 0 && hreq->suspended == 0) {
210                                         MHD_suspend_connection (connection);
211                                         hreq->suspended = 1;
212                                 }
213                                 return MHD_YES;
214                         }
215                         hreq->tail = hreq->url;
216                         hreq->lentail = hreq->lenurl;
217                 }
218                 iter = iter->next;
219         }
220
221         /* no handler */
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->upgrade)
234                 MHD_suspend_connection (connection);
235         afb_hreq_unref(hreq);
236 }
237
238 void run_micro_httpd(struct afb_hsrv *hsrv)
239 {
240         if (hsrv->in_run != 0)
241                 hsrv->in_run = 2;
242         else {
243                 sd_event_source_set_io_events(hsrv->evsrc, 0);
244                 do {
245                         hsrv->in_run = 1;
246                         MHD_run(hsrv->httpd);
247                 } while(hsrv->in_run == 2);
248                 hsrv->in_run = 0;
249                 sd_event_source_set_io_events(hsrv->evsrc, EPOLLIN);
250         }
251 }
252
253 static int io_event_callback(sd_event_source *src, int fd, uint32_t revents, void *hsrv)
254 {
255         run_micro_httpd(hsrv);
256         return 0;
257 }
258
259 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
260 {
261         return MHD_YES;
262 }
263
264 static struct hsrv_handler *new_handler(
265                 struct hsrv_handler *head,
266                 const char *prefix,
267                 int (*handler) (struct afb_hreq *, void *),
268                 void *data,
269                 int priority)
270 {
271         struct hsrv_handler *link, *iter, *previous;
272         size_t length;
273
274         /* get the length of the prefix without its leading / */
275         length = strlen(prefix);
276         while (length && prefix[length - 1] == '/')
277                 length--;
278
279         /* allocates the new link */
280         link = malloc(sizeof *link);
281         if (link == NULL)
282                 return NULL;
283
284         /* initialize it */
285         link->prefix = prefix;
286         link->length = length;
287         link->handler = handler;
288         link->data = data;
289         link->priority = priority;
290
291         /* adds it */
292         previous = NULL;
293         iter = head;
294         while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
295                 previous = iter;
296                 iter = iter->next;
297         }
298         link->next = iter;
299         if (previous == NULL)
300                 return link;
301         previous->next = link;
302         return head;
303 }
304
305 static int handle_alias(struct afb_hreq *hreq, void *data)
306 {
307         int rc;
308         struct hsrv_alias *da = data;
309         struct locale_search *search;
310
311         if (hreq->method != afb_method_get) {
312                 if (da->relax)
313                         return 0;
314                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
315                 return 1;
316         }
317
318         search = locale_root_search(da->root, hreq->lang, 0);
319         rc = afb_hreq_reply_locale_file_if_exist(hreq, search, &hreq->tail[1]);
320         locale_search_unref(search);
321         if (rc == 0) {
322                 if (da->relax)
323                         return 0;
324                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
325         }
326         return 1;
327 }
328
329 int afb_hsrv_add_handler(
330                 struct afb_hsrv *hsrv,
331                 const char *prefix,
332                 int (*handler) (struct afb_hreq *, void *),
333                 void *data,
334                 int priority)
335 {
336         struct hsrv_handler *head;
337
338         head = new_handler(hsrv->handlers, prefix, handler, data, priority);
339         if (head == NULL)
340                 return 0;
341         hsrv->handlers = head;
342         return 1;
343 }
344
345 int afb_hsrv_add_alias_root(struct afb_hsrv *hsrv, const char *prefix, struct locale_root *root, int priority, int relax)
346 {
347         struct hsrv_alias *da;
348
349         da = malloc(sizeof *da);
350         if (da != NULL) {
351                 da->root = root;
352                 da->relax = relax;
353                 if (afb_hsrv_add_handler(hsrv, prefix, handle_alias, da, priority)) {
354                         locale_root_addref(root);
355                         return 1;
356                 }
357                 free(da);
358         }
359         return 0;
360 }
361
362 int afb_hsrv_add_alias(struct afb_hsrv *hsrv, const char *prefix, const char *alias, int priority, int relax)
363 {
364         struct locale_root *root;
365         int rc;
366
367         root = locale_root_create_at(AT_FDCWD, alias);
368         if (root == NULL) {
369                 /* TODO message */
370                 rc = 0;
371         } else {
372                 rc = afb_hsrv_add_alias_root(hsrv, prefix, root, priority, relax);
373                 locale_root_unref(root);
374         }
375         return rc;
376 }
377
378 int afb_hsrv_set_cache_timeout(struct afb_hsrv *hsrv, int duration)
379 {
380         int rc;
381         char *dur;
382
383         rc = asprintf(&dur, "%d", duration);
384         if (rc < 0)
385                 return 0;
386
387         free(hsrv->cache_to);
388         hsrv->cache_to = dur;
389         return 1;
390 }
391
392 int afb_hsrv_start(struct afb_hsrv *hsrv, uint16_t port, unsigned int connection_timeout)
393 {
394         sd_event_source *evsrc;
395         int rc;
396         struct MHD_Daemon *httpd;
397         const union MHD_DaemonInfo *info;
398
399         httpd = MHD_start_daemon(
400                 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
401                 port,                           /* port */
402                 new_client_handler, NULL,       /* Tcp Accept call back + extra attribute */
403                 access_handler, hsrv,   /* Http Request Call back + extra attribute */
404                 MHD_OPTION_NOTIFY_COMPLETED, end_handler, hsrv,
405                 MHD_OPTION_CONNECTION_TIMEOUT, connection_timeout,
406                 MHD_OPTION_END);        /* options-end */
407
408         if (httpd == NULL) {
409                 ERROR("httpStart invalid httpd port: %d", (int)port);
410                 return 0;
411         }
412
413         info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
414         if (info == NULL) {
415                 MHD_stop_daemon(httpd);
416                 ERROR("httpStart no pollfd");
417                 return 0;
418         }
419
420         rc = sd_event_add_io(afb_common_get_event_loop(), &evsrc, info->listen_fd, EPOLLIN, io_event_callback, hsrv);
421         if (rc < 0) {
422                 MHD_stop_daemon(httpd);
423                 errno = -rc;
424                 ERROR("connection to events for httpd failed");
425                 return 0;
426         }
427
428         hsrv->httpd = httpd;
429         hsrv->evsrc = evsrc;
430         return 1;
431 }
432
433 void afb_hsrv_stop(struct afb_hsrv *hsrv)
434 {
435         if (hsrv->evsrc != NULL) {
436                 sd_event_source_unref(hsrv->evsrc);
437                 hsrv->evsrc = NULL;
438         }
439         if (hsrv->httpd != NULL)
440                 MHD_stop_daemon(hsrv->httpd);
441         hsrv->httpd = NULL;
442 }
443
444 struct afb_hsrv *afb_hsrv_create()
445 {
446         struct afb_hsrv *result = calloc(1, sizeof(struct afb_hsrv));
447         if (result != NULL)
448                 result->refcount = 1;
449         return result;
450 }
451
452 void afb_hsrv_put(struct afb_hsrv *hsrv)
453 {
454         assert(hsrv->refcount != 0);
455         if (!--hsrv->refcount) {
456                 afb_hsrv_stop(hsrv);
457                 free(hsrv);
458         }
459 }
460