Add comments about always setting INFER_EXTENSION.
[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         /*
278          * Set some well-known extensions
279          * Note that it is mandatory for example for css files in order to provide
280          * right mimetype that must be text/css (otherwise chrome browser will not
281          * load correctly css file) while libmagic returns text/plain.
282          */
283         const char *extension = strrchr(filename, '.');
284         if (extension) {
285                 static const char *const known[][2] = {
286                         { ".js",   "text/javascript" },
287                         { ".html", "text/html" },
288                         { ".css",  "text/css" },
289                         { ".ico",  "image/x-icon"},
290                         { ".png",  "image/png" },
291                         { ".svg",  "image/svg+xml" },
292                         { ".ttf",  "application/x-font-ttf"},
293                         { NULL, NULL }
294                 };
295                 int i = 0;
296                 while (known[i][0]) {
297                         if (!strcasecmp(extension, known[i][0])) {
298                                 result = known[i][1];
299                                 break;
300                         }
301                         i++;
302                 }
303         }
304 #endif
305 #if defined(USE_MAGIC_MIME_TYPE)
306         if (result == NULL)
307                 result = magic_mimetype_fd(fd);
308 #endif
309         return result;
310 }
311
312 void afb_hreq_addref(struct afb_hreq *hreq)
313 {
314         hreq->refcount++;
315 }
316
317 void afb_hreq_unref(struct afb_hreq *hreq)
318 {
319         struct hreq_data *data;
320
321         if (hreq == NULL || --hreq->refcount)
322                 return;
323
324         if (hreq->postform != NULL)
325                 MHD_destroy_post_processor(hreq->postform);
326         for (data = hreq->data; data; data = hreq->data) {
327                 hreq->data = data->next;
328                 if (data->path) {
329                         unlink(data->path);
330                         free(data->path);
331                 }
332                 free(data->key);
333                 free(data->value);
334                 free(data);
335         }
336         afb_context_disconnect(&hreq->context);
337         json_object_put(hreq->json);
338         free(hreq);
339 }
340
341 /*
342  * Removes the 'prefix' of 'length' from the tail of 'hreq'
343  * if and only if the prefix exists and is terminated by a leading
344  * slash
345  */
346 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
347 {
348         /* check the prefix ? */
349         if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
350             || strncasecmp(prefix, hreq->tail, length))
351                 return 0;
352
353         /* removes successives / */
354         while (length < hreq->lentail && hreq->tail[length + 1] == '/')
355                 length++;
356
357         /* update the tail */
358         hreq->lentail -= length;
359         hreq->tail += length;
360         return 1;
361 }
362
363 int afb_hreq_valid_tail(struct afb_hreq *hreq)
364 {
365         return validsubpath(hreq->tail);
366 }
367
368 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
369 {
370         afb_hreq_reply_empty(hreq, status, NULL);
371 }
372
373 int afb_hreq_redirect_to_ending_slash_if_needed(struct afb_hreq *hreq)
374 {
375         char *tourl;
376
377         if (hreq->url[hreq->lenurl - 1] == '/')
378                 return 0;
379
380         /* the redirect is needed for reliability of relative path */
381         tourl = alloca(hreq->lenurl + 2);
382         memcpy(tourl, hreq->url, hreq->lenurl);
383         tourl[hreq->lenurl] = '/';
384         tourl[hreq->lenurl + 1] = 0;
385         afb_hreq_redirect_to(hreq, tourl, 1);
386         return 1;
387 }
388
389 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
390 {
391         int rc;
392         int fd;
393         unsigned int status;
394         struct stat st;
395         char etag[1 + 2 * 8];
396         const char *inm;
397         struct MHD_Response *response;
398         const char *mimetype;
399
400         /* Opens the file or directory */
401         if (filename[0]) {
402                 fd = openat(dirfd, filename, O_RDONLY);
403                 if (fd < 0) {
404                         if (errno == ENOENT)
405                                 return 0;
406                         afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
407                         return 1;
408                 }
409         } else {
410                 fd = dup(dirfd);
411                 if (fd < 0) {
412                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
413                         return 1;
414                 }
415         }
416
417         /* Retrieves file's status */
418         if (fstat(fd, &st) != 0) {
419                 close(fd);
420                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
421                 return 1;
422         }
423
424         /* serve directory */
425         if (S_ISDIR(st.st_mode)) {
426                 rc = afb_hreq_redirect_to_ending_slash_if_needed(hreq);
427                 if (rc == 0) {
428                         static const char *indexes[] = { "index.html", NULL };
429                         int i = 0;
430                         while (indexes[i] != NULL) {
431                                 if (faccessat(fd, indexes[i], R_OK, 0) == 0) {
432                                         rc = afb_hreq_reply_file_if_exist(hreq, fd, indexes[i]);
433                                         break;
434                                 }
435                                 i++;
436                         }
437                 }
438                 close(fd);
439                 return rc;
440         }
441
442         /* Don't serve special files */
443         if (!S_ISREG(st.st_mode)) {
444                 close(fd);
445                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
446                 return 1;
447         }
448
449         /* Check the method */
450         if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
451                 close(fd);
452                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
453                 return 1;
454         }
455
456         /* computes the etag */
457         sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
458
459         /* checks the etag */
460         inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
461         if (inm && 0 == strcmp(inm, etag)) {
462                 /* etag ok, return NOT MODIFIED */
463                 close(fd);
464                 DEBUG("Not Modified: [%s]", filename);
465                 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
466                 status = MHD_HTTP_NOT_MODIFIED;
467         } else {
468                 /* check the size */
469                 if (st.st_size != (off_t) (size_t) st.st_size) {
470                         close(fd);
471                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
472                         return 1;
473                 }
474
475                 /* create the response */
476                 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
477                 status = MHD_HTTP_OK;
478
479                 /* set the type */
480                 mimetype = mimetype_fd_name(fd, filename);
481                 if (mimetype != NULL)
482                         MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
483         }
484
485         /* fills the value and send */
486         afb_hreq_reply(hreq, status, response,
487                         MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout,
488                         MHD_HTTP_HEADER_ETAG, etag,
489                         NULL);
490         return 1;
491 }
492
493 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
494 {
495         int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
496         if (rc == 0)
497                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
498         return 1;
499 }
500
501 int afb_hreq_reply_locale_file_if_exist(struct afb_hreq *hreq, struct locale_search *search, const char *filename)
502 {
503         int rc;
504         int fd;
505         unsigned int status;
506         struct stat st;
507         char etag[1 + 2 * 8];
508         const char *inm;
509         struct MHD_Response *response;
510         const char *mimetype;
511
512         /* Opens the file or directory */
513         fd = locale_search_open(search, filename[0] ? filename : ".", O_RDONLY);
514         if (fd < 0) {
515                 if (errno == ENOENT)
516                         return 0;
517                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
518                 return 1;
519         }
520
521         /* Retrieves file's status */
522         if (fstat(fd, &st) != 0) {
523                 close(fd);
524                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
525                 return 1;
526         }
527
528         /* serve directory */
529         if (S_ISDIR(st.st_mode)) {
530                 rc = afb_hreq_redirect_to_ending_slash_if_needed(hreq);
531                 if (rc == 0) {
532                         static const char *indexes[] = { "index.html", NULL };
533                         int i = 0;
534                         size_t length = strlen(filename);
535                         char *extname = alloca(length + 30); /* 30 is enough to old data of indexes */
536                         memcpy(extname, filename, length);
537                         if (length && extname[length - 1] != '/')
538                                 extname[length++] = '/';
539                         while (rc == 0 && indexes[i] != NULL) {
540                                 strcpy(extname + length, indexes[i++]);
541                                 rc = afb_hreq_reply_locale_file_if_exist(hreq, search, extname);
542                         }
543                 }
544                 close(fd);
545                 return rc;
546         }
547
548         /* Don't serve special files */
549         if (!S_ISREG(st.st_mode)) {
550                 close(fd);
551                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
552                 return 1;
553         }
554
555         /* Check the method */
556         if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
557                 close(fd);
558                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
559                 return 1;
560         }
561
562         /* computes the etag */
563         sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
564
565         /* checks the etag */
566         inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
567         if (inm && 0 == strcmp(inm, etag)) {
568                 /* etag ok, return NOT MODIFIED */
569                 close(fd);
570                 DEBUG("Not Modified: [%s]", filename);
571                 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
572                 status = MHD_HTTP_NOT_MODIFIED;
573         } else {
574                 /* check the size */
575                 if (st.st_size != (off_t) (size_t) st.st_size) {
576                         close(fd);
577                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
578                         return 1;
579                 }
580
581                 /* create the response */
582                 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
583                 status = MHD_HTTP_OK;
584
585                 /* set the type */
586                 mimetype = mimetype_fd_name(fd, filename);
587                 if (mimetype != NULL)
588                         MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
589         }
590
591         /* fills the value and send */
592         afb_hreq_reply(hreq, status, response,
593                         MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout,
594                         MHD_HTTP_HEADER_ETAG, etag,
595                         NULL);
596         return 1;
597 }
598
599 int afb_hreq_reply_locale_file(struct afb_hreq *hreq, struct locale_search *search, const char *filename)
600 {
601         int rc = afb_hreq_reply_locale_file_if_exist(hreq, search, filename);
602         if (rc == 0)
603                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
604         return 1;
605 }
606
607 struct _mkq_ {
608         int count;
609         size_t length;
610         size_t alloc;
611         char *text;
612 };
613
614 static void _mkq_add_(struct _mkq_ *mkq, char value)
615 {
616         char *text = mkq->text;
617         if (text != NULL) {
618                 if (mkq->length == mkq->alloc) {
619                         mkq->alloc += 100;
620                         text = realloc(text, mkq->alloc);
621                         if (text == NULL) {
622                                 free(mkq->text);
623                                 mkq->text = NULL;
624                                 return;
625                         }
626                         mkq->text = text;
627                 }
628                 text[mkq->length++] = value;
629         }
630 }
631
632 static void _mkq_add_hex_(struct _mkq_ *mkq, char value)
633 {
634         _mkq_add_(mkq, (char)(value < 10 ? value + '0' : value + 'A' - 10));
635 }
636
637 static void _mkq_add_esc_(struct _mkq_ *mkq, char value)
638 {
639         _mkq_add_(mkq, '%');
640         _mkq_add_hex_(mkq, (char)((value >> 4) & 15));
641         _mkq_add_hex_(mkq, (char)(value & 15));
642 }
643
644 static void _mkq_add_char_(struct _mkq_ *mkq, char value)
645 {
646         if (value <= ' ' || value >= 127)
647                 _mkq_add_esc_(mkq, value);
648         else
649                 switch(value) {
650                 case '=':
651                 case '&':
652                 case '%':
653                         _mkq_add_esc_(mkq, value);
654                         break;
655                 default:
656                         _mkq_add_(mkq, value);
657                 }
658 }
659
660 static void _mkq_append_(struct _mkq_ *mkq, const char *value)
661 {
662         while(*value)
663                 _mkq_add_char_(mkq, *value++);
664 }
665
666 static int _mkquery_(struct _mkq_ *mkq, enum MHD_ValueKind kind, const char *key, const char *value)
667 {
668         _mkq_add_(mkq, mkq->count++ ? '&' : '?');
669         _mkq_append_(mkq, key);
670         if (value != NULL) {
671                 _mkq_add_(mkq, '=');
672                 _mkq_append_(mkq, value);
673         }
674         return 1;
675 }
676
677 static char *url_with_query(struct afb_hreq *hreq, const char *url)
678 {
679         struct _mkq_ mkq;
680
681         mkq.count = 0;
682         mkq.length = strlen(url);
683         mkq.alloc = mkq.length + 1000;
684         mkq.text = malloc(mkq.alloc);
685         if (mkq.text != NULL) {
686                 strcpy(mkq.text, url);
687                 MHD_get_connection_values(hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_mkquery_, &mkq);
688                 _mkq_add_(&mkq, 0);
689         }
690         return mkq.text;
691 }
692
693 void afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url, int add_query_part)
694 {
695         const char *to;
696         char *wqp;
697
698         wqp = add_query_part ? url_with_query(hreq, url) : NULL;
699         to = wqp ? : url;
700         afb_hreq_reply_static(hreq, MHD_HTTP_MOVED_PERMANENTLY, 0, NULL,
701                         MHD_HTTP_HEADER_LOCATION, to, NULL);
702         DEBUG("redirect from [%s] to [%s]", hreq->url, url);
703         free(wqp);
704 }
705
706 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
707 {
708         return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
709 }
710
711 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
712 {
713         struct hreq_data *data = get_data(hreq, name, 0);
714         return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
715 }
716
717 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
718 {
719         return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
720 }
721
722 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
723 {
724         void *p;
725         struct hreq_data *hdat = get_data(hreq, key, 1);
726         if (hdat->path != NULL) {
727                 return 0;
728         }
729         p = realloc(hdat->value, hdat->length + size + 1);
730         if (p == NULL) {
731                 return 0;
732         }
733         hdat->value = p;
734         memcpy(&hdat->value[hdat->length], data, size);
735         hdat->length += size;
736         hdat->value[hdat->length] = 0;
737         return 1;
738 }
739
740 int afb_hreq_init_download_path(const char *directory)
741 {
742         struct stat st;
743         size_t n;
744         char *p;
745
746         if (access(directory, R_OK|W_OK)) {
747                 /* no read/write access */
748                 return -1;
749         }
750         if (stat(directory, &st)) {
751                 /* can't get info */
752                 return -1;
753         }
754         if (!S_ISDIR(st.st_mode)) {
755                 /* not a directory */
756                 errno = ENOTDIR;
757                 return -1;
758         }
759         n = strlen(directory);
760         while(n > 1 && directory[n-1] == '/') n--;
761         p = malloc(n + 8);
762         if (p == NULL) {
763                 /* can't allocate memory */
764                 errno = ENOMEM;
765                 return -1;
766         }
767         memcpy(p, directory, n);
768         p[n++] = '/';
769         p[n++] = 'X';
770         p[n++] = 'X';
771         p[n++] = 'X';
772         p[n++] = 'X';
773         p[n++] = 'X';
774         p[n++] = 'X';
775         p[n] = 0;
776         free(tmp_pattern);
777         tmp_pattern = p;
778         return 0;
779 }
780
781 static int opentempfile(char **path)
782 {
783         int fd;
784         char *fname;
785
786         fname = strdup(tmp_pattern ? : "XXXXXX"); /* TODO improve the path */
787         if (fname == NULL)
788                 return -1;
789
790         fd = mkostemp(fname, O_CLOEXEC|O_WRONLY);
791         if (fd < 0)
792                 free(fname);
793         else
794                 *path = fname;
795         return fd;
796 }
797
798 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
799 {
800         int fd;
801         ssize_t sz;
802         struct hreq_data *hdat = get_data(hreq, key, 1);
803
804         if (hdat->value == NULL) {
805                 hdat->value = strdup(file);
806                 if (hdat->value == NULL)
807                         return 0;
808                 fd = opentempfile(&hdat->path);
809         } else if (strcmp(hdat->value, file) || hdat->path == NULL) {
810                 return 0;
811         } else {
812                 fd = open(hdat->path, O_WRONLY|O_APPEND);
813         }
814         if (fd < 0)
815                 return 0;
816         while (size) {
817                 sz = write(fd, data, size);
818                 if (sz >= 0) {
819                         hdat->length += (size_t)sz;
820                         size -= (size_t)sz;
821                         data += sz;
822                 } else if (errno != EINTR)
823                         break;
824         }
825         close(fd);
826         return !size;
827 }
828
829 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
830 {
831         return (struct afb_req){ .itf = &afb_hreq_req_itf, .closure = hreq };
832 }
833
834 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
835 {
836         const char *value;
837         struct hreq_data *hdat = get_data(hreq, name, 0);
838         if (hdat)
839                 return (struct afb_arg){
840                         .name = hdat->key,
841                         .value = hdat->value,
842                         .path = hdat->path
843                 };
844
845         value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
846         return (struct afb_arg){
847                 .name = value == NULL ? NULL : name,
848                 .value = value,
849                 .path = NULL
850         };
851 }
852
853 static int _iterargs_(struct json_object *obj, enum MHD_ValueKind kind, const char *key, const char *value)
854 {
855         json_object_object_add(obj, key, value ? json_object_new_string(value) : NULL);
856         return 1;
857 }
858
859 static struct json_object *req_json(struct afb_hreq *hreq)
860 {
861         struct hreq_data *hdat;
862         struct json_object *obj, *val;
863
864         obj = hreq->json;
865         if (obj == NULL) {
866                 hreq->json = obj = json_object_new_object();
867                 if (obj == NULL) {
868                 } else {
869                         MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, obj);
870                         for (hdat = hreq->data ; hdat ; hdat = hdat->next) {
871                                 if (hdat->path == NULL)
872                                         val = hdat->value ? json_object_new_string(hdat->value) : NULL;
873                                 else {
874                                         val = json_object_new_object();
875                                         if (val == NULL) {
876                                         } else {
877                                                 json_object_object_add(val, "file", json_object_new_string(hdat->value));
878                                                 json_object_object_add(val, "path", json_object_new_string(hdat->path));
879                                         }
880                                 }
881                                 json_object_object_add(obj, hdat->key, val);
882                         }
883                 }
884         }
885         return obj;
886 }
887
888 static const char *req_raw(struct afb_hreq *hreq, size_t *size)
889 {
890         const char *result = json_object_get_string(req_json(hreq));
891         *size = result ? strlen(result) : 0;
892         return result;
893 }
894
895 static void req_send(struct afb_hreq *hreq, const char *buffer, size_t size)
896 {
897         afb_hreq_reply_copy(hreq, MHD_HTTP_OK, size, buffer, NULL);
898 }
899
900 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
901 {
902         ssize_t len = stpncpy(buf, json_object_to_json_string_ext(obj, JSON_C_TO_STRING_PLAIN)+pos, max) - buf;
903         return len ? : (ssize_t)MHD_CONTENT_READER_END_OF_STREAM;
904 }
905
906 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
907 {
908         struct json_object *reply;
909         const char *reqid;
910         struct MHD_Response *response;
911
912         reqid = afb_hreq_get_argument(hreq, long_key_for_reqid);
913         if (reqid == NULL)
914                 reqid = afb_hreq_get_argument(hreq, short_key_for_reqid);
915
916         reply = afb_msg_json_reply(status, info, resp, &hreq->context, reqid);
917
918         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);
919         afb_hreq_reply(hreq, retcode, response, NULL);
920 }
921
922 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
923 {
924         req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
925 }
926
927 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
928 {
929         req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
930 }
931
932 static int req_subscribe_unsubscribe_error(struct afb_hreq *hreq, struct afb_event event)
933 {
934         errno = EINVAL;
935         return -1;
936 }
937
938 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)
939 {
940         afb_subcall(&hreq->context, api, verb, args, callback, closure, (struct afb_req){ .itf = &afb_hreq_req_itf, .closure = hreq });
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->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->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