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