afb-method: creation
[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
27
28 struct afb_req_post {
29         const char *upload_data;
30         size_t *upload_data_size;
31 };
32
33 struct afb_req {
34         AFB_session *session;
35         struct MHD_Connection *connection;
36         enum afb_method method;
37         const char *url;
38         size_t lenurl;
39         const char *tail;
40         size_t lentail;
41         struct afb_req **recorder;
42         int (*post_handler) (struct afb_req *, struct afb_req_post *);
43         int (*post_completed) (struct afb_req *, struct afb_req_post *);
44         void *post_data;
45 };
46
47 struct afb_req_handler {
48         struct afb_req_handler *next;
49         const char *prefix;
50         size_t length;
51         int (*handler) (struct afb_req *, struct afb_req_post *, void *);
52         void *data;
53         int priority;
54 };
55
56 static char empty_string[1] = "";
57
58 /* a valid subpath is a relative path not looking deeper than root using .. */
59 static int validsubpath(const char *subpath)
60 {
61         int l = 0, i = 0;
62
63         while (subpath[i]) {
64                 switch (subpath[i++]) {
65                 case '.':
66                         if (!subpath[i])
67                                 break;
68                         if (subpath[i] == '/') {
69                                 i++;
70                                 break;
71                         }
72                         if (subpath[i++] == '.') {
73                                 if (!subpath[i]) {
74                                         if (--l < 0)
75                                                 return 0;
76                                         break;
77                                 }
78                                 if (subpath[i++] == '/') {
79                                         if (--l < 0)
80                                                 return 0;
81                                         break;
82                                 }
83                         }
84                 default:
85                         while (subpath[i] && subpath[i] != '/')
86                                 i++;
87                         l++;
88                 case '/':
89                         break;
90                 }
91         }
92         return 1;
93 }
94
95 /*
96  * Removes the 'prefix' of 'length' frome the tail of 'request'
97  * if and only if the prefix exists and is terminated by a leading
98  * slash
99  */
100 int afb_req_unprefix(struct afb_req *request, const char *prefix, size_t length)
101 {
102         /* check the prefix ? */
103         if (length > request->lentail || (request->tail[length] && request->tail[length] != '/')
104             || memcmp(prefix, request->tail, length))
105                 return 0;
106
107         /* removes successives / */
108         while (length < request->lentail && request->tail[length + 1] == '/')
109                 length++;
110
111         /* update the tail */
112         request->lentail -= length;
113         request->tail += length;
114         return 1;
115 }
116
117 int afb_req_valid_tail(struct afb_req *request)
118 {
119         return validsubpath(request->tail);
120 }
121
122 void afb_req_reply_error(struct afb_req *request, unsigned int status)
123 {
124         char *buffer;
125         int length;
126         struct MHD_Response *response;
127
128         length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
129         if (length > 0)
130                 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
131         else {
132                 buffer = "<html><body>error</body></html>";
133                 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
134         }
135         if (!MHD_queue_response(request->connection, status, response))
136                 fprintf(stderr, "Failed to reply error code %u", status);
137         MHD_destroy_response(response);
138 }
139
140 int afb_request_redirect_to(struct afb_req *request, const char *url)
141 {
142         struct MHD_Response *response;
143
144         response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
145         MHD_add_response_header(response, "Location", url);
146         MHD_queue_response(request->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
147         MHD_destroy_response(response);
148         if (verbose)
149                 fprintf(stderr, "redirect from [%s] to [%s]\n", request->url, url);
150         return 1;
151 }
152
153 int afb_request_one_page_api_redirect(struct afb_req *request, struct afb_req_post *post, void *data)
154 {
155         size_t plen;
156         char *url;
157
158         if (request->lentail >= 2 && request->tail[1] == '#')
159                 return 0;
160         /*
161          * Here we have for example:
162          *    url  = "/pre/dir/page"   lenurl = 13
163          *    tail =     "/dir/page"   lentail = 9
164          *
165          * We will produce "/pre/#!dir/page"
166          *
167          * Let compute plen that include the / at end (for "/pre/")
168          */
169         plen = request->lenurl - request->lentail + 1;
170         url = alloca(request->lenurl + 3);
171         memcpy(url, request->url, plen);
172         url[plen++] = '#';
173         url[plen++] = '!';
174         memcpy(&url[plen], &request->tail[1], request->lentail);
175         return afb_request_redirect_to(request, url);
176 }
177
178 struct afb_req_handler *afb_req_handler_new(struct afb_req_handler *head, const char *prefix,
179                                             int (*handler) (struct afb_req *, struct afb_req_post *, void *),
180                                             void *data, int priority)
181 {
182         struct afb_req_handler *link, *iter, *previous;
183         size_t length;
184
185         /* get the length of the prefix without its leading / */
186         length = strlen(prefix);
187         while (length && prefix[length - 1] == '/')
188                 length--;
189
190         /* allocates the new link */
191         link = malloc(sizeof *link);
192         if (link == NULL)
193                 return NULL;
194
195         /* initialize it */
196         link->prefix = prefix;
197         link->length = length;
198         link->handler = handler;
199         link->data = data;
200         link->priority = priority;
201
202         /* adds it */
203         previous = NULL;
204         iter = head;
205         while (iter && (priority < iter->priority || (priority == iter->priority && length <= iter->length))) {
206                 previous = iter;
207                 iter = iter->next;
208         }
209         link->next = iter;
210         if (previous == NULL)
211                 return link;
212         previous->next = link;
213         return head;
214 }
215
216 int afb_req_add_handler(AFB_session * session, const char *prefix,
217                         int (*handler) (struct afb_req *, struct afb_req_post *, void *), void *data, int priority)
218 {
219         struct afb_req_handler *head;
220
221         head = afb_req_handler_new(session->handlers, prefix, handler, data, priority);
222         if (head == NULL)
223                 return 0;
224         session->handlers = head;
225         return 1;
226 }
227
228 static int relay_to_doRestApi(struct afb_req *request, struct afb_req_post *post, void *data)
229 {
230         return doRestApi(request->connection, request->session, &request->tail[1], get_method_name(request->method),
231                          post->upload_data, post->upload_data_size, (void **)request->recorder);
232 }
233
234 static int afb_req_reply_file_if_exist(struct afb_req *request, int dirfd, const char *filename)
235 {
236         int rc;
237         int fd;
238         unsigned int status;
239         struct stat st;
240         char etag[1 + 2 * sizeof(int)];
241         const char *inm;
242         struct MHD_Response *response;
243
244         /* Opens the file or directory */
245         fd = openat(dirfd, filename, O_RDONLY);
246         if (fd < 0) {
247                 if (errno == ENOENT)
248                         return 0;
249                 afb_req_reply_error(request, MHD_HTTP_FORBIDDEN);
250                 return 1;
251         }
252
253         /* Retrieves file's status */
254         if (fstat(fd, &st) != 0) {
255                 close(fd);
256                 afb_req_reply_error(request, MHD_HTTP_INTERNAL_SERVER_ERROR);
257                 return 1;
258         }
259
260         /* Don't serve directory */
261         if (S_ISDIR(st.st_mode)) {
262                 rc = afb_req_reply_file_if_exist(request, fd, "index.html");
263                 close(fd);
264                 return rc;
265         }
266
267         /* Don't serve special files */
268         if (!S_ISREG(st.st_mode)) {
269                 close(fd);
270                 afb_req_reply_error(request, MHD_HTTP_FORBIDDEN);
271                 return 1;
272         }
273
274         /* Check the method */
275         if ((request->method & (afb_method_get | afb_method_head)) == 0) {
276                 close(fd);
277                 afb_req_reply_error(request, MHD_HTTP_METHOD_NOT_ALLOWED);
278                 return 1;
279         }
280
281         /* computes the etag */
282         sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
283
284         /* checks the etag */
285         inm = MHD_lookup_connection_value(request->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
286         if (inm && 0 == strcmp(inm, etag)) {
287                 /* etag ok, return NOT MODIFIED */
288                 close(fd);
289                 if (verbose)
290                         fprintf(stderr, "Not Modified: [%s]\n", filename);
291                 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
292                 status = MHD_HTTP_NOT_MODIFIED;
293         } else {
294                 /* check the size */
295                 if (st.st_size != (off_t) (size_t) st.st_size) {
296                         close(fd);
297                         afb_req_reply_error(request, MHD_HTTP_INTERNAL_SERVER_ERROR);
298                         return 1;
299                 }
300
301                 /* create the response */
302                 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
303                 status = MHD_HTTP_OK;
304
305 #if defined(USE_MAGIC_MIME_TYPE)
306                 /* set the type */
307                 if (request->session->magic) {
308                         const char *mimetype = magic_descriptor(request->session->magic, fd);
309                         if (mimetype != NULL)
310                                 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
311                 }
312 #endif
313         }
314
315         /* fills the value and send */
316         MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, request->session->cacheTimeout);
317         MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
318         MHD_queue_response(request->connection, status, response);
319         MHD_destroy_response(response);
320         return 1;
321 }
322
323 static int afb_req_reply_file(struct afb_req *request, int dirfd, const char *filename)
324 {
325         int rc = afb_req_reply_file_if_exist(request, dirfd, filename);
326         if (rc == 0)
327                 afb_req_reply_error(request, MHD_HTTP_NOT_FOUND);
328         return 1;
329 }
330
331 static int handle_alias(struct afb_req *request, struct afb_req_post *post, void *data)
332 {
333         char *path;
334         const char *alias = data;
335         size_t lenalias;
336
337         if (request->method != afb_method_get) {
338                 afb_req_reply_error(request, MHD_HTTP_METHOD_NOT_ALLOWED);
339                 return 1;
340         }
341
342         if (!validsubpath(request->tail)) {
343                 afb_req_reply_error(request, MHD_HTTP_FORBIDDEN);
344                 return 1;
345         }
346
347         lenalias = strlen(alias);
348         path = alloca(lenalias + request->lentail + 1);
349         memcpy(path, alias, lenalias);
350         memcpy(&path[lenalias], request->tail, request->lentail + 1);
351         return afb_req_reply_file(request, AT_FDCWD, path);
352 }
353
354 int afb_req_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
355 {
356         return afb_req_add_handler(session, prefix, handle_alias, (void *)alias, priority);
357 }
358
359 static int my_default_init(AFB_session * session)
360 {
361         int idx;
362
363         if (!afb_req_add_handler(session, session->config->rootapi, relay_to_doRestApi, NULL, 1))
364                 return 0;
365
366         for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
367                 if (!afb_req_add_alias
368                     (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
369                         return 0;
370
371         if (!afb_req_add_alias(session, "", session->config->rootdir, -10))
372                 return 0;
373
374         if (!afb_req_add_handler(session, session->config->rootbase, afb_request_one_page_api_redirect, NULL, -20))
375                 return 0;
376
377         return 1;
378 }
379
380 static int access_handler(void *cls,
381                           struct MHD_Connection *connection,
382                           const char *url,
383                           const char *methodstr,
384                           const char *version, const char *upload_data, size_t * upload_data_size, void **recorder)
385 {
386         struct afb_req_post post;
387         struct afb_req request;
388         enum afb_method method;
389         AFB_session *session;
390         struct afb_req_handler *iter;
391
392         session = cls;
393         post.upload_data = upload_data;
394         post.upload_data_size = upload_data_size;
395
396 #if 0
397         struct afb_req *previous;
398
399         previous = *recorder;
400         if (previous) {
401                 assert((void **)previous->recorder == recorder);
402                 assert(previous->session == session);
403                 assert(previous->connection == connection);
404                 assert(previous->method == get_method(methodstr));
405                 assert(previous->url == url);
406
407                 /* TODO */
408 /*
409                 assert(previous->post_handler != NULL);
410                 previous->post_handler(previous, &post);
411                 return MHD_NO;
412 */
413         }
414 #endif
415
416         method = get_method(methodstr);
417         if (method == afb_method_none) {
418                 afb_req_reply_error(&request, MHD_HTTP_BAD_REQUEST);
419                 return MHD_YES;
420         }
421
422         /* init the request */
423         request.session = cls;
424         request.connection = connection;
425         request.method = method;
426         request.tail = request.url = url;
427         request.lentail = request.lenurl = strlen(url);
428         request.recorder = (struct afb_req **)recorder;
429         request.post_handler = NULL;
430         request.post_completed = NULL;
431         request.post_data = NULL;
432
433         /* search an handler for the request */
434         iter = session->handlers;
435         while (iter) {
436                 if (afb_req_unprefix(&request, iter->prefix, iter->length)) {
437                         if (iter->handler(&request, &post, iter->data))
438                                 return MHD_YES;
439                         request.tail = request.url;
440                         request.lentail = request.lenurl;
441                 }
442                 iter = iter->next;
443         }
444
445         /* no handler */
446         afb_req_reply_error(&request, method != afb_method_get ? MHD_HTTP_BAD_REQUEST : MHD_HTTP_NOT_FOUND);
447         return MHD_YES;
448 }
449
450 /* Because of POST call multiple time requestApi we need to free POST handle here */
451 static void end_handler(void *cls, struct MHD_Connection *connection, void **con_cls,
452                         enum MHD_RequestTerminationCode toe)
453 {
454         AFB_PostHandle *posthandle = *con_cls;
455
456         /* if post handle was used let's free everything */
457         if (posthandle != NULL)
458                 endPostRequest(posthandle);
459 }
460
461 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
462 {
463         return MHD_YES;
464 }
465
466 #if defined(USE_MAGIC_MIME_TYPE)
467
468 #if !defined(MAGIC_DB)
469 #define MAGIC_DB "/usr/share/misc/magic.mgc"
470 #endif
471
472 static int init_lib_magic (AFB_session *session)
473 {
474         /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
475         if (verbose)
476                 printf("Loading mimetype default magic database\n");
477
478         session->magic = magic_open(MAGIC_MIME_TYPE);
479         if (session->magic == NULL) {
480                 fprintf(stderr,"ERROR: unable to initialize magic library\n");
481                 return 0;
482         }
483
484         /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
485         if (magic_load(session->magic, MAGIC_DB) != 0) {
486                 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
487 /*
488                 magic_close(session->magic);
489                 session->magic = NULL;
490                 return 0;
491 */
492         }
493
494         return 1;
495 }
496 #endif
497
498 AFB_error httpdStart(AFB_session * session)
499 {
500
501         if (!my_default_init(session)) {
502                 printf("Error: initialisation of httpd failed");
503                 return AFB_FATAL;
504         }
505
506         /* Initialise Client Session Hash Table */
507         ctxStoreInit(CTX_NBCLIENTS);
508
509 #if defined(USE_MAGIC_MIME_TYPE)
510         /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
511         init_lib_magic (session);
512 #endif
513
514         if (verbose) {
515                 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
516                 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
517         }
518
519         session->httpd = MHD_start_daemon(
520                 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG,
521                 (uint16_t) session->config->httpdPort,  /* port */
522                 new_client_handler, NULL,       /* Tcp Accept call back + extra attribute */
523                 access_handler, session,        /* Http Request Call back + extra attribute */
524                 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
525                 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15,        /* 15 seconds */
526                 MHD_OPTION_END);        /* options-end */
527
528         if (session->httpd == NULL) {
529                 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
530                 return AFB_FATAL;
531         }
532         return AFB_SUCCESS;
533 }
534
535 /* infinite loop */
536 AFB_error httpdLoop(AFB_session * session)
537 {
538         int count = 0;
539         const union MHD_DaemonInfo *info;
540         struct pollfd pfd;
541
542         info = MHD_get_daemon_info(session->httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
543         if (info == NULL) {
544                 printf("Error: httpLoop no pollfd");
545                 goto error;
546         }
547         pfd.fd = info->listen_fd;
548         pfd.events = POLLIN;
549
550         if (verbose)
551                 fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
552         while (TRUE) {
553                 if (verbose)
554                         fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
555                 poll(&pfd, 1, 15000);   /* 15 seconds (as above timeout when starting) */
556                 MHD_run(session->httpd);
557         }
558
559  error:
560         /* should never return from here */
561         return AFB_FATAL;
562 }
563
564 int httpdStatus(AFB_session * session)
565 {
566         return MHD_run(session->httpd);
567 }
568
569 void httpdStop(AFB_session * session)
570 {
571         MHD_stop_daemon(session->httpd);
572 }