fix file posting
[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"); /* TODO improve the path */
442         if (fname == NULL)
443                 return -1;
444
445         fd = mkostemp(fname, O_CLOEXEC|O_WRONLY);
446         if (fd < 0)
447                 free(fname);
448         else
449                 *path = fname;
450         return fd;
451 }
452
453 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
454 {
455         int fd;
456         ssize_t sz;
457         struct hreq_data *hdat = get_data(hreq, key, 1);
458
459 fprintf(stderr, "%s=%s %s=%s %s\n",key,hdat->key,file,hdat->value,hdat->path);
460         if (hdat->value == NULL) {
461                 hdat->value = strdup(file);
462                 if (hdat->value == NULL)
463                         return 0;
464                 fd = opentempfile(&hdat->path);
465         } else if (strcmp(hdat->value, file) || hdat->path == NULL) {
466                 return 0;
467         } else {
468                 fd = open(hdat->path, O_WRONLY|O_APPEND);
469         }
470         if (fd < 0)
471                 return 0;
472         while (size) {
473                 sz = write(fd, data, size);
474                 if (sz >= 0) {
475                         hdat->length += (size_t)sz;
476                         size -= (size_t)sz;
477                         data += sz;
478                 } else if (errno != EINTR)
479                         break;
480         }
481         close(fd);
482         return !size;
483 }
484
485 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
486 {
487         return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
488 }
489
490 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
491 {
492         struct hreq_data *hdat = get_data(hreq, name, 0);
493         if (hdat)
494                 return (struct afb_arg){
495                         .name = hdat->key,
496                         .value = hdat->value,
497                         .size = hdat->length,
498                         .path = hdat->path
499                 };
500                 
501         return (struct afb_arg){
502                 .name = name,
503                 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
504                 .size = 0,
505                 .path = NULL
506         };
507 }
508
509 struct iterdata
510 {
511         struct afb_hreq *hreq;
512         int (*iterator)(void *closure, struct afb_arg arg);
513         void *closure;
514 };
515
516 static int _iterargs_(struct iterdata *id, enum MHD_ValueKind kind, const char *key, const char *value)
517 {
518         if (get_data(id->hreq, key, 0))
519                 return 1;
520         return id->iterator(id->closure, (struct afb_arg){
521                 .name = key,
522                 .value = value,
523                 .size = 0,
524                 .path = NULL
525         });
526 }
527
528 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
529 {
530         struct iterdata id = { .hreq = hreq, .iterator = iterator, .closure = closure };
531         struct hreq_data *hdat = hreq->data;
532         while (hdat) {
533                 if (!iterator(closure, (struct afb_arg){
534                         .name = hdat->key,
535                         .value = hdat->value,
536                         .size = hdat->length,
537                         .path = hdat->path}))
538                         return;
539                 hdat = hdat->next;
540         }
541         MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, &id);
542 }
543
544 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
545 {
546         ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
547         return len ? : -1;
548 }
549
550 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
551 {
552         json_object *root, *request;
553         struct MHD_Response *response;
554
555         root = json_object_new_object();
556         json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
557         request = json_object_new_object();
558         json_object_object_add(root, "request", request);
559         json_object_object_add(request, "status", json_object_new_string(status));
560         if (info)
561                 json_object_object_add(request, "info", json_object_new_string(info));
562         if (resp)
563                 json_object_object_add(root, "response", resp);
564         if (hreq->context) {
565                 json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
566                 json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
567         }
568
569         response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
570         MHD_queue_response(hreq->connection, retcode, response);
571         MHD_destroy_response(response);
572 }
573
574 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
575 {
576         req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
577 }
578
579 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
580 {
581         req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
582 }
583
584 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
585 {
586         const char *uuid;
587
588         if (hreq->context == NULL) {
589                 uuid = afb_hreq_get_header(hreq, uuid_header);
590                 if (uuid == NULL)
591                         uuid = afb_hreq_get_argument(hreq, uuid_arg);
592                 if (uuid == NULL)
593                         uuid = afb_hreq_get_cookie(hreq, uuid_cookie);
594                 hreq->context = ctxClientGetForUuid(uuid);
595         }
596         return hreq->context;
597 }
598
599 static int req_session_create(struct afb_hreq *hreq)
600 {
601         struct AFB_clientCtx *context = afb_hreq_context(hreq);
602         if (context == NULL)
603                 return 0;
604         if (context->created)
605                 return 0;
606         return req_session_check(hreq, 1);
607 }
608
609 static int req_session_check(struct afb_hreq *hreq, int refresh)
610 {
611         const char *token;
612
613         struct AFB_clientCtx *context = afb_hreq_context(hreq);
614
615         if (context == NULL)
616                 return 0;
617
618         token = afb_hreq_get_header(hreq, token_header);
619         if (token == NULL)
620                 token = afb_hreq_get_argument(hreq, token_arg);
621         if (token == NULL)
622                 token = afb_hreq_get_cookie(hreq, token_cookie);
623         if (token == NULL)
624                 return 0;
625
626         if (!ctxTokenCheck (context, token))
627                 return 0;
628
629         if (refresh) {
630                 ctxTokenNew (context);
631         }
632
633         return 1;
634 }
635
636 static void req_session_close(struct afb_hreq *hreq)
637 {
638         struct AFB_clientCtx *context = afb_hreq_context(hreq);
639         if (context != NULL)
640                 ctxClientClose(context);
641 }
642
643
644