Merge branch 'master' of github.com:iotbzh/afb-daemon
[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         int file;
59         size_t length;
60         char *value;
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
188
189 void afb_hreq_free(struct afb_hreq *hreq)
190 {
191         struct hreq_data *data;
192         if (hreq != NULL) {
193                 if (hreq->postform != NULL)
194                         MHD_destroy_post_processor(hreq->postform);
195                 for (data = hreq->data; data; data = hreq->data) {
196                         hreq->data = data->next;
197                         free(data->key);
198                         free(data->value);
199                         free(data);
200                 }
201                 ctxClientPut(hreq->context);
202                 free(hreq);
203         }
204 }
205
206 /*
207  * Removes the 'prefix' of 'length' from the tail of 'hreq'
208  * if and only if the prefix exists and is terminated by a leading
209  * slash
210  */
211 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
212 {
213         /* check the prefix ? */
214         if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
215             || strncasecmp(prefix, hreq->tail, length))
216                 return 0;
217
218         /* removes successives / */
219         while (length < hreq->lentail && hreq->tail[length + 1] == '/')
220                 length++;
221
222         /* update the tail */
223         hreq->lentail -= length;
224         hreq->tail += length;
225         return 1;
226 }
227
228 int afb_hreq_valid_tail(struct afb_hreq *hreq)
229 {
230         return validsubpath(hreq->tail);
231 }
232
233 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
234 {
235         char *buffer;
236         int length;
237         struct MHD_Response *response;
238
239         length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
240         if (length > 0)
241                 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
242         else {
243                 buffer = "<html><body>error</body></html>";
244                 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
245         }
246         if (!MHD_queue_response(hreq->connection, status, response))
247                 fprintf(stderr, "Failed to reply error code %u", status);
248         MHD_destroy_response(response);
249 }
250
251 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
252 {
253         int rc;
254         int fd;
255         unsigned int status;
256         struct stat st;
257         char etag[1 + 2 * sizeof(int)];
258         const char *inm;
259         struct MHD_Response *response;
260
261         /* Opens the file or directory */
262         if (filename[0]) {
263                 fd = openat(dirfd, filename, O_RDONLY);
264                 if (fd < 0) {
265                         if (errno == ENOENT)
266                                 return 0;
267                         afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
268                         return 1;
269                 }
270         } else {
271                 fd = dup(dirfd);
272                 if (fd < 0) {
273                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
274                         return 1;
275                 }
276         }
277
278         /* Retrieves file's status */
279         if (fstat(fd, &st) != 0) {
280                 close(fd);
281                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
282                 return 1;
283         }
284
285         /* serve directory */
286         if (S_ISDIR(st.st_mode)) {
287                 if (hreq->url[hreq->lenurl - 1] != '/') {
288                         /* the redirect is needed for reliability of relative path */
289                         char *tourl = alloca(hreq->lenurl + 2);
290                         memcpy(tourl, hreq->url, hreq->lenurl);
291                         tourl[hreq->lenurl] = '/';
292                         tourl[hreq->lenurl + 1] = 0;
293                         rc = afb_hreq_redirect_to(hreq, tourl);
294                 } else {
295                         rc = afb_hreq_reply_file_if_exist(hreq, fd, "index.html");
296                 }
297                 close(fd);
298                 return rc;
299         }
300
301         /* Don't serve special files */
302         if (!S_ISREG(st.st_mode)) {
303                 close(fd);
304                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
305                 return 1;
306         }
307
308         /* Check the method */
309         if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
310                 close(fd);
311                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
312                 return 1;
313         }
314
315         /* computes the etag */
316         sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
317
318         /* checks the etag */
319         inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
320         if (inm && 0 == strcmp(inm, etag)) {
321                 /* etag ok, return NOT MODIFIED */
322                 close(fd);
323                 if (verbosity)
324                         fprintf(stderr, "Not Modified: [%s]\n", filename);
325                 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
326                 status = MHD_HTTP_NOT_MODIFIED;
327         } else {
328                 /* check the size */
329                 if (st.st_size != (off_t) (size_t) st.st_size) {
330                         close(fd);
331                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
332                         return 1;
333                 }
334
335                 /* create the response */
336                 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
337                 status = MHD_HTTP_OK;
338
339 #if defined(USE_MAGIC_MIME_TYPE)
340                 /* set the type */
341                 {
342                         const char *mimetype = magic_mimetype_fd(fd);
343                         if (mimetype != NULL)
344                                 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
345                 }
346 #endif
347         }
348
349         /* fills the value and send */
350         MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, hreq->session->cacheTimeout);
351         MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
352         MHD_queue_response(hreq->connection, status, response);
353         MHD_destroy_response(response);
354         return 1;
355 }
356
357 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
358 {
359         int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
360         if (rc == 0)
361                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
362         return 1;
363 }
364
365 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
366 {
367         struct MHD_Response *response;
368
369         response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
370         MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION, url);
371         MHD_queue_response(hreq->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
372         MHD_destroy_response(response);
373         if (verbosity)
374                 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
375         return 1;
376 }
377
378 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
379 {
380         return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
381 }
382
383 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
384 {
385         struct hreq_data *data = get_data(hreq, name, 0);
386         return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
387 }
388
389 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
390 {
391         return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
392 }
393
394 void afb_hreq_post_end(struct afb_hreq *hreq)
395 {
396         struct hreq_data *data = hreq->data;
397         while(data) {
398                 if (data->file > 0) {
399                         close(data->file);
400                         data->file = -1;
401                 }
402                 data = data->next;
403         }
404 }
405
406 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
407 {
408         void *p;
409         struct hreq_data *hdat = get_data(hreq, key, 1);
410         if (hdat->file) {
411                 return 0;
412         }
413         p = realloc(hdat->value, hdat->length + size + 1);
414         if (p == NULL) {
415                 return 0;
416         }
417         hdat->value = p;
418         memcpy(&hdat->value[hdat->length], data, size);
419         hdat->length += size;
420         hdat->value[hdat->length] = 0;
421         return 1;
422 }
423
424 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
425 {
426         struct hreq_data *hdat = get_data(hreq, key, 1);
427
428         /* continuation with reopening */
429         if (hdat->file < 0) {
430                 hdat->file = open(hdat->value, O_WRONLY|O_APPEND);
431                 if (hdat->file == 0) {
432                         hdat->file = dup(0);
433                         close(0);
434                 }
435                 if (hdat->file <= 0)
436                         return 0;
437         }
438         if (hdat->file > 0) {
439                 write(hdat->file, data, size);
440                 return 1;
441         }
442
443         /* creation */
444         /* TODO */
445         return 0;
446         
447 }
448
449 int afb_hreq_is_argument_a_file(struct afb_hreq *hreq, const char *key)
450 {
451         struct hreq_data *hdat = get_data(hreq, key, 0);
452         return hdat != NULL && hdat->file != 0;
453 }
454
455
456 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
457 {
458         return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
459 }
460
461 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
462 {
463         struct hreq_data *hdat = get_data(hreq, name, 0);
464         if (hdat)
465                 return (struct afb_arg){
466                         .name = hdat->key,
467                         .value = hdat->value,
468                         .size = hdat->length,
469                         .is_file = (hdat->file != 0)
470                 };
471                 
472         return (struct afb_arg){
473                 .name = name,
474                 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
475                 .size = 0,
476                 .is_file = 0
477         };
478 }
479
480 struct iterdata
481 {
482         struct afb_hreq *hreq;
483         int (*iterator)(void *closure, struct afb_arg arg);
484         void *closure;
485 };
486
487 static int _iterargs_(struct iterdata *id, enum MHD_ValueKind kind, const char *key, const char *value)
488 {
489         if (get_data(id->hreq, key, 0))
490                 return 1;
491         return id->iterator(id->closure, (struct afb_arg){
492                 .name = key,
493                 .value = value,
494                 .size = 0,
495                 .is_file = 0
496         });
497 }
498
499 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
500 {
501         struct iterdata id = { .hreq = hreq, .iterator = iterator, .closure = closure };
502         struct hreq_data *hdat = hreq->data;
503         while (hdat) {
504                 if (!iterator(closure, (struct afb_arg){
505                         .name = hdat->key,
506                         .value = hdat->value,
507                         .size = hdat->length,
508                         .is_file = (hdat->file != 0)}))
509                         return;
510                 hdat = hdat->next;
511         }
512         MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, &id);
513 }
514
515 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
516 {
517         ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
518         return len ? : -1;
519 }
520
521 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
522 {
523         json_object *root, *request;
524         struct MHD_Response *response;
525
526         root = json_object_new_object();
527         json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
528         request = json_object_new_object();
529         json_object_object_add(root, "request", request);
530         json_object_object_add(request, "status", json_object_new_string(status));
531         if (info)
532                 json_object_object_add(request, "info", json_object_new_string(info));
533         if (resp)
534                 json_object_object_add(root, "response", resp);
535         if (hreq->context) {
536                 json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
537                 json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
538         }
539
540         response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
541         MHD_queue_response(hreq->connection, retcode, response);
542         MHD_destroy_response(response);
543 }
544
545 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
546 {
547         req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
548 }
549
550 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
551 {
552         req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
553 }
554
555 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
556 {
557         const char *uuid;
558
559         if (hreq->context == NULL) {
560                 uuid = afb_hreq_get_header(hreq, uuid_header);
561                 if (uuid == NULL)
562                         uuid = afb_hreq_get_argument(hreq, uuid_arg);
563                 if (uuid == NULL)
564                         uuid = afb_hreq_get_cookie(hreq, uuid_cookie);
565                 hreq->context = ctxClientGetForUuid(uuid);
566         }
567         return hreq->context;
568 }
569
570 static int req_session_create(struct afb_hreq *hreq)
571 {
572         struct AFB_clientCtx *context = afb_hreq_context(hreq);
573         if (context == NULL)
574                 return 0;
575         if (context->created)
576                 return 0;
577         return req_session_check(hreq, 1);
578 }
579
580 static int req_session_check(struct afb_hreq *hreq, int refresh)
581 {
582         const char *token;
583
584         struct AFB_clientCtx *context = afb_hreq_context(hreq);
585
586         if (context == NULL)
587                 return 0;
588
589         token = afb_hreq_get_header(hreq, token_header);
590         if (token == NULL)
591                 token = afb_hreq_get_argument(hreq, token_arg);
592         if (token == NULL)
593                 token = afb_hreq_get_cookie(hreq, token_cookie);
594         if (token == NULL)
595                 return 0;
596
597         if (!ctxTokenCheck (context, token))
598                 return 0;
599
600         if (refresh) {
601                 ctxTokenNew (context);
602         }
603
604         return 1;
605 }
606
607 static void req_session_close(struct afb_hreq *hreq)
608 {
609         struct AFB_clientCtx *context = afb_hreq_context(hreq);
610         if (context != NULL)
611                 ctxClientClose(context);
612 }
613
614
615