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