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