315de12839690fb6dbfe14052da5d200fa4efef1
[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_hreq_post {
29         const char *upload_data;
30         size_t *upload_data_size;
31 };
32
33 struct afb_hreq {
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_hreq **recorder;
42         int (*post_handler) (struct afb_hreq *, struct afb_hreq_post *);
43         int (*post_completed) (struct afb_hreq *, struct afb_hreq_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_hreq *, struct afb_hreq_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_hreq *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_hreq *request)
118 {
119         return validsubpath(request->tail);
120 }
121
122 void afb_req_reply_error(struct afb_hreq *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_hreq *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_hreq *request, struct afb_hreq_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_hreq *, struct afb_hreq_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_hreq *, struct afb_hreq_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_hreq *request, struct afb_hreq_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_hreq *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_hreq *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 struct afb_diralias {
332         const char *alias;
333         const char *directory;
334         size_t lendir;
335         int dirfd;
336 };
337
338 static int handle_alias(struct afb_hreq *request, struct afb_hreq_post *post, void *data)
339 {
340         char *path;
341         struct afb_diralias *da = data;
342         size_t lenalias;
343
344         if (request->method != afb_method_get) {
345                 afb_req_reply_error(request, MHD_HTTP_METHOD_NOT_ALLOWED);
346                 return 1;
347         }
348
349         if (!validsubpath(request->tail)) {
350                 afb_req_reply_error(request, MHD_HTTP_FORBIDDEN);
351                 return 1;
352         }
353
354         return afb_req_reply_file(request, da->dirfd, &request->tail[request->lentail + 1]);
355 }
356
357 int afb_req_add_alias(AFB_session * session, const char *prefix, const char *alias, int priority)
358 {
359         struct afb_diralias *da;
360         int dirfd;
361
362         dirfd = open(alias, O_PATH|O_DIRECTORY);
363         if (dirfd < 0) {
364                 /* TODO message */
365                 return 0;
366         }
367         da = malloc(sizeof *da);
368         if (da != NULL) {
369                 da->alias = prefix;
370                 da->directory = alias;
371                 da->lendir = strlen(da->directory);
372                 da->dirfd = dirfd;
373                 if (afb_req_add_handler(session, prefix, handle_alias, (void *)alias, priority))
374                         return 1;
375                 free(da);
376         }
377         close(dirfd);
378         return 0;
379 }
380
381 static int my_default_init(AFB_session * session)
382 {
383         int idx;
384
385         if (!afb_req_add_handler(session, session->config->rootapi, relay_to_doRestApi, NULL, 1))
386                 return 0;
387
388         for (idx = 0; session->config->aliasdir[idx].url != NULL; idx++)
389                 if (!afb_req_add_alias
390                     (session, session->config->aliasdir[idx].url, session->config->aliasdir[idx].path, 0))
391                         return 0;
392
393         if (!afb_req_add_alias(session, "", session->config->rootdir, -10))
394                 return 0;
395
396         if (!afb_req_add_handler(session, session->config->rootbase, afb_request_one_page_api_redirect, NULL, -20))
397                 return 0;
398
399         return 1;
400 }
401
402 static int access_handler(
403                 void *cls,
404                 struct MHD_Connection *connection,
405                 const char *url,
406                 const char *methodstr,
407                 const char *version,
408                 const char *upload_data,
409                 size_t * upload_data_size,
410                 void **recorder)
411 {
412         struct afb_hreq_post post;
413         struct afb_hreq request;
414         enum afb_method method;
415         AFB_session *session;
416         struct afb_req_handler *iter;
417
418         session = cls;
419         post.upload_data = upload_data;
420         post.upload_data_size = upload_data_size;
421
422 #if 0
423         struct afb_hreq *previous;
424
425         previous = *recorder;
426         if (previous) {
427                 assert((void **)previous->recorder == recorder);
428                 assert(previous->session == session);
429                 assert(previous->connection == connection);
430                 assert(previous->method == get_method(methodstr));
431                 assert(previous->url == url);
432
433                 /* TODO */
434 /*
435                 assert(previous->post_handler != NULL);
436                 previous->post_handler(previous, &post);
437                 return MHD_NO;
438 */
439         }
440 #endif
441
442         method = get_method(methodstr);
443         if (method == afb_method_none) {
444                 afb_req_reply_error(&request, MHD_HTTP_BAD_REQUEST);
445                 return MHD_YES;
446         }
447
448         /* init the request */
449         request.session = cls;
450         request.connection = connection;
451         request.method = method;
452         request.tail = request.url = url;
453         request.lentail = request.lenurl = strlen(url);
454         request.recorder = (struct afb_hreq **)recorder;
455         request.post_handler = NULL;
456         request.post_completed = NULL;
457         request.post_data = NULL;
458
459         /* search an handler for the request */
460         iter = session->handlers;
461         while (iter) {
462                 if (afb_req_unprefix(&request, iter->prefix, iter->length)) {
463                         if (iter->handler(&request, &post, iter->data))
464                                 return MHD_YES;
465                         request.tail = request.url;
466                         request.lentail = request.lenurl;
467                 }
468                 iter = iter->next;
469         }
470
471         /* no handler */
472         afb_req_reply_error(&request, method != afb_method_get ? MHD_HTTP_BAD_REQUEST : MHD_HTTP_NOT_FOUND);
473         return MHD_YES;
474 }
475
476 /* Because of POST call multiple time requestApi we need to free POST handle here */
477 static void end_handler(void *cls, struct MHD_Connection *connection, void **con_cls,
478                         enum MHD_RequestTerminationCode toe)
479 {
480         AFB_PostHandle *posthandle = *con_cls;
481
482         /* if post handle was used let's free everything */
483         if (posthandle != NULL)
484                 endPostRequest(posthandle);
485 }
486
487 static int new_client_handler(void *cls, const struct sockaddr *addr, socklen_t addrlen)
488 {
489         return MHD_YES;
490 }
491
492 #if defined(USE_MAGIC_MIME_TYPE)
493
494 #if !defined(MAGIC_DB)
495 #define MAGIC_DB "/usr/share/misc/magic.mgc"
496 #endif
497
498 static int init_lib_magic (AFB_session *session)
499 {
500         /* MAGIC_MIME tells magic to return a mime of the file, but you can specify different things */
501         if (verbose)
502                 printf("Loading mimetype default magic database\n");
503
504         session->magic = magic_open(MAGIC_MIME_TYPE);
505         if (session->magic == NULL) {
506                 fprintf(stderr,"ERROR: unable to initialize magic library\n");
507                 return 0;
508         }
509
510         /* Warning: should not use NULL for DB [libmagic bug wont pass efence check] */
511         if (magic_load(session->magic, MAGIC_DB) != 0) {
512                 fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
513 /*
514                 magic_close(session->magic);
515                 session->magic = NULL;
516                 return 0;
517 */
518         }
519
520         return 1;
521 }
522 #endif
523
524 AFB_error httpdStart(AFB_session * session)
525 {
526
527         if (!my_default_init(session)) {
528                 printf("Error: initialisation of httpd failed");
529                 return AFB_FATAL;
530         }
531
532         /* Initialise Client Session Hash Table */
533         ctxStoreInit(CTX_NBCLIENTS);
534
535 #if defined(USE_MAGIC_MIME_TYPE)
536         /*TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)] */
537         init_lib_magic (session);
538 #endif
539
540         if (verbose) {
541                 printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
542                 printf("AFB:notice Browser URL= http:/*localhost:%d\n", session->config->httpdPort);
543         }
544
545         session->httpd = MHD_start_daemon(
546                 MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_TCP_FASTOPEN | MHD_USE_DEBUG,
547                 (uint16_t) session->config->httpdPort,  /* port */
548                 new_client_handler, NULL,       /* Tcp Accept call back + extra attribute */
549                 access_handler, session,        /* Http Request Call back + extra attribute */
550                 MHD_OPTION_NOTIFY_COMPLETED, end_handler, session,
551                 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)15,        /* 15 seconds */
552                 MHD_OPTION_END);        /* options-end */
553
554         if (session->httpd == NULL) {
555                 printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
556                 return AFB_FATAL;
557         }
558         return AFB_SUCCESS;
559 }
560
561 /* infinite loop */
562 AFB_error httpdLoop(AFB_session * session)
563 {
564         int count = 0;
565         const union MHD_DaemonInfo *info;
566         struct pollfd pfd;
567
568         info = MHD_get_daemon_info(session->httpd, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
569         if (info == NULL) {
570                 printf("Error: httpLoop no pollfd");
571                 goto error;
572         }
573         pfd.fd = info->listen_fd;
574         pfd.events = POLLIN;
575
576         if (verbose)
577                 fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
578         while (TRUE) {
579                 if (verbose)
580                         fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
581                 poll(&pfd, 1, 15000);   /* 15 seconds (as above timeout when starting) */
582                 MHD_run(session->httpd);
583         }
584
585  error:
586         /* should never return from here */
587         return AFB_FATAL;
588 }
589
590 int httpdStatus(AFB_session * session)
591 {
592         return MHD_run(session->httpd);
593 }
594
595 void httpdStop(AFB_session * session)
596 {
597         MHD_stop_daemon(session->httpd);
598 }