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