more simplification
[src/app-framework-binder.git] / src / afb-hreq.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 USE_MAGIC_MIME_TYPE
19 #define _GNU_SOURCE
20
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <assert.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <sys/stat.h>
28
29 #include <microhttpd.h>
30 #include <json.h>
31
32 #if defined(USE_MAGIC_MIME_TYPE)
33 #include <magic.h>
34 #endif
35
36 #include "afb-method.h"
37 #include "afb-websock.h"
38 #include "afb-apis.h"
39 #include "afb-req-itf.h"
40 #include "afb-hreq.h"
41 #include "session.h"
42 #include "verbose.h"
43
44 #define SIZE_RESPONSE_BUFFER   8000
45
46 static char empty_string[] = "";
47
48 static const char uuid_header[] = "x-afb-uuid";
49 static const char uuid_arg[] = "uuid";
50 static const char uuid_cookie[] = "uuid";
51
52 static const char token_header[] = "x-afb-token";
53 static const char token_arg[] = "token";
54 static const char token_cookie[] = "token";
55
56
57 struct hreq_data {
58         struct hreq_data *next;
59         char *key;
60         size_t length;
61         char *value;
62         char *path;
63 };
64
65 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name);
66 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure);
67 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info);
68 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info);
69 static int req_session_create(struct afb_hreq *hreq);
70 static int req_session_check(struct afb_hreq *hreq, int refresh);
71 static void req_session_close(struct afb_hreq *hreq);
72
73 static const struct afb_req_itf afb_hreq_itf = {
74         .get = (void*)req_get,
75         .iterate = (void*)req_iterate,
76         .fail = (void*)req_fail,
77         .success = (void*)req_success,
78         .session_create = (void*)req_session_create,
79         .session_check = (void*)req_session_check,
80         .session_close = (void*)req_session_close
81 };
82
83 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
84 {
85         struct hreq_data *data = hreq->data;
86         if (key == NULL)
87                 key = empty_string;
88         while (data != NULL) {
89                 if (!strcasecmp(data->key, key))
90                         return data;
91                 data = data->next;
92         }
93         if (create) {
94                 data = calloc(1, sizeof *data);
95                 if (data != NULL) {
96                         data->key = strdup(key);
97                         if (data->key == NULL) {
98                                 free(data);
99                                 data = NULL;
100                         } else {
101                                 data->next = hreq->data;
102                                 hreq->data = data;
103                         }
104                 }
105         }
106         return data;
107 }
108
109 /* a valid subpath is a relative path not looking deeper than root using .. */
110 static int validsubpath(const char *subpath)
111 {
112         int l = 0, i = 0;
113
114         while (subpath[i]) {
115                 switch (subpath[i++]) {
116                 case '.':
117                         if (!subpath[i])
118                                 break;
119                         if (subpath[i] == '/') {
120                                 i++;
121                                 break;
122                         }
123                         if (subpath[i++] == '.') {
124                                 if (!subpath[i]) {
125                                         if (--l < 0)
126                                                 return 0;
127                                         break;
128                                 }
129                                 if (subpath[i++] == '/') {
130                                         if (--l < 0)
131                                                 return 0;
132                                         break;
133                                 }
134                         }
135                 default:
136                         while (subpath[i] && subpath[i] != '/')
137                                 i++;
138                         l++;
139                 case '/':
140                         break;
141                 }
142         }
143         return 1;
144 }
145
146 #if defined(USE_MAGIC_MIME_TYPE)
147
148 #if !defined(MAGIC_DB)
149 #define MAGIC_DB "/usr/share/misc/magic.mgc"
150 #endif
151
152 static magic_t lazy_libmagic()
153 {
154         static int done = 0;
155         static magic_t result = NULL;
156
157         if (!done) {
158                 done = 1;
159                 /* MAGIC_MIME tells magic to return a mime of the file,
160                          but you can specify different things */
161                 if (verbosity)
162                         printf("Loading mimetype default magic database\n");
163
164                 result = magic_open(MAGIC_MIME_TYPE);
165                 if (result == NULL) {
166                         fprintf(stderr,"ERROR: unable to initialize magic library\n");
167                 }
168                 /* Warning: should not use NULL for DB
169                                 [libmagic bug wont pass efence check] */
170                 else if (magic_load(result, MAGIC_DB) != 0) {
171                         fprintf(stderr,"cannot load magic database - %s\n",
172                                         magic_error(result));
173                         magic_close(result);
174                         result = NULL;
175                 }
176         }
177
178         return result;
179 }
180
181 static const char *magic_mimetype_fd(int fd)
182 {
183         magic_t lib = lazy_libmagic();
184         return lib ? magic_descriptor(lib, fd) : NULL;
185 }
186
187 #endif
188
189 static const char *mimetype_fd_name(int fd, const char *filename)
190 {
191         const char *result = NULL;
192
193 #if defined(INFER_EXTENSION)
194         const char *extension = strrchr(filename, '.');
195         if (extension) {
196                 static const char *const known[][2] = {
197                         { ".js", "text/javascript" },
198                         { ".html", "text/html" },
199                         { NULL, NULL }
200                 };
201                 int i = 0;
202                 while (known[i][0]) {
203                         if (!strcasecmp(extension, known[i][0])) {
204                                 result = known[i][1];
205                                 break;
206                         }
207                         i++;
208                 }
209         }
210 #endif
211 #if defined(USE_MAGIC_MIME_TYPE)
212         if (result == NULL)
213                 result = magic_mimetype_fd(fd);
214 #endif
215         return result;
216 }
217
218 void afb_hreq_free(struct afb_hreq *hreq)
219 {
220         struct hreq_data *data;
221         if (hreq != NULL) {
222                 if (hreq->postform != NULL)
223                         MHD_destroy_post_processor(hreq->postform);
224                 for (data = hreq->data; data; data = hreq->data) {
225                         hreq->data = data->next;
226                         free(data->key);
227                         free(data->value);
228                         free(data);
229                 }
230                 ctxClientPut(hreq->context);
231                 free(hreq);
232         }
233 }
234
235 /*
236  * Removes the 'prefix' of 'length' from the tail of 'hreq'
237  * if and only if the prefix exists and is terminated by a leading
238  * slash
239  */
240 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
241 {
242         /* check the prefix ? */
243         if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
244             || strncasecmp(prefix, hreq->tail, length))
245                 return 0;
246
247         /* removes successives / */
248         while (length < hreq->lentail && hreq->tail[length + 1] == '/')
249                 length++;
250
251         /* update the tail */
252         hreq->lentail -= length;
253         hreq->tail += length;
254         return 1;
255 }
256
257 int afb_hreq_valid_tail(struct afb_hreq *hreq)
258 {
259         return validsubpath(hreq->tail);
260 }
261
262 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
263 {
264         char *buffer;
265         int length;
266         struct MHD_Response *response;
267
268         length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
269         if (length > 0)
270                 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
271         else {
272                 buffer = "<html><body>error</body></html>";
273                 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
274         }
275         if (!MHD_queue_response(hreq->connection, status, response))
276                 fprintf(stderr, "Failed to reply error code %u", status);
277         MHD_destroy_response(response);
278 }
279
280 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
281 {
282         int rc;
283         int fd;
284         unsigned int status;
285         struct stat st;
286         char etag[1 + 2 * sizeof(int)];
287         const char *inm;
288         struct MHD_Response *response;
289         const char *mimetype;
290
291         /* Opens the file or directory */
292         if (filename[0]) {
293                 fd = openat(dirfd, filename, O_RDONLY);
294                 if (fd < 0) {
295                         if (errno == ENOENT)
296                                 return 0;
297                         afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
298                         return 1;
299                 }
300         } else {
301                 fd = dup(dirfd);
302                 if (fd < 0) {
303                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
304                         return 1;
305                 }
306         }
307
308         /* Retrieves file's status */
309         if (fstat(fd, &st) != 0) {
310                 close(fd);
311                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
312                 return 1;
313         }
314
315         /* serve directory */
316         if (S_ISDIR(st.st_mode)) {
317                 static const char *indexes[] = { "index.html", NULL };
318                 int i = 0;
319                 rc = 0;
320                 while (indexes[i] != NULL) {
321                         if (faccessat(fd, indexes[i], R_OK, 0) == 0) {
322                                 if (hreq->url[hreq->lenurl - 1] != '/') {
323                                         /* the redirect is needed for reliability of relative path */
324                                         char *tourl = alloca(hreq->lenurl + 2);
325                                         memcpy(tourl, hreq->url, hreq->lenurl);
326                                         tourl[hreq->lenurl] = '/';
327                                         tourl[hreq->lenurl + 1] = 0;
328                                         rc = afb_hreq_redirect_to(hreq, tourl);
329                                 } else {
330                                         rc = afb_hreq_reply_file_if_exist(hreq, fd, indexes[i]);
331                                 }
332                                 break;
333                         }
334                         i++;
335                 }
336                 close(fd);
337                 return rc;
338         }
339
340         /* Don't serve special files */
341         if (!S_ISREG(st.st_mode)) {
342                 close(fd);
343                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
344                 return 1;
345         }
346
347         /* Check the method */
348         if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
349                 close(fd);
350                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
351                 return 1;
352         }
353
354         /* computes the etag */
355         sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
356
357         /* checks the etag */
358         inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
359         if (inm && 0 == strcmp(inm, etag)) {
360                 /* etag ok, return NOT MODIFIED */
361                 close(fd);
362                 if (verbosity)
363                         fprintf(stderr, "Not Modified: [%s]\n", filename);
364                 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
365                 status = MHD_HTTP_NOT_MODIFIED;
366         } else {
367                 /* check the size */
368                 if (st.st_size != (off_t) (size_t) st.st_size) {
369                         close(fd);
370                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
371                         return 1;
372                 }
373
374                 /* create the response */
375                 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
376                 status = MHD_HTTP_OK;
377
378                 /* set the type */
379                 mimetype = mimetype_fd_name(fd, filename);
380                 if (mimetype != NULL)
381                         MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
382         }
383
384         /* fills the value and send */
385         MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout);
386         MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
387         MHD_queue_response(hreq->connection, status, response);
388         MHD_destroy_response(response);
389         return 1;
390 }
391
392 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
393 {
394         int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
395         if (rc == 0)
396                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
397         return 1;
398 }
399
400 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
401 {
402         struct MHD_Response *response;
403
404         response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
405         MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION, url);
406         MHD_queue_response(hreq->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
407         MHD_destroy_response(response);
408         if (verbosity)
409                 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
410         return 1;
411 }
412
413 int afb_hreq_one_page_api_redirect(
414                 struct afb_hreq *hreq,
415                 void *data)
416 {
417         size_t plen;
418         char *url;
419
420         if (hreq->lentail >= 2 && hreq->tail[1] == '#')
421                 return 0;
422         /*
423          * Here we have for example:
424          *    url  = "/pre/dir/page"   lenurl = 13
425          *    tail =     "/dir/page"   lentail = 9
426          *
427          * We will produce "/pre/#!dir/page"
428          *
429          * Let compute plen that include the / at end (for "/pre/")
430          */
431         plen = hreq->lenurl - hreq->lentail + 1;
432         url = alloca(hreq->lenurl + 3);
433         memcpy(url, hreq->url, plen);
434         url[plen++] = '#';
435         url[plen++] = '!';
436         memcpy(&url[plen], &hreq->tail[1], hreq->lentail);
437         return afb_hreq_redirect_to(hreq, url);
438 }
439
440 int afb_hreq_websocket_switch(struct afb_hreq *hreq, void *data)
441 {
442         int later;
443
444         afb_hreq_context(hreq);
445         if (hreq->lentail != 0 || !afb_websock_check(hreq, &later))
446                 return 0;
447
448         if (!later) {
449                 struct afb_websock *ws = afb_websock_create(hreq);
450                 if (ws != NULL)
451                         hreq->upgrade = 1;
452         }
453         return 1;
454 }
455
456 int afb_hreq_rest_api(struct afb_hreq *hreq, void *data)
457 {
458         const char *api, *verb;
459         size_t lenapi, lenverb;
460         struct AFB_clientCtx *context;
461
462         api = &hreq->tail[strspn(hreq->tail, "/")];
463         lenapi = strcspn(api, "/");
464         verb = &api[lenapi];
465         verb = &verb[strspn(verb, "/")];
466         lenverb = strcspn(verb, "/");
467
468         if (!(*api && *verb && lenapi && lenverb))
469                 return 0;
470
471         context = afb_hreq_context(hreq);
472         return afb_apis_handle(afb_hreq_to_req(hreq), context, api, lenapi, verb, lenverb);
473 }
474
475 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
476 {
477         return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
478 }
479
480 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
481 {
482         struct hreq_data *data = get_data(hreq, name, 0);
483         return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
484 }
485
486 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
487 {
488         return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
489 }
490
491 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
492 {
493         void *p;
494         struct hreq_data *hdat = get_data(hreq, key, 1);
495         if (hdat->path != NULL) {
496                 return 0;
497         }
498         p = realloc(hdat->value, hdat->length + size + 1);
499         if (p == NULL) {
500                 return 0;
501         }
502         hdat->value = p;
503         memcpy(&hdat->value[hdat->length], data, size);
504         hdat->length += size;
505         hdat->value[hdat->length] = 0;
506         return 1;
507 }
508
509 static int opentempfile(char **path)
510 {
511         int fd;
512         char *fname;
513
514         fname = strdup("XXXXXX"); /* TODO improve the path */
515         if (fname == NULL)
516                 return -1;
517
518         fd = mkostemp(fname, O_CLOEXEC|O_WRONLY);
519         if (fd < 0)
520                 free(fname);
521         else
522                 *path = fname;
523         return fd;
524 }
525
526 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
527 {
528         int fd;
529         ssize_t sz;
530         struct hreq_data *hdat = get_data(hreq, key, 1);
531
532 fprintf(stderr, "%s=%s %s=%s %s\n",key,hdat->key,file,hdat->value,hdat->path);
533         if (hdat->value == NULL) {
534                 hdat->value = strdup(file);
535                 if (hdat->value == NULL)
536                         return 0;
537                 fd = opentempfile(&hdat->path);
538         } else if (strcmp(hdat->value, file) || hdat->path == NULL) {
539                 return 0;
540         } else {
541                 fd = open(hdat->path, O_WRONLY|O_APPEND);
542         }
543         if (fd < 0)
544                 return 0;
545         while (size) {
546                 sz = write(fd, data, size);
547                 if (sz >= 0) {
548                         hdat->length += (size_t)sz;
549                         size -= (size_t)sz;
550                         data += sz;
551                 } else if (errno != EINTR)
552                         break;
553         }
554         close(fd);
555         return !size;
556 }
557
558 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
559 {
560         return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
561 }
562
563 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
564 {
565         struct hreq_data *hdat = get_data(hreq, name, 0);
566         if (hdat)
567                 return (struct afb_arg){
568                         .name = hdat->key,
569                         .value = hdat->value,
570                         .size = hdat->length,
571                         .path = hdat->path
572                 };
573                 
574         return (struct afb_arg){
575                 .name = name,
576                 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
577                 .size = 0,
578                 .path = NULL
579         };
580 }
581
582 struct iterdata
583 {
584         struct afb_hreq *hreq;
585         int (*iterator)(void *closure, struct afb_arg arg);
586         void *closure;
587 };
588
589 static int _iterargs_(struct iterdata *id, enum MHD_ValueKind kind, const char *key, const char *value)
590 {
591         if (get_data(id->hreq, key, 0))
592                 return 1;
593         return id->iterator(id->closure, (struct afb_arg){
594                 .name = key,
595                 .value = value ? : "",
596                 .size = value ? strlen(value) : 0,
597                 .path = NULL
598         });
599 }
600
601 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
602 {
603         struct iterdata id = { .hreq = hreq, .iterator = iterator, .closure = closure };
604         struct hreq_data *hdat = hreq->data;
605         while (hdat) {
606                 if (!iterator(closure, (struct afb_arg){
607                         .name = hdat->key,
608                         .value = hdat->value,
609                         .size = hdat->length,
610                         .path = hdat->path}))
611                         return;
612                 hdat = hdat->next;
613         }
614         MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, &id);
615 }
616
617 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
618 {
619         ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
620         return len ? : -1;
621 }
622
623 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
624 {
625         json_object *root, *request;
626         struct MHD_Response *response;
627
628         root = json_object_new_object();
629         json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
630         request = json_object_new_object();
631         json_object_object_add(root, "request", request);
632         json_object_object_add(request, "status", json_object_new_string(status));
633         if (info)
634                 json_object_object_add(request, "info", json_object_new_string(info));
635         if (resp)
636                 json_object_object_add(root, "response", resp);
637         if (hreq->context) {
638                 json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
639                 json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
640         }
641
642         response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
643         MHD_queue_response(hreq->connection, retcode, response);
644         MHD_destroy_response(response);
645 }
646
647 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
648 {
649         req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
650 }
651
652 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
653 {
654         req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
655 }
656
657 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
658 {
659         const char *uuid;
660
661         if (hreq->context == NULL) {
662                 uuid = afb_hreq_get_header(hreq, uuid_header);
663                 if (uuid == NULL)
664                         uuid = afb_hreq_get_argument(hreq, uuid_arg);
665                 if (uuid == NULL)
666                         uuid = afb_hreq_get_cookie(hreq, uuid_cookie);
667                 hreq->context = ctxClientGetForUuid(uuid);
668         }
669         return hreq->context;
670 }
671
672 static int req_session_create(struct afb_hreq *hreq)
673 {
674         struct AFB_clientCtx *context = afb_hreq_context(hreq);
675         if (context == NULL)
676                 return 0;
677         if (context->created)
678                 return 0;
679         return req_session_check(hreq, 1);
680 }
681
682 static int req_session_check(struct afb_hreq *hreq, int refresh)
683 {
684         const char *token;
685
686         struct AFB_clientCtx *context = afb_hreq_context(hreq);
687
688         if (context == NULL)
689                 return 0;
690
691         token = afb_hreq_get_header(hreq, token_header);
692         if (token == NULL)
693                 token = afb_hreq_get_argument(hreq, token_arg);
694         if (token == NULL)
695                 token = afb_hreq_get_cookie(hreq, token_cookie);
696         if (token == NULL)
697                 return 0;
698
699         if (!ctxTokenCheck (context, token))
700                 return 0;
701
702         if (refresh) {
703                 ctxTokenNew (context);
704         }
705
706         return 1;
707 }
708
709 static void req_session_close(struct afb_hreq *hreq)
710 {
711         struct AFB_clientCtx *context = afb_hreq_context(hreq);
712         if (context != NULL)
713                 ctxClientClose(context);
714 }
715
716
717