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