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