Update copyright dates
[src/app-framework-binder.git] / src / afb-hreq.c
1 /*
2  * Copyright (C) 2015-2020 "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 <ctype.h>
24 #include <assert.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <sys/stat.h>
28
29 #include <microhttpd.h>
30 #include <json-c/json.h>
31 #if !defined(JSON_C_TO_STRING_NOSLASHESCAPE)
32 #define JSON_C_TO_STRING_NOSLASHESCAPE 0
33 #endif
34
35 #if defined(USE_MAGIC_MIME_TYPE)
36 #include <magic.h>
37 #endif
38
39 #include "afb-method.h"
40 #include "afb-msg-json.h"
41 #include "afb-context.h"
42 #include "afb-hreq.h"
43 #include "afb-hsrv.h"
44 #include "afb-session.h"
45 #include "afb-token.h"
46 #include "afb-error-text.h"
47 #include "verbose.h"
48 #include "locale-root.h"
49
50 #define SIZE_RESPONSE_BUFFER   8192
51
52 static int global_reqids = 0;
53
54 static char empty_string[] = "";
55
56 static const char long_key_for_uuid[] = "x-afb-uuid";
57 static const char short_key_for_uuid[] = "uuid";
58
59 static const char long_key_for_token[] = "x-afb-token";
60 static const char short_key_for_token[] = "token";
61
62 static const char long_key_for_reqid[] = "x-afb-reqid";
63 static const char short_key_for_reqid[] = "reqid";
64
65 static const char key_for_bearer[] = "Bearer";
66 static const char key_for_access_token[] = "access_token";
67
68 static char *cookie_name = NULL;
69 static char *cookie_setter = NULL;
70 static char *tmp_pattern = NULL;
71
72 /*
73  * Structure for storing key/values read from POST requests
74  */
75 struct hreq_data {
76         struct hreq_data *next; /* chain to next data */
77         char *key;              /* key name */
78         size_t length;          /* length of the value (used for appending) */
79         char *value;            /* the value (or original filename) */
80         char *path;             /* path of the file saved */
81 };
82
83 static struct json_object *req_json(struct afb_xreq *xreq);
84 static struct afb_arg req_get(struct afb_xreq *xreq, const char *name);
85 static void req_reply(struct afb_xreq *xreq, struct json_object *object, const char *error, const char *info);
86 static void req_destroy(struct afb_xreq *xreq);
87
88 const struct afb_xreq_query_itf afb_hreq_xreq_query_itf = {
89         .json = req_json,
90         .get = req_get,
91         .reply = req_reply,
92         .unref = req_destroy
93 };
94
95 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
96 {
97         struct hreq_data *data = hreq->data;
98         while (data != NULL) {
99                 if (!strcasecmp(data->key, key))
100                         return data;
101                 data = data->next;
102         }
103         if (create) {
104                 data = calloc(1, sizeof *data);
105                 if (data != NULL) {
106                         data->key = strdup(key);
107                         if (data->key == NULL) {
108                                 free(data);
109                                 data = NULL;
110                         } else {
111                                 data->next = hreq->data;
112                                 hreq->data = data;
113                         }
114                 }
115         }
116         return data;
117 }
118
119 /* a valid subpath is a relative path not looking deeper than root using .. */
120 static int validsubpath(const char *subpath)
121 {
122         int l = 0, i = 0;
123
124         while (subpath[i]) {
125                 switch (subpath[i++]) {
126                 case '.':
127                         if (!subpath[i])
128                                 break;
129                         if (subpath[i] == '/') {
130                                 i++;
131                                 break;
132                         }
133                         if (subpath[i++] == '.') {
134                                 if (!subpath[i]) {
135                                         if (--l < 0)
136                                                 return 0;
137                                         break;
138                                 }
139                                 if (subpath[i++] == '/') {
140                                         if (--l < 0)
141                                                 return 0;
142                                         break;
143                                 }
144                         }
145                 default:
146                         while (subpath[i] && subpath[i] != '/')
147                                 i++;
148                         l++;
149                 case '/':
150                         break;
151                 }
152         }
153         return 1;
154 }
155
156 static void afb_hreq_reply_v(struct afb_hreq *hreq, unsigned status, struct MHD_Response *response, va_list args)
157 {
158         char *cookie;
159         const char *k, *v;
160
161         if (hreq->replied != 0)
162                 return;
163
164         k = va_arg(args, const char *);
165         while (k != NULL) {
166                 v = va_arg(args, const char *);
167                 MHD_add_response_header(response, k, v);
168                 k = va_arg(args, const char *);
169         }
170
171         v = afb_context_uuid(&hreq->xreq.context);
172         if (v != NULL && asprintf(&cookie, cookie_setter, v) > 0) {
173                 MHD_add_response_header(response, MHD_HTTP_HEADER_SET_COOKIE, cookie);
174                 free(cookie);
175         }
176         MHD_queue_response(hreq->connection, status, response);
177         MHD_destroy_response(response);
178
179         hreq->replied = 1;
180         if (hreq->suspended != 0) {
181                 MHD_resume_connection (hreq->connection);
182                 hreq->suspended = 0;
183                 afb_hsrv_run(hreq->hsrv);
184         }
185 }
186
187 void afb_hreq_reply(struct afb_hreq *hreq, unsigned status, struct MHD_Response *response, ...)
188 {
189         va_list args;
190         va_start(args, response);
191         afb_hreq_reply_v(hreq, status, response, args);
192         va_end(args);
193 }
194
195 void afb_hreq_reply_empty(struct afb_hreq *hreq, unsigned status, ...)
196 {
197         va_list args;
198         va_start(args, status);
199         afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT), args);
200         va_end(args);
201 }
202
203 void afb_hreq_reply_static(struct afb_hreq *hreq, unsigned status, size_t size, const char *buffer, ...)
204 {
205         va_list args;
206         va_start(args, buffer);
207         afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, (char*)buffer, MHD_RESPMEM_PERSISTENT), args);
208         va_end(args);
209 }
210
211 void afb_hreq_reply_copy(struct afb_hreq *hreq, unsigned status, size_t size, const char *buffer, ...)
212 {
213         va_list args;
214         va_start(args, buffer);
215         afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, (char*)buffer, MHD_RESPMEM_MUST_COPY), args);
216         va_end(args);
217 }
218
219 void afb_hreq_reply_free(struct afb_hreq *hreq, unsigned status, size_t size, char *buffer, ...)
220 {
221         va_list args;
222         va_start(args, buffer);
223         afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_MUST_FREE), args);
224         va_end(args);
225 }
226
227 #if defined(USE_MAGIC_MIME_TYPE)
228
229 #if !defined(MAGIC_DB)
230 #define MAGIC_DB "/usr/share/misc/magic.mgc"
231 #endif
232
233 static magic_t lazy_libmagic()
234 {
235         static int done = 0;
236         static magic_t result = NULL;
237
238         if (!done) {
239                 done = 1;
240                 /* MAGIC_MIME tells magic to return a mime of the file,
241                          but you can specify different things */
242                 INFO("Loading mimetype default magic database");
243                 result = magic_open(MAGIC_MIME_TYPE);
244                 if (result == NULL) {
245                         ERROR("unable to initialize magic library");
246                 }
247                 /* Warning: should not use NULL for DB
248                                 [libmagic bug wont pass efence check] */
249                 else if (magic_load(result, MAGIC_DB) != 0) {
250                         ERROR("cannot load magic database: %s", magic_error(result));
251                         magic_close(result);
252                         result = NULL;
253                 }
254         }
255
256         return result;
257 }
258
259 static const char *magic_mimetype_fd(int fd)
260 {
261         magic_t lib = lazy_libmagic();
262         return lib ? magic_descriptor(lib, fd) : NULL;
263 }
264
265 #endif
266
267 static const char *mimetype_fd_name(int fd, const char *filename)
268 {
269         const char *result = NULL;
270
271 #if defined(INFER_EXTENSION)
272         /*
273          * Set some well-known extensions
274          * Note that it is mandatory for example for css files in order to provide
275          * right mimetype that must be text/css (otherwise chrome browser will not
276          * load correctly css file) while libmagic returns text/plain.
277          */
278         const char *extension = strrchr(filename, '.');
279         if (extension) {
280                 static const char *const known[][2] = {
281                         /* keep it sorted for dichotomic search */
282                         { ".css",       "text/css" },
283                         { ".gif",       "image/gif" },
284                         { ".html",      "text/html" },
285                         { ".htm",       "text/html" },
286                         { ".ico",       "image/x-icon"},
287                         { ".jpeg",      "image/jpeg" },
288                         { ".jpg",       "image/jpeg" },
289                         { ".js",        "text/javascript" },
290                         { ".json",      "application/json" },
291                         { ".mp3",       "audio/mpeg" },
292                         { ".png",       "image/png" },
293                         { ".svg",       "image/svg+xml" },
294                         { ".ttf",       "application/x-font-ttf"},
295                         { ".txt",       "text/plain" },
296                         { ".wav",       "audio/x-wav" },
297                         { ".xht",       "application/xhtml+xml" },
298                         { ".xhtml",     "application/xhtml+xml" },
299                         { ".xml",       "application/xml" }
300                 };
301                 int i, c, l = 0, u = sizeof known / sizeof *known;
302                 while (l < u) {
303                         i = (l + u) >> 1;
304                         c = strcasecmp(extension, known[i][0]);
305                         if (!c) {
306                                 result = known[i][1];
307                                 break;
308                         }
309                         if (c < 0)
310                                 u = i;
311                         else
312                                 l = i + 1;
313                 }
314         }
315 #endif
316 #if defined(USE_MAGIC_MIME_TYPE)
317         if (result == NULL)
318                 result = magic_mimetype_fd(fd);
319 #endif
320         return result;
321 }
322
323 static void req_destroy(struct afb_xreq *xreq)
324 {
325         struct afb_hreq *hreq = CONTAINER_OF_XREQ(struct afb_hreq, xreq);
326         struct hreq_data *data;
327
328         if (hreq->postform != NULL)
329                 MHD_destroy_post_processor(hreq->postform);
330         if (hreq->tokener != NULL)
331                 json_tokener_free(hreq->tokener);
332
333         for (data = hreq->data; data; data = hreq->data) {
334                 hreq->data = data->next;
335                 if (data->path) {
336                         unlink(data->path);
337                         free(data->path);
338                 }
339                 free(data->key);
340                 free(data->value);
341                 free(data);
342         }
343         afb_context_disconnect(&hreq->xreq.context);
344         json_object_put(hreq->json);
345         free((char*)hreq->xreq.request.called_api);
346         free((char*)hreq->xreq.request.called_verb);
347         free(hreq);
348 }
349
350 void afb_hreq_addref(struct afb_hreq *hreq)
351 {
352         afb_xreq_unhooked_addref(&hreq->xreq);
353 }
354
355 void afb_hreq_unref(struct afb_hreq *hreq)
356 {
357         if (hreq->replied)
358                 hreq->xreq.replied = 1;
359         afb_xreq_unhooked_unref(&hreq->xreq);
360 }
361
362 /*
363  * Removes the 'prefix' of 'length' from the tail of 'hreq'
364  * if and only if the prefix exists and is terminated by a leading
365  * slash
366  */
367 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
368 {
369         /* check the prefix ? */
370         if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
371             || strncasecmp(prefix, hreq->tail, length))
372                 return 0;
373
374         /* removes successives / */
375         while (length < hreq->lentail && hreq->tail[length + 1] == '/')
376                 length++;
377
378         /* update the tail */
379         hreq->lentail -= length;
380         hreq->tail += length;
381         return 1;
382 }
383
384 int afb_hreq_valid_tail(struct afb_hreq *hreq)
385 {
386         return validsubpath(hreq->tail);
387 }
388
389 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
390 {
391         afb_hreq_reply_empty(hreq, status, NULL);
392 }
393
394 int afb_hreq_redirect_to_ending_slash_if_needed(struct afb_hreq *hreq)
395 {
396         char *tourl;
397
398         if (hreq->url[hreq->lenurl - 1] == '/')
399                 return 0;
400
401         /* the redirect is needed for reliability of relative path */
402         tourl = alloca(hreq->lenurl + 2);
403         memcpy(tourl, hreq->url, hreq->lenurl);
404         tourl[hreq->lenurl] = '/';
405         tourl[hreq->lenurl + 1] = 0;
406         afb_hreq_redirect_to(hreq, tourl, 1);
407         return 1;
408 }
409
410 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
411 {
412         int rc;
413         int fd;
414         unsigned int status;
415         struct stat st;
416         char etag[1 + 2 * 8];
417         const char *inm;
418         struct MHD_Response *response;
419         const char *mimetype;
420
421         /* Opens the file or directory */
422         if (filename[0]) {
423                 fd = openat(dirfd, filename, O_RDONLY);
424                 if (fd < 0) {
425                         if (errno == ENOENT)
426                                 return 0;
427                         afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
428                         return 1;
429                 }
430         } else {
431                 fd = dup(dirfd);
432                 if (fd < 0) {
433                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
434                         return 1;
435                 }
436         }
437
438         /* Retrieves file's status */
439         if (fstat(fd, &st) != 0) {
440                 close(fd);
441                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
442                 return 1;
443         }
444
445         /* serve directory */
446         if (S_ISDIR(st.st_mode)) {
447                 rc = afb_hreq_redirect_to_ending_slash_if_needed(hreq);
448                 if (rc == 0) {
449                         static const char *indexes[] = { "index.html", NULL };
450                         int i = 0;
451                         while (indexes[i] != NULL) {
452                                 if (faccessat(fd, indexes[i], R_OK, 0) == 0) {
453                                         rc = afb_hreq_reply_file_if_exist(hreq, fd, indexes[i]);
454                                         break;
455                                 }
456                                 i++;
457                         }
458                 }
459                 close(fd);
460                 return rc;
461         }
462
463         /* Don't serve special files */
464         if (!S_ISREG(st.st_mode)) {
465                 close(fd);
466                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
467                 return 1;
468         }
469
470         /* Check the method */
471         if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
472                 close(fd);
473                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
474                 return 1;
475         }
476
477         /* computes the etag */
478         sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
479
480         /* checks the etag */
481         inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
482         if (inm && 0 == strcmp(inm, etag)) {
483                 /* etag ok, return NOT MODIFIED */
484                 close(fd);
485                 DEBUG("Not Modified: [%s]", filename);
486                 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
487                 status = MHD_HTTP_NOT_MODIFIED;
488         } else {
489                 /* check the size */
490                 if (st.st_size != (off_t) (size_t) st.st_size) {
491                         close(fd);
492                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
493                         return 1;
494                 }
495
496                 /* create the response */
497                 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
498                 status = MHD_HTTP_OK;
499
500                 /* set the type */
501                 mimetype = mimetype_fd_name(fd, filename);
502                 if (mimetype != NULL)
503                         MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
504         }
505
506         /* fills the value and send */
507         afb_hreq_reply(hreq, status, response,
508                         MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout,
509                         MHD_HTTP_HEADER_ETAG, etag,
510                         NULL);
511         return 1;
512 }
513
514 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
515 {
516         int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
517         if (rc == 0)
518                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
519         return 1;
520 }
521
522 int afb_hreq_reply_locale_file_if_exist(struct afb_hreq *hreq, struct locale_search *search, const char *filename)
523 {
524         int rc;
525         int fd;
526         unsigned int status;
527         struct stat st;
528         char etag[1 + 2 * 8];
529         const char *inm;
530         struct MHD_Response *response;
531         const char *mimetype;
532
533         /* Opens the file or directory */
534         fd = locale_search_open(search, filename[0] ? filename : ".", O_RDONLY);
535         if (fd < 0) {
536                 if (errno == ENOENT)
537                         return 0;
538                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
539                 return 1;
540         }
541
542         /* Retrieves file's status */
543         if (fstat(fd, &st) != 0) {
544                 close(fd);
545                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
546                 return 1;
547         }
548
549         /* serve directory */
550         if (S_ISDIR(st.st_mode)) {
551                 rc = afb_hreq_redirect_to_ending_slash_if_needed(hreq);
552                 if (rc == 0) {
553                         static const char *indexes[] = { "index.html", NULL };
554                         int i = 0;
555                         size_t length = strlen(filename);
556                         char *extname = alloca(length + 30); /* 30 is enough to old data of indexes */
557                         memcpy(extname, filename, length);
558                         if (length && extname[length - 1] != '/')
559                                 extname[length++] = '/';
560                         while (rc == 0 && indexes[i] != NULL) {
561                                 strcpy(extname + length, indexes[i++]);
562                                 rc = afb_hreq_reply_locale_file_if_exist(hreq, search, extname);
563                         }
564                 }
565                 close(fd);
566                 return rc;
567         }
568
569         /* Don't serve special files */
570         if (!S_ISREG(st.st_mode)) {
571                 close(fd);
572                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
573                 return 1;
574         }
575
576         /* Check the method */
577         if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
578                 close(fd);
579                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
580                 return 1;
581         }
582
583         /* computes the etag */
584         sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
585
586         /* checks the etag */
587         inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
588         if (inm && 0 == strcmp(inm, etag)) {
589                 /* etag ok, return NOT MODIFIED */
590                 close(fd);
591                 DEBUG("Not Modified: [%s]", filename);
592                 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
593                 status = MHD_HTTP_NOT_MODIFIED;
594         } else {
595                 /* check the size */
596                 if (st.st_size != (off_t) (size_t) st.st_size) {
597                         close(fd);
598                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
599                         return 1;
600                 }
601
602                 /* create the response */
603                 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
604                 status = MHD_HTTP_OK;
605
606                 /* set the type */
607                 mimetype = mimetype_fd_name(fd, filename);
608                 if (mimetype != NULL)
609                         MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
610         }
611
612         /* fills the value and send */
613         afb_hreq_reply(hreq, status, response,
614                         MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout,
615                         MHD_HTTP_HEADER_ETAG, etag,
616                         NULL);
617         return 1;
618 }
619
620 int afb_hreq_reply_locale_file(struct afb_hreq *hreq, struct locale_search *search, const char *filename)
621 {
622         int rc = afb_hreq_reply_locale_file_if_exist(hreq, search, filename);
623         if (rc == 0)
624                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
625         return 1;
626 }
627
628 struct _mkq_ {
629         int count;
630         size_t length;
631         size_t alloc;
632         char *text;
633 };
634
635 static void _mkq_add_(struct _mkq_ *mkq, char value)
636 {
637         char *text = mkq->text;
638         if (text != NULL) {
639                 if (mkq->length == mkq->alloc) {
640                         mkq->alloc += 100;
641                         text = realloc(text, mkq->alloc);
642                         if (text == NULL) {
643                                 free(mkq->text);
644                                 mkq->text = NULL;
645                                 return;
646                         }
647                         mkq->text = text;
648                 }
649                 text[mkq->length++] = value;
650         }
651 }
652
653 static void _mkq_add_hex_(struct _mkq_ *mkq, char value)
654 {
655         _mkq_add_(mkq, (char)(value < 10 ? value + '0' : value + 'A' - 10));
656 }
657
658 static void _mkq_add_esc_(struct _mkq_ *mkq, char value)
659 {
660         _mkq_add_(mkq, '%');
661         _mkq_add_hex_(mkq, (char)((value >> 4) & 15));
662         _mkq_add_hex_(mkq, (char)(value & 15));
663 }
664
665 static void _mkq_add_char_(struct _mkq_ *mkq, char value)
666 {
667         if (value <= ' ' || value >= 127)
668                 _mkq_add_esc_(mkq, value);
669         else
670                 switch(value) {
671                 case '=':
672                 case '&':
673                 case '%':
674                         _mkq_add_esc_(mkq, value);
675                         break;
676                 default:
677                         _mkq_add_(mkq, value);
678                 }
679 }
680
681 static void _mkq_append_(struct _mkq_ *mkq, const char *value)
682 {
683         while(*value)
684                 _mkq_add_char_(mkq, *value++);
685 }
686
687 static int _mkquery_(struct _mkq_ *mkq, enum MHD_ValueKind kind, const char *key, const char *value)
688 {
689         _mkq_add_(mkq, mkq->count++ ? '&' : '?');
690         _mkq_append_(mkq, key);
691         if (value != NULL) {
692                 _mkq_add_(mkq, '=');
693                 _mkq_append_(mkq, value);
694         }
695         return 1;
696 }
697
698 static char *url_with_query(struct afb_hreq *hreq, const char *url)
699 {
700         struct _mkq_ mkq;
701
702         mkq.count = 0;
703         mkq.length = strlen(url);
704         mkq.alloc = mkq.length + 1000;
705         mkq.text = malloc(mkq.alloc);
706         if (mkq.text != NULL) {
707                 strcpy(mkq.text, url);
708                 MHD_get_connection_values(hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_mkquery_, &mkq);
709                 _mkq_add_(&mkq, 0);
710         }
711         return mkq.text;
712 }
713
714 void afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url, int add_query_part)
715 {
716         const char *to;
717         char *wqp;
718
719         wqp = add_query_part ? url_with_query(hreq, url) : NULL;
720         to = wqp ? : url;
721         afb_hreq_reply_static(hreq, MHD_HTTP_MOVED_PERMANENTLY, 0, NULL,
722                         MHD_HTTP_HEADER_LOCATION, to, NULL);
723         DEBUG("redirect from [%s] to [%s]", hreq->url, url);
724         free(wqp);
725 }
726
727 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
728 {
729         return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
730 }
731
732 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
733 {
734         struct hreq_data *data = get_data(hreq, name, 0);
735         return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
736 }
737
738 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
739 {
740         return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
741 }
742
743 const char *afb_hreq_get_authorization_bearer(struct afb_hreq *hreq)
744 {
745         const char *value = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_AUTHORIZATION);
746         if (value) {
747                 if (strncasecmp(value, key_for_bearer, sizeof key_for_bearer - 1) == 0) {
748                         value += sizeof key_for_bearer - 1;
749                         if (isblank(*value++)) {
750                                 while (isblank(*value))
751                                         value++;
752                                 if (*value)
753                                         return value;
754                         }
755                 }
756         }
757         return NULL;
758 }
759
760 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
761 {
762         void *p;
763         struct hreq_data *hdat = get_data(hreq, key, 1);
764         if (hdat->path != NULL) {
765                 return 0;
766         }
767         p = realloc(hdat->value, hdat->length + size + 1);
768         if (p == NULL) {
769                 return 0;
770         }
771         hdat->value = p;
772         memcpy(&hdat->value[hdat->length], data, size);
773         hdat->length += size;
774         hdat->value[hdat->length] = 0;
775         return 1;
776 }
777
778 int afb_hreq_init_download_path(const char *directory)
779 {
780         struct stat st;
781         size_t n;
782         char *p;
783
784         if (access(directory, R_OK|W_OK)) {
785                 /* no read/write access */
786                 return -1;
787         }
788         if (stat(directory, &st)) {
789                 /* can't get info */
790                 return -1;
791         }
792         if (!S_ISDIR(st.st_mode)) {
793                 /* not a directory */
794                 errno = ENOTDIR;
795                 return -1;
796         }
797         n = strlen(directory);
798         while(n > 1 && directory[n-1] == '/') n--;
799         p = malloc(n + 8);
800         if (p == NULL) {
801                 /* can't allocate memory */
802                 errno = ENOMEM;
803                 return -1;
804         }
805         memcpy(p, directory, n);
806         p[n++] = '/';
807         p[n++] = 'X';
808         p[n++] = 'X';
809         p[n++] = 'X';
810         p[n++] = 'X';
811         p[n++] = 'X';
812         p[n++] = 'X';
813         p[n] = 0;
814         free(tmp_pattern);
815         tmp_pattern = p;
816         return 0;
817 }
818
819 static int opentempfile(char **path)
820 {
821         int fd;
822         char *fname;
823
824         fname = strdup(tmp_pattern ? : "XXXXXX"); /* TODO improve the path */
825         if (fname == NULL)
826                 return -1;
827
828         fd = mkostemp(fname, O_CLOEXEC|O_WRONLY);
829         if (fd < 0)
830                 free(fname);
831         else
832                 *path = fname;
833         return fd;
834 }
835
836 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
837 {
838         int fd;
839         ssize_t sz;
840         struct hreq_data *hdat = get_data(hreq, key, 1);
841
842         if (hdat->value == NULL) {
843                 hdat->value = strdup(file);
844                 if (hdat->value == NULL)
845                         return 0;
846                 fd = opentempfile(&hdat->path);
847         } else if (strcmp(hdat->value, file) || hdat->path == NULL) {
848                 return 0;
849         } else {
850                 fd = open(hdat->path, O_WRONLY|O_APPEND);
851         }
852         if (fd < 0)
853                 return 0;
854         while (size) {
855                 sz = write(fd, data, size);
856                 if (sz >= 0) {
857                         hdat->length += (size_t)sz;
858                         size -= (size_t)sz;
859                         data += sz;
860                 } else if (errno != EINTR)
861                         break;
862         }
863         close(fd);
864         return !size;
865 }
866
867 static struct afb_arg req_get(struct afb_xreq *xreq, const char *name)
868 {
869         const char *value;
870         struct afb_hreq *hreq = CONTAINER_OF_XREQ(struct afb_hreq, xreq);
871         struct hreq_data *hdat = get_data(hreq, name, 0);
872         if (hdat)
873                 return (struct afb_arg){
874                         .name = hdat->key,
875                         .value = hdat->value,
876                         .path = hdat->path
877                 };
878
879         value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
880         return (struct afb_arg){
881                 .name = value == NULL ? NULL : name,
882                 .value = value,
883                 .path = NULL
884         };
885 }
886
887 static int _iterargs_(struct json_object *obj, enum MHD_ValueKind kind, const char *key, const char *value)
888 {
889         json_object_object_add(obj, key, value ? json_object_new_string(value) : NULL);
890         return 1;
891 }
892
893 static struct json_object *req_json(struct afb_xreq *xreq)
894 {
895         struct hreq_data *hdat;
896         struct json_object *obj, *val;
897         struct afb_hreq *hreq = CONTAINER_OF_XREQ(struct afb_hreq, xreq);
898
899         obj = hreq->json;
900         if (obj == NULL) {
901                 hreq->json = obj = json_object_new_object();
902                 if (obj == NULL) {
903                 } else {
904                         MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, obj);
905                         for (hdat = hreq->data ; hdat ; hdat = hdat->next) {
906                                 if (hdat->path == NULL)
907                                         val = hdat->value ? json_object_new_string(hdat->value) : NULL;
908                                 else {
909                                         val = json_object_new_object();
910                                         if (val == NULL) {
911                                         } else {
912                                                 json_object_object_add(val, "file", json_object_new_string(hdat->value));
913                                                 json_object_object_add(val, "path", json_object_new_string(hdat->path));
914                                         }
915                                 }
916                                 json_object_object_add(obj, hdat->key, val);
917                         }
918                 }
919         }
920         return obj;
921 }
922
923 static inline const char *get_json_string(json_object *obj)
924 {
925         return json_object_to_json_string_ext(obj, JSON_C_TO_STRING_PLAIN|JSON_C_TO_STRING_NOSLASHESCAPE);
926 }
927 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
928 {
929         ssize_t len = stpncpy(buf, get_json_string(obj)+pos, max) - buf;
930         return len ? : (ssize_t)MHD_CONTENT_READER_END_OF_STREAM;
931 }
932
933 static void req_reply(struct afb_xreq *xreq, struct json_object *object, const char *error, const char *info)
934 {
935         struct afb_hreq *hreq = CONTAINER_OF_XREQ(struct afb_hreq, xreq);
936         struct json_object *sub, *reply;
937         const char *reqid;
938         struct MHD_Response *response;
939
940         /* create the reply */
941         reply = afb_msg_json_reply(object, error, info, &xreq->context);
942
943         /* append the req id on need */
944         reqid = afb_hreq_get_argument(hreq, long_key_for_reqid);
945         if (reqid == NULL)
946                 reqid = afb_hreq_get_argument(hreq, short_key_for_reqid);
947         if (reqid != NULL && json_object_object_get_ex(reply, "request", &sub))
948                 json_object_object_add(sub, "reqid", json_object_new_string(reqid));
949
950         response = MHD_create_response_from_callback(
951                         (uint64_t)strlen(get_json_string(reply)),
952                         SIZE_RESPONSE_BUFFER,
953                         (void*)send_json_cb,
954                         reply,
955                         (void*)json_object_put);
956
957         /* handle authorisation feedback */
958         if (error == afb_error_text_invalid_token)
959                 afb_hreq_reply(hreq, MHD_HTTP_UNAUTHORIZED, response, MHD_HTTP_HEADER_WWW_AUTHENTICATE, "error=\"invalid_token\"", NULL);
960         else if (error == afb_error_text_insufficient_scope)
961                 afb_hreq_reply(hreq, MHD_HTTP_FORBIDDEN, response, MHD_HTTP_HEADER_WWW_AUTHENTICATE, "error=\"insufficient_scope\"", NULL);
962         else
963                 afb_hreq_reply(hreq, MHD_HTTP_OK, response, NULL);
964 }
965
966 void afb_hreq_call(struct afb_hreq *hreq, struct afb_apiset *apiset, const char *api, size_t lenapi, const char *verb, size_t lenverb)
967 {
968         hreq->xreq.request.called_api = strndup(api, lenapi);
969         hreq->xreq.request.called_verb = strndup(verb, lenverb);
970         if (hreq->xreq.request.called_api == NULL || hreq->xreq.request.called_verb == NULL) {
971                 ERROR("Out of memory");
972                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
973         } else if (afb_hreq_init_context(hreq) < 0) {
974                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
975         } else {
976                 afb_xreq_unhooked_addref(&hreq->xreq);
977                 afb_xreq_process(&hreq->xreq, apiset);
978         }
979 }
980
981 int afb_hreq_init_context(struct afb_hreq *hreq)
982 {
983         const char *uuid;
984         const char *token;
985         struct afb_token *tok;
986
987         if (hreq->xreq.context.session != NULL)
988                 return 0;
989
990         /* get the uuid of the session */
991         uuid = afb_hreq_get_header(hreq, long_key_for_uuid);
992         if (uuid == NULL) {
993                 uuid = afb_hreq_get_argument(hreq, long_key_for_uuid);
994                 if (uuid == NULL) {
995                         uuid = afb_hreq_get_cookie(hreq, cookie_name);
996                         if (uuid == NULL)
997                                 uuid = afb_hreq_get_argument(hreq, short_key_for_uuid);
998                 }
999         }
1000
1001         /* get the authorisation token */
1002         token = afb_hreq_get_authorization_bearer(hreq);
1003         if (token == NULL) {
1004                 token = afb_hreq_get_argument(hreq, key_for_access_token);
1005                 if (token == NULL) {
1006                         token = afb_hreq_get_header(hreq, long_key_for_token);
1007                         if (token == NULL) {
1008                                 token = afb_hreq_get_argument(hreq, long_key_for_token);
1009                                 if (token == NULL)
1010                                         token = afb_hreq_get_argument(hreq, short_key_for_token);
1011                         }
1012                 }
1013         }
1014         tok = NULL;
1015         if (token)
1016                 afb_token_get(&tok, token);
1017
1018         return afb_context_connect(&hreq->xreq.context, uuid, tok, NULL);
1019 }
1020
1021 int afb_hreq_init_cookie(int port, const char *path, int maxage)
1022 {
1023         int rc;
1024
1025         free(cookie_name);
1026         free(cookie_setter);
1027         cookie_name = NULL;
1028         cookie_setter = NULL;
1029
1030         path = path ? : "/";
1031         rc = asprintf(&cookie_name, "%s-%d", long_key_for_uuid, port);
1032         if (rc < 0)
1033                 return 0;
1034         rc = asprintf(&cookie_setter, "%s=%%s; Path=%s; Max-Age=%d; HttpOnly",
1035                         cookie_name, path, maxage);
1036         if (rc < 0)
1037                 return 0;
1038         return 1;
1039 }
1040
1041 struct afb_xreq *afb_hreq_to_xreq(struct afb_hreq *hreq)
1042 {
1043         return &hreq->xreq;
1044 }
1045
1046 struct afb_hreq *afb_hreq_create()
1047 {
1048         struct afb_hreq *hreq = calloc(1, sizeof *hreq);
1049         if (hreq) {
1050                 /* init the request */
1051                 afb_xreq_init(&hreq->xreq, &afb_hreq_xreq_query_itf);
1052                 hreq->reqid = ++global_reqids;
1053         }
1054         return hreq;
1055 }
1056