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