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