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