improves file 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                 if (hreq->url[hreq->lenurl - 1] != '/') {
316                         /* the redirect is needed for reliability of relative path */
317                         char *tourl = alloca(hreq->lenurl + 2);
318                         memcpy(tourl, hreq->url, hreq->lenurl);
319                         tourl[hreq->lenurl] = '/';
320                         tourl[hreq->lenurl + 1] = 0;
321                         rc = afb_hreq_redirect_to(hreq, tourl);
322                 } else {
323                         rc = afb_hreq_reply_file_if_exist(hreq, fd, "index.html");
324                 }
325                 close(fd);
326                 return rc;
327         }
328
329         /* Don't serve special files */
330         if (!S_ISREG(st.st_mode)) {
331                 close(fd);
332                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
333                 return 1;
334         }
335
336         /* Check the method */
337         if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
338                 close(fd);
339                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
340                 return 1;
341         }
342
343         /* computes the etag */
344         sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
345
346         /* checks the etag */
347         inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
348         if (inm && 0 == strcmp(inm, etag)) {
349                 /* etag ok, return NOT MODIFIED */
350                 close(fd);
351                 if (verbosity)
352                         fprintf(stderr, "Not Modified: [%s]\n", filename);
353                 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
354                 status = MHD_HTTP_NOT_MODIFIED;
355         } else {
356                 /* check the size */
357                 if (st.st_size != (off_t) (size_t) st.st_size) {
358                         close(fd);
359                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
360                         return 1;
361                 }
362
363                 /* create the response */
364                 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
365                 status = MHD_HTTP_OK;
366
367                 /* set the type */
368                 mimetype = mimetype_fd_name(fd, filename);
369                 if (mimetype != NULL)
370                         MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
371         }
372
373         /* fills the value and send */
374         MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, hreq->session->cacheTimeout);
375         MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
376         MHD_queue_response(hreq->connection, status, response);
377         MHD_destroy_response(response);
378         return 1;
379 }
380
381 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
382 {
383         int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
384         if (rc == 0)
385                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
386         return 1;
387 }
388
389 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
390 {
391         struct MHD_Response *response;
392
393         response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
394         MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION, url);
395         MHD_queue_response(hreq->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
396         MHD_destroy_response(response);
397         if (verbosity)
398                 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
399         return 1;
400 }
401
402 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
403 {
404         return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
405 }
406
407 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
408 {
409         struct hreq_data *data = get_data(hreq, name, 0);
410         return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
411 }
412
413 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
414 {
415         return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
416 }
417
418 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
419 {
420         void *p;
421         struct hreq_data *hdat = get_data(hreq, key, 1);
422         if (hdat->path != NULL) {
423                 return 0;
424         }
425         p = realloc(hdat->value, hdat->length + size + 1);
426         if (p == NULL) {
427                 return 0;
428         }
429         hdat->value = p;
430         memcpy(&hdat->value[hdat->length], data, size);
431         hdat->length += size;
432         hdat->value[hdat->length] = 0;
433         return 1;
434 }
435
436 static int opentempfile(char **path)
437 {
438         int fd;
439         char *fname;
440
441         fname = strdup("XXXXXX");
442         if (fname == NULL)
443                 return -1;
444
445         fd = mkostemp(fname, O_CLOEXEC);
446         if (fd < 0)
447                 free(fname);
448         return fd;
449 }
450
451 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
452 {
453         int fd;
454         ssize_t sz;
455         struct hreq_data *hdat = get_data(hreq, key, 1);
456
457         if (hdat->value == NULL) {
458                 hdat->value = strdup(file);
459                 if (hdat->value == NULL)
460                         return 0;
461                 fd = opentempfile(&hdat->path);
462         } else if (strcmp(hdat->value, file) || hdat->path == NULL) {
463                 return 0;
464         } else {
465                 fd = open(hdat->path, O_WRONLY|O_APPEND);
466         }
467         if (fd < 0)
468                 return 0;
469         while (size) {
470                 sz = write(fd, data, size);
471                 if (sz >= 0) {
472                         hdat->length += (size_t)sz;
473                         size -= (size_t)sz;
474                         data += sz;
475                 } else if (errno != EINTR)
476                         break;
477         }
478         close(fd);
479         return !size;
480 }
481
482 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
483 {
484         return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
485 }
486
487 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
488 {
489         struct hreq_data *hdat = get_data(hreq, name, 0);
490         if (hdat)
491                 return (struct afb_arg){
492                         .name = hdat->key,
493                         .value = hdat->value,
494                         .size = hdat->length,
495                         .path = hdat->path
496                 };
497                 
498         return (struct afb_arg){
499                 .name = name,
500                 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
501                 .size = 0,
502                 .path = NULL
503         };
504 }
505
506 struct iterdata
507 {
508         struct afb_hreq *hreq;
509         int (*iterator)(void *closure, struct afb_arg arg);
510         void *closure;
511 };
512
513 static int _iterargs_(struct iterdata *id, enum MHD_ValueKind kind, const char *key, const char *value)
514 {
515         if (get_data(id->hreq, key, 0))
516                 return 1;
517         return id->iterator(id->closure, (struct afb_arg){
518                 .name = key,
519                 .value = value,
520                 .size = 0,
521                 .path = NULL
522         });
523 }
524
525 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
526 {
527         struct iterdata id = { .hreq = hreq, .iterator = iterator, .closure = closure };
528         struct hreq_data *hdat = hreq->data;
529         while (hdat) {
530                 if (!iterator(closure, (struct afb_arg){
531                         .name = hdat->key,
532                         .value = hdat->value,
533                         .size = hdat->length,
534                         .path = hdat->path}))
535                         return;
536                 hdat = hdat->next;
537         }
538         MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, &id);
539 }
540
541 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
542 {
543         ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
544         return len ? : -1;
545 }
546
547 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
548 {
549         json_object *root, *request;
550         struct MHD_Response *response;
551
552         root = json_object_new_object();
553         json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
554         request = json_object_new_object();
555         json_object_object_add(root, "request", request);
556         json_object_object_add(request, "status", json_object_new_string(status));
557         if (info)
558                 json_object_object_add(request, "info", json_object_new_string(info));
559         if (resp)
560                 json_object_object_add(root, "response", resp);
561         if (hreq->context) {
562                 json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
563                 json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
564         }
565
566         response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
567         MHD_queue_response(hreq->connection, retcode, response);
568         MHD_destroy_response(response);
569 }
570
571 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
572 {
573         req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
574 }
575
576 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
577 {
578         req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
579 }
580
581 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
582 {
583         const char *uuid;
584
585         if (hreq->context == NULL) {
586                 uuid = afb_hreq_get_header(hreq, uuid_header);
587                 if (uuid == NULL)
588                         uuid = afb_hreq_get_argument(hreq, uuid_arg);
589                 if (uuid == NULL)
590                         uuid = afb_hreq_get_cookie(hreq, uuid_cookie);
591                 hreq->context = ctxClientGetForUuid(uuid);
592         }
593         return hreq->context;
594 }
595
596 static int req_session_create(struct afb_hreq *hreq)
597 {
598         struct AFB_clientCtx *context = afb_hreq_context(hreq);
599         if (context == NULL)
600                 return 0;
601         if (context->created)
602                 return 0;
603         return req_session_check(hreq, 1);
604 }
605
606 static int req_session_check(struct afb_hreq *hreq, int refresh)
607 {
608         const char *token;
609
610         struct AFB_clientCtx *context = afb_hreq_context(hreq);
611
612         if (context == NULL)
613                 return 0;
614
615         token = afb_hreq_get_header(hreq, token_header);
616         if (token == NULL)
617                 token = afb_hreq_get_argument(hreq, token_arg);
618         if (token == NULL)
619                 token = afb_hreq_get_cookie(hreq, token_cookie);
620         if (token == NULL)
621                 return 0;
622
623         if (!ctxTokenCheck (context, token))
624                 return 0;
625
626         if (refresh) {
627                 ctxTokenNew (context);
628         }
629
630         return 1;
631 }
632
633 static void req_session_close(struct afb_hreq *hreq)
634 {
635         struct AFB_clientCtx *context = afb_hreq_context(hreq);
636         if (context != NULL)
637                 ctxClientClose(context);
638 }
639
640
641