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