refactored verbosity
[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 _GNU_SOURCE
19
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <assert.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <sys/stat.h>
27
28 #include <microhttpd.h>
29
30 #include "local-def.h"
31 #include "afb-method.h"
32 #include "afb-req-itf.h"
33 #include "afb-hreq.h"
34 #include "session.h"
35 #include "verbose.h"
36
37 #define SIZE_RESPONSE_BUFFER   8000
38
39 static char empty_string[] = "";
40
41 static const char uuid_header[] = "x-afb-uuid";
42 static const char uuid_arg[] = "uuid";
43 static const char uuid_cookie[] = "uuid";
44
45 static const char token_header[] = "x-afb-token";
46 static const char token_arg[] = "token";
47 static const char token_cookie[] = "token";
48
49
50 struct hreq_data {
51         struct hreq_data *next;
52         char *key;
53         int file;
54         size_t length;
55         char *value;
56 };
57
58 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name);
59 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure);
60 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info);
61 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info);
62 static int req_session_create(struct afb_hreq *hreq);
63 static int req_session_check(struct afb_hreq *hreq, int refresh);
64 static void req_session_close(struct afb_hreq *hreq);
65
66 static const struct afb_req_itf afb_hreq_itf = {
67         .get = (void*)req_get,
68         .iterate = (void*)req_iterate,
69         .fail = (void*)req_fail,
70         .success = (void*)req_success,
71         .session_create = (void*)req_session_create,
72         .session_check = (void*)req_session_check,
73         .session_close = (void*)req_session_close
74 };
75
76 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
77 {
78         struct hreq_data *data = hreq->data;
79         if (key == NULL)
80                 key = empty_string;
81         while (data != NULL) {
82                 if (!strcasecmp(data->key, key))
83                         return data;
84                 data = data->next;
85         }
86         if (create) {
87                 data = calloc(1, sizeof *data);
88                 if (data != NULL) {
89                         data->key = strdup(key);
90                         if (data->key == NULL) {
91                                 free(data);
92                                 data = NULL;
93                         } else {
94                                 data->next = hreq->data;
95                                 hreq->data = data;
96                         }
97                 }
98         }
99         return data;
100 }
101
102 /* a valid subpath is a relative path not looking deeper than root using .. */
103 static int validsubpath(const char *subpath)
104 {
105         int l = 0, i = 0;
106
107         while (subpath[i]) {
108                 switch (subpath[i++]) {
109                 case '.':
110                         if (!subpath[i])
111                                 break;
112                         if (subpath[i] == '/') {
113                                 i++;
114                                 break;
115                         }
116                         if (subpath[i++] == '.') {
117                                 if (!subpath[i]) {
118                                         if (--l < 0)
119                                                 return 0;
120                                         break;
121                                 }
122                                 if (subpath[i++] == '/') {
123                                         if (--l < 0)
124                                                 return 0;
125                                         break;
126                                 }
127                         }
128                 default:
129                         while (subpath[i] && subpath[i] != '/')
130                                 i++;
131                         l++;
132                 case '/':
133                         break;
134                 }
135         }
136         return 1;
137 }
138
139 void afb_hreq_free(struct afb_hreq *hreq)
140 {
141         struct hreq_data *data;
142         if (hreq != NULL) {
143                 if (hreq->postform != NULL)
144                         MHD_destroy_post_processor(hreq->postform);
145                 for (data = hreq->data; data; data = hreq->data) {
146                         hreq->data = data->next;
147                         free(data->key);
148                         free(data->value);
149                         free(data);
150                 }
151                 ctxClientPut(hreq->context);
152                 free(hreq);
153         }
154 }
155
156 /*
157  * Removes the 'prefix' of 'length' from the tail of 'hreq'
158  * if and only if the prefix exists and is terminated by a leading
159  * slash
160  */
161 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
162 {
163         /* check the prefix ? */
164         if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
165             || strncasecmp(prefix, hreq->tail, length))
166                 return 0;
167
168         /* removes successives / */
169         while (length < hreq->lentail && hreq->tail[length + 1] == '/')
170                 length++;
171
172         /* update the tail */
173         hreq->lentail -= length;
174         hreq->tail += length;
175         return 1;
176 }
177
178 int afb_hreq_valid_tail(struct afb_hreq *hreq)
179 {
180         return validsubpath(hreq->tail);
181 }
182
183 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
184 {
185         char *buffer;
186         int length;
187         struct MHD_Response *response;
188
189         length = asprintf(&buffer, "<html><body>error %u</body></html>", status);
190         if (length > 0)
191                 response = MHD_create_response_from_buffer((unsigned)length, buffer, MHD_RESPMEM_MUST_FREE);
192         else {
193                 buffer = "<html><body>error</body></html>";
194                 response = MHD_create_response_from_buffer(strlen(buffer), buffer, MHD_RESPMEM_PERSISTENT);
195         }
196         if (!MHD_queue_response(hreq->connection, status, response))
197                 fprintf(stderr, "Failed to reply error code %u", status);
198         MHD_destroy_response(response);
199 }
200
201 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
202 {
203         int rc;
204         int fd;
205         unsigned int status;
206         struct stat st;
207         char etag[1 + 2 * sizeof(int)];
208         const char *inm;
209         struct MHD_Response *response;
210
211         /* Opens the file or directory */
212         if (filename[0]) {
213                 fd = openat(dirfd, filename, O_RDONLY);
214                 if (fd < 0) {
215                         if (errno == ENOENT)
216                                 return 0;
217                         afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
218                         return 1;
219                 }
220         } else {
221                 fd = dup(dirfd);
222                 if (fd < 0) {
223                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
224                         return 1;
225                 }
226         }
227
228         /* Retrieves file's status */
229         if (fstat(fd, &st) != 0) {
230                 close(fd);
231                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
232                 return 1;
233         }
234
235         /* serve directory */
236         if (S_ISDIR(st.st_mode)) {
237                 if (hreq->url[hreq->lenurl - 1] != '/') {
238                         /* the redirect is needed for reliability of relative path */
239                         char *tourl = alloca(hreq->lenurl + 2);
240                         memcpy(tourl, hreq->url, hreq->lenurl);
241                         tourl[hreq->lenurl] = '/';
242                         tourl[hreq->lenurl + 1] = 0;
243                         rc = afb_hreq_redirect_to(hreq, tourl);
244                 } else {
245                         rc = afb_hreq_reply_file_if_exist(hreq, fd, "index.html");
246                 }
247                 close(fd);
248                 return rc;
249         }
250
251         /* Don't serve special files */
252         if (!S_ISREG(st.st_mode)) {
253                 close(fd);
254                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
255                 return 1;
256         }
257
258         /* Check the method */
259         if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
260                 close(fd);
261                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
262                 return 1;
263         }
264
265         /* computes the etag */
266         sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
267
268         /* checks the etag */
269         inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
270         if (inm && 0 == strcmp(inm, etag)) {
271                 /* etag ok, return NOT MODIFIED */
272                 close(fd);
273                 if (verbosity)
274                         fprintf(stderr, "Not Modified: [%s]\n", filename);
275                 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
276                 status = MHD_HTTP_NOT_MODIFIED;
277         } else {
278                 /* check the size */
279                 if (st.st_size != (off_t) (size_t) st.st_size) {
280                         close(fd);
281                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
282                         return 1;
283                 }
284
285                 /* create the response */
286                 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
287                 status = MHD_HTTP_OK;
288
289 #if defined(USE_MAGIC_MIME_TYPE)
290                 /* set the type */
291                 if (hreq->session->magic) {
292                         const char *mimetype = magic_descriptor(hreq->session->magic, fd);
293                         if (mimetype != NULL)
294                                 MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
295                 }
296 #endif
297         }
298
299         /* fills the value and send */
300         MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, hreq->session->cacheTimeout);
301         MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etag);
302         MHD_queue_response(hreq->connection, status, response);
303         MHD_destroy_response(response);
304         return 1;
305 }
306
307 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
308 {
309         int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
310         if (rc == 0)
311                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
312         return 1;
313 }
314
315 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
316 {
317         struct MHD_Response *response;
318
319         response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
320         MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION, url);
321         MHD_queue_response(hreq->connection, MHD_HTTP_MOVED_PERMANENTLY, response);
322         MHD_destroy_response(response);
323         if (verbosity)
324                 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
325         return 1;
326 }
327
328 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
329 {
330         return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
331 }
332
333 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
334 {
335         struct hreq_data *data = get_data(hreq, name, 0);
336         return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
337 }
338
339 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
340 {
341         return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
342 }
343
344 void afb_hreq_post_end(struct afb_hreq *hreq)
345 {
346         struct hreq_data *data = hreq->data;
347         while(data) {
348                 if (data->file > 0) {
349                         close(data->file);
350                         data->file = -1;
351                 }
352                 data = data->next;
353         }
354 }
355
356 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
357 {
358         void *p;
359         struct hreq_data *hdat = get_data(hreq, key, 1);
360         if (hdat->file) {
361                 return 0;
362         }
363         p = realloc(hdat->value, hdat->length + size + 1);
364         if (p == NULL) {
365                 return 0;
366         }
367         hdat->value = p;
368         memcpy(&hdat->value[hdat->length], data, size);
369         hdat->length += size;
370         hdat->value[hdat->length] = 0;
371         return 1;
372 }
373
374 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
375 {
376         struct hreq_data *hdat = get_data(hreq, key, 1);
377
378         /* continuation with reopening */
379         if (hdat->file < 0) {
380                 hdat->file = open(hdat->value, O_WRONLY|O_APPEND);
381                 if (hdat->file == 0) {
382                         hdat->file = dup(0);
383                         close(0);
384                 }
385                 if (hdat->file <= 0)
386                         return 0;
387         }
388         if (hdat->file > 0) {
389                 write(hdat->file, data, size);
390                 return 1;
391         }
392
393         /* creation */
394         /* TODO */
395         return 0;
396         
397 }
398
399 int afb_hreq_is_argument_a_file(struct afb_hreq *hreq, const char *key)
400 {
401         struct hreq_data *hdat = get_data(hreq, key, 0);
402         return hdat != NULL && hdat->file != 0;
403 }
404
405
406 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
407 {
408         return (struct afb_req){ .itf = &afb_hreq_itf, .data = hreq };
409 }
410
411 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
412 {
413         struct hreq_data *hdat = get_data(hreq, name, 0);
414         if (hdat)
415                 return (struct afb_arg){
416                         .name = hdat->key,
417                         .value = hdat->value,
418                         .size = hdat->length,
419                         .is_file = (hdat->file != 0)
420                 };
421                 
422         return (struct afb_arg){
423                 .name = name,
424                 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
425                 .size = 0,
426                 .is_file = 0
427         };
428 }
429
430 struct iterdata
431 {
432         struct afb_hreq *hreq;
433         int (*iterator)(void *closure, struct afb_arg arg);
434         void *closure;
435 };
436
437 static int _iterargs_(struct iterdata *id, enum MHD_ValueKind kind, const char *key, const char *value)
438 {
439         if (get_data(id->hreq, key, 0))
440                 return 1;
441         return id->iterator(id->closure, (struct afb_arg){
442                 .name = key,
443                 .value = value,
444                 .size = 0,
445                 .is_file = 0
446         });
447 }
448
449 static void req_iterate(struct afb_hreq *hreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
450 {
451         struct iterdata id = { .hreq = hreq, .iterator = iterator, .closure = closure };
452         struct hreq_data *hdat = hreq->data;
453         while (hdat) {
454                 if (!iterator(closure, (struct afb_arg){
455                         .name = hdat->key,
456                         .value = hdat->value,
457                         .size = hdat->length,
458                         .is_file = (hdat->file != 0)}))
459                         return;
460                 hdat = hdat->next;
461         }
462         MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, &id);
463 }
464
465 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
466 {
467         ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
468         return len ? : -1;
469 }
470
471 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
472 {
473         json_object *root, *request;
474         struct MHD_Response *response;
475
476         root = json_object_new_object();
477         json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
478         request = json_object_new_object();
479         json_object_object_add(root, "request", request);
480         json_object_object_add(request, "status", json_object_new_string(status));
481         if (info)
482                 json_object_object_add(request, "info", json_object_new_string(info));
483         if (resp)
484                 json_object_object_add(root, "response", resp);
485         if (hreq->context) {
486                 json_object_object_add(request, uuid_arg, json_object_new_string(hreq->context->uuid));
487                 json_object_object_add(request, token_arg, json_object_new_string(hreq->context->token));
488         }
489
490         response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, SIZE_RESPONSE_BUFFER, (void*)send_json_cb, root, (void*)json_object_put);
491         MHD_queue_response(hreq->connection, retcode, response);
492         MHD_destroy_response(response);
493 }
494
495 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
496 {
497         req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
498 }
499
500 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
501 {
502         req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
503 }
504
505 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
506 {
507         const char *uuid;
508
509         if (hreq->context == NULL) {
510                 uuid = afb_hreq_get_header(hreq, uuid_header);
511                 if (uuid == NULL)
512                         uuid = afb_hreq_get_argument(hreq, uuid_arg);
513                 if (uuid == NULL)
514                         uuid = afb_hreq_get_cookie(hreq, uuid_cookie);
515                 hreq->context = ctxClientGet(uuid);
516         }
517         return hreq->context;
518 }
519
520 static int req_session_create(struct afb_hreq *hreq)
521 {
522         struct AFB_clientCtx *context = afb_hreq_context(hreq);
523         if (context == NULL)
524                 return 0;
525         if (context->created)
526                 return 0;
527         return req_session_check(hreq, 1);
528 }
529
530 static int req_session_check(struct afb_hreq *hreq, int refresh)
531 {
532         const char *token;
533
534         struct AFB_clientCtx *context = afb_hreq_context(hreq);
535
536         if (context == NULL)
537                 return 0;
538
539         token = afb_hreq_get_header(hreq, token_header);
540         if (token == NULL)
541                 token = afb_hreq_get_argument(hreq, token_arg);
542         if (token == NULL)
543                 token = afb_hreq_get_cookie(hreq, token_cookie);
544         if (token == NULL)
545                 return 0;
546
547         if (!ctxTokenCheck (context, token))
548                 return 0;
549
550         if (refresh) {
551                 ctxTokenNew (context);
552         }
553
554         return 1;
555 }
556
557 static void req_session_close(struct afb_hreq *hreq)
558 {
559         struct AFB_clientCtx *context = afb_hreq_context(hreq);
560         if (context != NULL)
561                 ctxClientClose(context);
562 }
563
564
565