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