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