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