refactoring req interface
[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-req-itf.h"
38 #include "afb-hreq.h"
39 #include "session.h"
40 #include "verbose.h"
41
42 #define SIZE_RESPONSE_BUFFER   8000
43
44 static char empty_string[] = "";
45
46 static const char uuid_header[] = "x-afb-uuid";
47 static const char uuid_arg[] = "uuid";
48 static const char uuid_cookie[] = "uuid";
49
50 static const char token_header[] = "x-afb-token";
51 static const char token_arg[] = "token";
52 static const char token_cookie[] = "token";
53
54
55 struct hreq_data {
56         struct hreq_data *next;
57         char *key;
58         size_t length;
59         char *value;
60         char *path;
61 };
62
63 static struct json_object *req_json(struct afb_hreq *hreq);
64 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name);
65 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info);
66 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info);
67 static const char *req_raw(struct afb_hreq *hreq, size_t *size);
68 static void req_send(struct afb_hreq *hreq, char *buffer, size_t size);
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         .json = (void*)req_json,
75         .get = (void*)req_get,
76         .success = (void*)req_success,
77         .fail = (void*)req_fail,
78         .raw = (void*)req_raw,
79         .send = (void*)req_send,
80         .session_create = (void*)req_session_create,
81         .session_check = (void*)req_session_check,
82         .session_close = (void*)req_session_close
83 };
84
85 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
86 {
87         struct hreq_data *data = hreq->data;
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 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
414 {
415         return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
416 }
417
418 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
419 {
420         struct hreq_data *data = get_data(hreq, name, 0);
421         return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
422 }
423
424 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
425 {
426         return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
427 }
428
429 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
430 {
431         void *p;
432         struct hreq_data *hdat = get_data(hreq, key, 1);
433         if (hdat->path != NULL) {
434                 return 0;
435         }
436         p = realloc(hdat->value, hdat->length + size + 1);
437         if (p == NULL) {
438                 return 0;
439         }
440         hdat->value = p;
441         memcpy(&hdat->value[hdat->length], data, size);
442         hdat->length += size;
443         hdat->value[hdat->length] = 0;
444         return 1;
445 }
446
447 static int opentempfile(char **path)
448 {
449         int fd;
450         char *fname;
451
452         fname = strdup("XXXXXX"); /* TODO improve the path */
453         if (fname == NULL)
454                 return -1;
455
456         fd = mkostemp(fname, O_CLOEXEC|O_WRONLY);
457         if (fd < 0)
458                 free(fname);
459         else
460                 *path = fname;
461         return fd;
462 }
463
464 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
465 {
466         int fd;
467         ssize_t sz;
468         struct hreq_data *hdat = get_data(hreq, key, 1);
469
470         if (hdat->value == NULL) {
471                 hdat->value = strdup(file);
472                 if (hdat->value == NULL)
473                         return 0;
474                 fd = opentempfile(&hdat->path);
475         } else if (strcmp(hdat->value, file) || hdat->path == NULL) {
476                 return 0;
477         } else {
478                 fd = open(hdat->path, O_WRONLY|O_APPEND);
479         }
480         if (fd < 0)
481                 return 0;
482         while (size) {
483                 sz = write(fd, data, size);
484                 if (sz >= 0) {
485                         hdat->length += (size_t)sz;
486                         size -= (size_t)sz;
487                         data += sz;
488                 } else if (errno != EINTR)
489                         break;
490         }
491         close(fd);
492         return !size;
493 }
494
495 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
496 {
497         return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
498 }
499
500 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
501 {
502         struct hreq_data *hdat = get_data(hreq, name, 0);
503         if (hdat)
504                 return (struct afb_arg){
505                         .name = hdat->key,
506                         .value = hdat->value,
507                         .path = hdat->path
508                 };
509                 
510         return (struct afb_arg){
511                 .name = name,
512                 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
513                 .path = NULL
514         };
515 }
516
517 static int _iterargs_(struct json_object *obj, enum MHD_ValueKind kind, const char *key, const char *value)
518 {
519         json_object_object_add(obj, key, value ? json_object_new_string(value) : NULL);
520         return 1;
521 }
522
523 static struct json_object *req_json(struct afb_hreq *hreq)
524 {
525         struct hreq_data *hdat;
526         struct json_object *obj, *val;
527
528         obj = hreq->json;
529         if (obj == NULL) {
530                 hreq->json = obj = json_object_new_object();
531                 if (obj == NULL) {
532                 } else {
533                         MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, obj);
534                         for (hdat = hreq->data ; hdat ; hdat = hdat->next) {
535                                 if (hdat->path == NULL)
536                                         val = hdat->value ? json_object_new_string(hdat->value) : NULL;
537                                 else {
538                                         val = json_object_new_object();
539                                         if (val == NULL) {
540                                         } else {
541                                                 json_object_object_add(val, "file", json_object_new_string(hdat->value));
542                                                 json_object_object_add(val, "path", json_object_new_string(hdat->path));
543                                         }
544                                 }
545                                 json_object_object_add(obj, hdat->key, val);
546                         }
547                 }
548         }
549         return obj;
550 }
551
552 static const char *req_raw(struct afb_hreq *hreq, size_t *size)
553 {
554         const char *result = json_object_get_string(req_json(hreq));
555         *size = result ? strlen(result) : 0;
556         return result;
557 }
558
559 static void req_send(struct afb_hreq *hreq, char *buffer, size_t size)
560 {
561         struct MHD_Response *response = MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_MUST_FREE);
562         MHD_queue_response(hreq->connection, MHD_HTTP_OK, response);
563         MHD_destroy_response(response);
564 }
565
566 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
567 {
568         ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
569         return len ? : -1;
570 }
571
572 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
573 {
574         json_object *root, *request;
575         struct MHD_Response *response;
576
577         root = json_object_new_object();
578         json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
579         request = json_object_new_object();
580         json_object_object_add(root, "request", request);
581         json_object_object_add(request, "status", json_object_new_string(status));
582         if (info)
583                 json_object_object_add(request, "info", json_object_new_string(info));
584         if (resp)
585                 json_object_object_add(root, "response", resp);
586         if (hreq->context) {
587                 json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
588                 json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
589         }
590
591         response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
592         MHD_queue_response(hreq->connection, retcode, response);
593         MHD_destroy_response(response);
594 }
595
596 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
597 {
598         req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
599 }
600
601 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
602 {
603         req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
604 }
605
606 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
607 {
608         const char *uuid;
609
610         if (hreq->context == NULL) {
611                 uuid = afb_hreq_get_header(hreq, uuid_header);
612                 if (uuid == NULL)
613                         uuid = afb_hreq_get_argument(hreq, uuid_arg);
614                 if (uuid == NULL)
615                         uuid = afb_hreq_get_cookie(hreq, uuid_cookie);
616                 hreq->context = ctxClientGetForUuid(uuid);
617         }
618         return hreq->context;
619 }
620
621 static int req_session_create(struct afb_hreq *hreq)
622 {
623         struct AFB_clientCtx *context = afb_hreq_context(hreq);
624         if (context == NULL)
625                 return 0;
626         if (context->created)
627                 return 0;
628         return req_session_check(hreq, 1);
629 }
630
631 static int req_session_check(struct afb_hreq *hreq, int refresh)
632 {
633         const char *token;
634
635         struct AFB_clientCtx *context = afb_hreq_context(hreq);
636
637         if (context == NULL)
638                 return 0;
639
640         token = afb_hreq_get_header(hreq, token_header);
641         if (token == NULL)
642                 token = afb_hreq_get_argument(hreq, token_arg);
643         if (token == NULL)
644                 token = afb_hreq_get_cookie(hreq, token_cookie);
645         if (token == NULL)
646                 return 0;
647
648         if (!ctxTokenCheck (context, token))
649                 return 0;
650
651         if (refresh) {
652                 ctxTokenNew (context);
653         }
654
655         return 1;
656 }
657
658 static void req_session_close(struct afb_hreq *hreq)
659 {
660         struct AFB_clientCtx *context = afb_hreq_context(hreq);
661         if (context != NULL)
662                 ctxClientClose(context);
663 }
664
665
666