new main loop in place
[src/app-framework-binder.git] / src / afb-hsrv.c
1 /*
2  * Copyright 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 <stdio.h>
21 #include <string.h>
22 #include <assert.h>
23 #include <poll.h>
24 #include <fcntl.h>
25 #include <sys/stat.h>
26
27 #include <microhttpd.h>
28
29 #include "local-def.h"
30 #include "afb-method.h"
31 #include "afb-hreq.h"
32 #include "afb-websock.h"
33 #include "afb-apis.h"
34 #include "afb-req-itf.h"
35 #include "verbose.h"
36 #include "utils-upoll.h"
37
38 #define JSON_CONTENT  "application/json"
39 #define FORM_CONTENT  MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
40
41
42 struct afb_hsrv_handler {
43         struct afb_hsrv_handler *next;
44         const char *prefix;
45         size_t length;
46         int (*handler) (struct afb_hreq *, void *);
47         void *data;
48         int priority;
49 };
50
51 struct afb_diralias {
52         const char *alias;
53         const char *directory;
54         size_t lendir;
55         int dirfd;
56 };
57
58 static struct upoll *upoll = NULL;
59
60 int afb_hreq_one_page_api_redirect(
61                 struct afb_hreq *hreq,
62                 void *data)
63 {
64         size_t plen;
65         char *url;
66
67         if (hreq->lentail >= 2 && hreq->tail[1] == '#')
68                 return 0;
69         /*
70          * Here we have for example:
71          *    url  = "/pre/dir/page"   lenurl = 13
72          *    tail =     "/dir/page"   lentail = 9
73          *
74          * We will produce "/pre/#!dir/page"
75          *
76          * Let compute plen that include the / at end (for "/pre/")
77          */
78         plen = hreq->lenurl - hreq->lentail + 1;
79         url = alloca(hreq->lenurl + 3);
80         memcpy(url, hreq->url, plen);
81         url[plen++] = '#';
82         url[plen++] = '!';
83         memcpy(&url[plen], &hreq->tail[1], hreq->lentail);
84         return afb_hreq_redirect_to(hreq, url);
85 }
86
87 static struct afb_hsrv_handler *new_handler(
88                 struct afb_hsrv_handler *head,
89                 const char *prefix,
90                 int (*handler) (struct afb_hreq *, void *),
91                 void *data,
92                 int priority)
93 {
94         struct afb_hsrv_handler *link, *iter, *previous;
95         size_t length;
96
97         /* get the length of the prefix without its leading / */
98         length = strlen(prefix);
99         while (length && prefix[length - 1] == '/')
100                 length--;
101
102         /* allocates the new link */
103         link = malloc(sizeof *link);
104         if (link == NULL)
105                 return NULL;
106
107         /* initialize it */
108         link->prefix = prefix;
109         link->length = length;
110         link->handler = handler;
111         link->data = data;
112         link->priority = priority;
113
114         /* adds it */
115         previous = NULL;
116         iter = head;
117         while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
118                 previous = iter;
119                 iter = iter->next;
120         }
121         link->next = iter;
122         if (previous == NULL)
123                 return link;
124         previous->next = link;
125         return head;
126 }
127
128 int afb_hsrv_add_handler(
129                 AFB_session * session,
130                 const char *prefix,
131                 int (*handler) (struct afb_hreq *, void *),
132                 void *data,
133                 int priority)
134 {
135         struct afb_hsrv_handler *head;
136
137         head = new_handler(session->handlers, prefix, handler, data, priority);
138         if (head == NULL)
139                 return 0;
140         session->handlers = head;
141         return 1;
142 }
143
144 static int afb_hreq_websocket_switch(struct afb_hreq *hreq, void *data)
145 {
146         int later;
147
148         afb_hreq_context(hreq);
149         if (hreq->lentail != 0 || !afb_websock_check(hreq, &later))
150                 return 0;
151
152         if (!later) {
153                 struct afb_websock *ws = afb_websock_create(hreq->connection);
154                 if (ws == NULL) {
155                         /* TODO */
156                 } else {
157                         /* TODO */
158                 }
159         }
160         return 1;
161 }
162
163 static int afb_hreq_rest_api(struct afb_hreq *hreq, void *data)
164 {
165         const char *api, *verb;
166         size_t lenapi, lenverb;
167         struct AFB_clientCtx *context;
168
169         api = &hreq->tail[strspn(hreq->tail, "/")];
170         lenapi = strcspn(api, "/");
171         verb = &api[lenapi];
172         verb = &verb[strspn(verb, "/")];
173         lenverb = strcspn(verb, "/");
174
175         if (!(*api && *verb && lenapi && lenverb))
176                 return 0;
177
178         context = afb_hreq_context(hreq);
179         return afb_apis_handle(afb_hreq_to_req(hreq), context, api, lenapi, verb, lenverb);
180 }
181
182 static int handle_alias(struct afb_hreq *hreq, void *data)
183 {
184         struct afb_diralias *da = data;
185
186         if (hreq->method != afb_method_get) {
187                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
188                 return 1;
189         }
190
191         if (!afb_hreq_valid_tail(hreq)) {
192                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
193                 return 1;
194         }
195
196         return afb_hreq_reply_file(hreq, da->dirfd, &hreq->tail[1]);
197 }
198
199 int afb_hsrv_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
200 {
201         struct afb_diralias *da;
202         int dirfd;
203
204         dirfd = open(alias, O_PATH|O_DIRECTORY);
205         if (dirfd < 0) {
206                 /* TODO message */
207                 return 0;
208         }
209         da = malloc(sizeof *da);
210         if (da != NULL) {
211                 da->alias = prefix;
212                 da->directory = alias;
213                 da->lendir = strlen(da->directory);
214                 da->dirfd = dirfd;
215                 if (afb_hsrv_add_handler(session, prefix, handle_alias, da, priority))
216                         return 1;
217                 free(da);
218         }
219         close(dirfd);
220         return 0;
221 }
222
223 void afb_hsrv_reply_error(struct MHD_Connection *connection, unsigned int status)
224 {
225         char *buffer;
226         int length;
227         struct MHD_Response *response;
228
229         length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
230         if (length > 0)
231                 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
232         else {
233                 buffer = "<html><body>error</body></html>";
234                 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
235         }
236         if (!MHD_queue_response(connection, status, response))
237                 fprintf(stderr, "Failed to reply error code %u", status);
238         MHD_destroy_response(response);
239 }
240
241 static int postproc(void *cls,
242                     enum MHD_ValueKind kind,
243                     const char *key,
244                     const char *filename,
245                     const char *content_type,
246                     const char *transfer_encoding,
247                     const char *data,
248                     uint64_t off,
249                     size_t size)
250 {
251         struct afb_hreq *hreq = cls;
252         if (filename != NULL)
253                 return afb_hreq_post_add_file(hreq, key, filename, data, size);
254         else
255                 return afb_hreq_post_add(hreq, key, data, size);
256 }
257
258 static int access_handler(
259                 void *cls,
260                 struct MHD_Connection *connection,
261                 const char *url,
262                 const char *methodstr,
263                 const char *version,
264                 const char *upload_data,
265                 size_t *upload_data_size,
266                 void **recordreq)
267 {
268         int rc;
269         struct afb_hreq *hreq;
270         enum afb_method method;
271         AFB_session *session;
272         struct afb_hsrv_handler *iter;
273         const char *type;
274
275         session = cls;
276         hreq = *recordreq;
277         if (hreq == NULL) {
278                 /* create the request */
279                 hreq = calloc(1, sizeof *hreq);
280                 if (hreq == NULL)
281                         goto internal_error;
282                 *recordreq = hreq;
283
284                 /* get the method */
285                 method = get_method(methodstr);
286                 method &= afb_method_get | afb_method_post;
287                 if (method == afb_method_none)
288                         goto bad_request;
289
290                 /* init the request */
291                 hreq->session = cls;
292                 hreq->connection = connection;
293                 hreq->method = method;
294                 hreq->version = version;
295                 hreq->tail = hreq->url = url;
296                 hreq->lentail = hreq->lenurl = strlen(url);
297
298                 /* init the post processing */
299                 if (method == afb_method_post) {
300                         type = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONTENT_TYPE);
301                         if (type == NULL) {
302                                 /* an empty post, let's process it as a get */
303                                 hreq->method = afb_method_get;
304                         } else if (strcasestr(type, FORM_CONTENT) != NULL) {
305                                 hreq->postform = MHD_create_post_processor (connection, 65500, postproc, hreq);
306                                 if (hreq->postform == NULL)
307                                         goto internal_error;
308                         } else if (strcasestr(type, JSON_CONTENT) == NULL) {
309                                 afb_hsrv_reply_error(connection, MHD_HTTP_UNSUPPORTED_MEDIA_TYPE);
310                                 return MHD_YES;
311                         }
312                 }
313         }
314
315         /* process further data */
316         if (*upload_data_size) {
317                 if (hreq->postform != NULL) {
318                         if (!MHD_post_process (hreq->postform, upload_data, *upload_data_size))
319                                 goto internal_error;
320                 } else {
321                         if (!afb_hreq_post_add(hreq, NULL, upload_data, *upload_data_size))
322                                 goto internal_error;
323                 }
324                 *upload_data_size = 0;
325                 return MHD_YES;         
326         }
327
328         /* flush the data */
329         afb_hreq_post_end(hreq);
330         if (hreq->postform != NULL) {
331                 rc = MHD_destroy_post_processor(hreq->postform);
332                 hreq->postform = NULL;
333                 if (rc == MHD_NO)
334                         goto bad_request;
335         }
336
337         /* search an handler for the request */
338         iter = session->handlers;
339         while (iter) {
340                 if (afb_hreq_unprefix(hreq, iter->prefix, iter->length)) {
341                         if (iter->handler(hreq, iter->data))
342                                 return MHD_YES;
343                         hreq->tail = hreq->url;
344                         hreq->lentail = hreq->lenurl;
345                 }
346                 iter = iter->next;
347         }
348
349         /* no handler */
350         afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
351         return MHD_YES;
352
353 bad_request:
354         afb_hsrv_reply_error(connection, MHD_HTTP_BAD_REQUEST);
355         return MHD_YES;
356
357 internal_error:
358         afb_hsrv_reply_error(connection, MHD_HTTP_INTERNAL_SERVER_ERROR);
359         return MHD_YES;
360 }
361
362 /* Because of POST call multiple time requestApi we need to free POST handle here */
363 static void end_handler(void *cls, struct MHD_Connection *connection, void **recordreq,
364                         enum MHD_RequestTerminationCode toe)
365 {
366         struct afb_hreq *hreq;
367
368         hreq = *recordreq;
369
370         afb_hreq_free(hreq);
371 }
372
373 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
374 {
375         return MHD_YES;
376 }
377
378 #if defined(USE_MAGIC_MIME_TYPE)
379
380 #if !defined(MAGIC_DB)
381 #define MAGIC_DB "/usr/share/misc/magic.mgc"
382 #endif
383
384 static int init_lib_magic (AFB_session *session)
385 {
386         /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
387         if (verbosity)
388                 printf("Loading mimetype default magic database\n");
389
390         session->magic = magic_open(MAGIC_MIME_TYPE);
391         if (session->magic == NULL) {
392                 fprintf(stderr,"ERROR: unable to initialize magic library\n");
393                 return 0;
394         }
395
396         /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
397         if (magic_load(session->magic, MAGIC_DB) != 0) {
398                 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
399                 magic_close(session->magic);
400                 session->magic = NULL;
401                 return 0;
402         }
403
404         return 1;
405 }
406 #endif
407
408 static int my_default_init(AFB_session * session)
409 {
410         int idx;
411
412         if (!afb_hsrv_add_handler(session, session->config->rootapi, afb_hreq_websocket_switch, NULL, 20))
413                 return 0;
414
415         if (!afb_hsrv_add_handler(session, session->config->rootapi, afb_hreq_rest_api, NULL, 10))
416                 return 0;
417
418         for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
419                 if (!afb_hsrv_add_alias (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
420                         return 0;
421
422         if (!afb_hsrv_add_alias(session, "", session->config->rootdir, -10))
423                 return 0;
424
425         if (!afb_hsrv_add_handler(session, session->config->rootbase, afb_hreq_one_page_api_redirect, NULL, -20))
426                 return 0;
427
428 #if defined(USE_MAGIC_MIME_TYPE)
429         /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
430         init_lib_magic (session);
431 #endif
432
433         return 1;
434 }
435
436 /* infinite loop */
437 static void hsrv_handle_event(struct MHD_Daemon *httpd)
438 {
439         MHD_run(httpd);
440 }
441
442 int afb_hsrv_start(AFB_session * session)
443 {
444         struct MHD_Daemon *httpd;
445         const union MHD_DaemonInfo *info;
446
447         if (!my_default_init(session)) {
448                 printf("Error: initialisation of httpd failed");
449                 return 0;
450         }
451
452         if (verbosity) {
453                 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
454                 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
455         }
456
457         httpd = MHD_start_daemon(
458                 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG | MHD_USE_SUSPEND_RESUME,
459                 (uint16_t) session->config->httpdPort,  /* port */
460                 new_client_handler, NULL,       /* Tcp Accept call back + extra attribute */
461                 access_handler, session,        /* Http Request Call back + extra attribute */
462                 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
463                 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15,        /* 15 seconds */
464                 MHD_OPTION_END);        /* options-end */
465
466         if (httpd == NULL) {
467                 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
468                 return 0;
469         }
470
471         info = MHD_get_daemon_info(httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
472         if (info == NULL) {
473                 MHD_stop_daemon(httpd);
474                 fprintf(stderr, "Error: httpStart no pollfd");
475                 return 0;
476         }
477
478         upoll = upoll_open(info->listen_fd, httpd);
479         if (upoll == NULL) {
480                 MHD_stop_daemon(httpd);
481                 fprintf(stderr, "Error: connection to upoll of httpd failed");
482                 return 0;
483         }
484         upoll_on_readable(upoll, (void*)hsrv_handle_event);
485
486         session->httpd = httpd;
487         return 1;
488 }
489
490 void afb_hsrv_stop(AFB_session * session)
491 {
492         if (upoll)
493                 upoll_close(upoll);
494         upoll = NULL;
495         if (session->httpd != NULL)
496                 MHD_stop_daemon(session->httpd);
497         session->httpd = NULL;
498 }
499