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