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