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