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