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