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