afb-hreq: Handle HTTP header Authorization
[src/app-framework-binder.git] / src / afb-hreq.c
1 /*
2  * Copyright (C) 2016-2019 "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 <ctype.h>
24 #include <assert.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <sys/stat.h>
28
29 #include <microhttpd.h>
30 #include <json-c/json.h>
31 #if !defined(JSON_C_TO_STRING_NOSLASHESCAPE)
32 #define JSON_C_TO_STRING_NOSLASHESCAPE 0
33 #endif
34
35 #if defined(USE_MAGIC_MIME_TYPE)
36 #include <magic.h>
37 #endif
38
39 #include "afb-method.h"
40 #include "afb-msg-json.h"
41 #include "afb-context.h"
42 #include "afb-hreq.h"
43 #include "afb-hsrv.h"
44 #include "afb-session.h"
45 #include "afb-cred.h"
46 #include "verbose.h"
47 #include "locale-root.h"
48
49 #define SIZE_RESPONSE_BUFFER   8192
50
51 static int global_reqids = 0;
52
53 static char empty_string[] = "";
54
55 static const char long_key_for_uuid[] = "x-afb-uuid";
56 static const char short_key_for_uuid[] = "uuid";
57
58 static const char long_key_for_token[] = "x-afb-token";
59 static const char short_key_for_token[] = "token";
60
61 static const char long_key_for_reqid[] = "x-afb-reqid";
62 static const char short_key_for_reqid[] = "reqid";
63
64 static char *cookie_name = NULL;
65 static char *cookie_setter = NULL;
66 static char *tmp_pattern = NULL;
67
68 /*
69  * Structure for storing key/values read from POST requests
70  */
71 struct hreq_data {
72         struct hreq_data *next; /* chain to next data */
73         char *key;              /* key name */
74         size_t length;          /* length of the value (used for appending) */
75         char *value;            /* the value (or original filename) */
76         char *path;             /* path of the file saved */
77 };
78
79 static struct json_object *req_json(struct afb_xreq *xreq);
80 static struct afb_arg req_get(struct afb_xreq *xreq, const char *name);
81 static void req_reply(struct afb_xreq *xreq, struct json_object *object, const char *error, const char *info);
82 static void req_destroy(struct afb_xreq *xreq);
83
84 const struct afb_xreq_query_itf afb_hreq_xreq_query_itf = {
85         .json = req_json,
86         .get = req_get,
87         .reply = req_reply,
88         .unref = req_destroy
89 };
90
91 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
92 {
93         struct hreq_data *data = hreq->data;
94         while (data != NULL) {
95                 if (!strcasecmp(data->key, key))
96                         return data;
97                 data = data->next;
98         }
99         if (create) {
100                 data = calloc(1, sizeof *data);
101                 if (data != NULL) {
102                         data->key = strdup(key);
103                         if (data->key == NULL) {
104                                 free(data);
105                                 data = NULL;
106                         } else {
107                                 data->next = hreq->data;
108                                 hreq->data = data;
109                         }
110                 }
111         }
112         return data;
113 }
114
115 /* a valid subpath is a relative path not looking deeper than root using .. */
116 static int validsubpath(const char *subpath)
117 {
118         int l = 0, i = 0;
119
120         while (subpath[i]) {
121                 switch (subpath[i++]) {
122                 case '.':
123                         if (!subpath[i])
124                                 break;
125                         if (subpath[i] == '/') {
126                                 i++;
127                                 break;
128                         }
129                         if (subpath[i++] == '.') {
130                                 if (!subpath[i]) {
131                                         if (--l < 0)
132                                                 return 0;
133                                         break;
134                                 }
135                                 if (subpath[i++] == '/') {
136                                         if (--l < 0)
137                                                 return 0;
138                                         break;
139                                 }
140                         }
141                 default:
142                         while (subpath[i] && subpath[i] != '/')
143                                 i++;
144                         l++;
145                 case '/':
146                         break;
147                 }
148         }
149         return 1;
150 }
151
152 static void afb_hreq_reply_v(struct afb_hreq *hreq, unsigned status, struct MHD_Response *response, va_list args)
153 {
154         char *cookie;
155         const char *k, *v;
156
157         if (hreq->replied != 0)
158                 return;
159
160         k = va_arg(args, const char *);
161         while (k != NULL) {
162                 v = va_arg(args, const char *);
163                 MHD_add_response_header(response, k, v);
164                 k = va_arg(args, const char *);
165         }
166         v = afb_context_sent_uuid(&hreq->xreq.context);
167         if (v != NULL && asprintf(&cookie, cookie_setter, v) > 0) {
168                 MHD_add_response_header(response, MHD_HTTP_HEADER_SET_COOKIE, cookie);
169                 free(cookie);
170         }
171         MHD_queue_response(hreq->connection, status, response);
172         MHD_destroy_response(response);
173
174         hreq->replied = 1;
175         if (hreq->suspended != 0) {
176                 MHD_resume_connection (hreq->connection);
177                 hreq->suspended = 0;
178                 afb_hsrv_run(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                         /* keep it sorted for dichotomic search */
277                         { ".css",       "text/css" },
278                         { ".gif",       "image/gif" },
279                         { ".html",      "text/html" },
280                         { ".htm",       "text/html" },
281                         { ".ico",       "image/x-icon"},
282                         { ".jpeg",      "image/jpeg" },
283                         { ".jpg",       "image/jpeg" },
284                         { ".js",        "text/javascript" },
285                         { ".json",      "application/json" },
286                         { ".mp3",       "audio/mpeg" },
287                         { ".png",       "image/png" },
288                         { ".svg",       "image/svg+xml" },
289                         { ".ttf",       "application/x-font-ttf"},
290                         { ".txt",       "text/plain" },
291                         { ".wav",       "audio/x-wav" },
292                         { ".xht",       "application/xhtml+xml" },
293                         { ".xhtml",     "application/xhtml+xml" },
294                         { ".xml",       "application/xml" }
295                 };
296                 int i, c, l = 0, u = sizeof known / sizeof *known;
297                 while (l < u) {
298                         i = (l + u) >> 1;
299                         c = strcasecmp(extension, known[i][0]);
300                         if (!c) {
301                                 result = known[i][1];
302                                 break;
303                         }
304                         if (c < 0)
305                                 u = i;
306                         else
307                                 l = i + 1;
308                 }
309         }
310 #endif
311 #if defined(USE_MAGIC_MIME_TYPE)
312         if (result == NULL)
313                 result = magic_mimetype_fd(fd);
314 #endif
315         return result;
316 }
317
318 static void req_destroy(struct afb_xreq *xreq)
319 {
320         struct afb_hreq *hreq = CONTAINER_OF_XREQ(struct afb_hreq, xreq);
321         struct hreq_data *data;
322
323         if (hreq->postform != NULL)
324                 MHD_destroy_post_processor(hreq->postform);
325         if (hreq->tokener != NULL)
326                 json_tokener_free(hreq->tokener);
327
328         for (data = hreq->data; data; data = hreq->data) {
329                 hreq->data = data->next;
330                 if (data->path) {
331                         unlink(data->path);
332                         free(data->path);
333                 }
334                 free(data->key);
335                 free(data->value);
336                 free(data);
337         }
338         afb_context_disconnect(&hreq->xreq.context);
339         json_object_put(hreq->json);
340         free((char*)hreq->xreq.request.called_api);
341         free((char*)hreq->xreq.request.called_verb);
342         afb_cred_unref(hreq->xreq.cred);
343         free(hreq);
344 }
345
346 void afb_hreq_addref(struct afb_hreq *hreq)
347 {
348         afb_xreq_unhooked_addref(&hreq->xreq);
349 }
350
351 void afb_hreq_unref(struct afb_hreq *hreq)
352 {
353         if (hreq->replied)
354                 hreq->xreq.replied = 1;
355         afb_xreq_unhooked_unref(&hreq->xreq);
356 }
357
358 /*
359  * Removes the 'prefix' of 'length' from the tail of 'hreq'
360  * if and only if the prefix exists and is terminated by a leading
361  * slash
362  */
363 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
364 {
365         /* check the prefix ? */
366         if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
367             || strncasecmp(prefix, hreq->tail, length))
368                 return 0;
369
370         /* removes successives / */
371         while (length < hreq->lentail && hreq->tail[length + 1] == '/')
372                 length++;
373
374         /* update the tail */
375         hreq->lentail -= length;
376         hreq->tail += length;
377         return 1;
378 }
379
380 int afb_hreq_valid_tail(struct afb_hreq *hreq)
381 {
382         return validsubpath(hreq->tail);
383 }
384
385 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
386 {
387         afb_hreq_reply_empty(hreq, status, NULL);
388 }
389
390 int afb_hreq_redirect_to_ending_slash_if_needed(struct afb_hreq *hreq)
391 {
392         char *tourl;
393
394         if (hreq->url[hreq->lenurl - 1] == '/')
395                 return 0;
396
397         /* the redirect is needed for reliability of relative path */
398         tourl = alloca(hreq->lenurl + 2);
399         memcpy(tourl, hreq->url, hreq->lenurl);
400         tourl[hreq->lenurl] = '/';
401         tourl[hreq->lenurl + 1] = 0;
402         afb_hreq_redirect_to(hreq, tourl, 1);
403         return 1;
404 }
405
406 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
407 {
408         int rc;
409         int fd;
410         unsigned int status;
411         struct stat st;
412         char etag[1 + 2 * 8];
413         const char *inm;
414         struct MHD_Response *response;
415         const char *mimetype;
416
417         /* Opens the file or directory */
418         if (filename[0]) {
419                 fd = openat(dirfd, filename, O_RDONLY);
420                 if (fd < 0) {
421                         if (errno == ENOENT)
422                                 return 0;
423                         afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
424                         return 1;
425                 }
426         } else {
427                 fd = dup(dirfd);
428                 if (fd < 0) {
429                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
430                         return 1;
431                 }
432         }
433
434         /* Retrieves file's status */
435         if (fstat(fd, &st) != 0) {
436                 close(fd);
437                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
438                 return 1;
439         }
440
441         /* serve directory */
442         if (S_ISDIR(st.st_mode)) {
443                 rc = afb_hreq_redirect_to_ending_slash_if_needed(hreq);
444                 if (rc == 0) {
445                         static const char *indexes[] = { "index.html", NULL };
446                         int i = 0;
447                         while (indexes[i] != NULL) {
448                                 if (faccessat(fd, indexes[i], R_OK, 0) == 0) {
449                                         rc = afb_hreq_reply_file_if_exist(hreq, fd, indexes[i]);
450                                         break;
451                                 }
452                                 i++;
453                         }
454                 }
455                 close(fd);
456                 return rc;
457         }
458
459         /* Don't serve special files */
460         if (!S_ISREG(st.st_mode)) {
461                 close(fd);
462                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
463                 return 1;
464         }
465
466         /* Check the method */
467         if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
468                 close(fd);
469                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
470                 return 1;
471         }
472
473         /* computes the etag */
474         sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
475
476         /* checks the etag */
477         inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
478         if (inm && 0 == strcmp(inm, etag)) {
479                 /* etag ok, return NOT MODIFIED */
480                 close(fd);
481                 DEBUG("Not Modified: [%s]", filename);
482                 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
483                 status = MHD_HTTP_NOT_MODIFIED;
484         } else {
485                 /* check the size */
486                 if (st.st_size != (off_t) (size_t) st.st_size) {
487                         close(fd);
488                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
489                         return 1;
490                 }
491
492                 /* create the response */
493                 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
494                 status = MHD_HTTP_OK;
495
496                 /* set the type */
497                 mimetype = mimetype_fd_name(fd, filename);
498                 if (mimetype != NULL)
499                         MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
500         }
501
502         /* fills the value and send */
503         afb_hreq_reply(hreq, status, response,
504                         MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout,
505                         MHD_HTTP_HEADER_ETAG, etag,
506                         NULL);
507         return 1;
508 }
509
510 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
511 {
512         int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
513         if (rc == 0)
514                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
515         return 1;
516 }
517
518 int afb_hreq_reply_locale_file_if_exist(struct afb_hreq *hreq, struct locale_search *search, const char *filename)
519 {
520         int rc;
521         int fd;
522         unsigned int status;
523         struct stat st;
524         char etag[1 + 2 * 8];
525         const char *inm;
526         struct MHD_Response *response;
527         const char *mimetype;
528
529         /* Opens the file or directory */
530         fd = locale_search_open(search, filename[0] ? filename : ".", O_RDONLY);
531         if (fd < 0) {
532                 if (errno == ENOENT)
533                         return 0;
534                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
535                 return 1;
536         }
537
538         /* Retrieves file's status */
539         if (fstat(fd, &st) != 0) {
540                 close(fd);
541                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
542                 return 1;
543         }
544
545         /* serve directory */
546         if (S_ISDIR(st.st_mode)) {
547                 rc = afb_hreq_redirect_to_ending_slash_if_needed(hreq);
548                 if (rc == 0) {
549                         static const char *indexes[] = { "index.html", NULL };
550                         int i = 0;
551                         size_t length = strlen(filename);
552                         char *extname = alloca(length + 30); /* 30 is enough to old data of indexes */
553                         memcpy(extname, filename, length);
554                         if (length && extname[length - 1] != '/')
555                                 extname[length++] = '/';
556                         while (rc == 0 && indexes[i] != NULL) {
557                                 strcpy(extname + length, indexes[i++]);
558                                 rc = afb_hreq_reply_locale_file_if_exist(hreq, search, extname);
559                         }
560                 }
561                 close(fd);
562                 return rc;
563         }
564
565         /* Don't serve special files */
566         if (!S_ISREG(st.st_mode)) {
567                 close(fd);
568                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
569                 return 1;
570         }
571
572         /* Check the method */
573         if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
574                 close(fd);
575                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
576                 return 1;
577         }
578
579         /* computes the etag */
580         sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
581
582         /* checks the etag */
583         inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
584         if (inm && 0 == strcmp(inm, etag)) {
585                 /* etag ok, return NOT MODIFIED */
586                 close(fd);
587                 DEBUG("Not Modified: [%s]", filename);
588                 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
589                 status = MHD_HTTP_NOT_MODIFIED;
590         } else {
591                 /* check the size */
592                 if (st.st_size != (off_t) (size_t) st.st_size) {
593                         close(fd);
594                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
595                         return 1;
596                 }
597
598                 /* create the response */
599                 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
600                 status = MHD_HTTP_OK;
601
602                 /* set the type */
603                 mimetype = mimetype_fd_name(fd, filename);
604                 if (mimetype != NULL)
605                         MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
606         }
607
608         /* fills the value and send */
609         afb_hreq_reply(hreq, status, response,
610                         MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout,
611                         MHD_HTTP_HEADER_ETAG, etag,
612                         NULL);
613         return 1;
614 }
615
616 int afb_hreq_reply_locale_file(struct afb_hreq *hreq, struct locale_search *search, const char *filename)
617 {
618         int rc = afb_hreq_reply_locale_file_if_exist(hreq, search, filename);
619         if (rc == 0)
620                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
621         return 1;
622 }
623
624 struct _mkq_ {
625         int count;
626         size_t length;
627         size_t alloc;
628         char *text;
629 };
630
631 static void _mkq_add_(struct _mkq_ *mkq, char value)
632 {
633         char *text = mkq->text;
634         if (text != NULL) {
635                 if (mkq->length == mkq->alloc) {
636                         mkq->alloc += 100;
637                         text = realloc(text, mkq->alloc);
638                         if (text == NULL) {
639                                 free(mkq->text);
640                                 mkq->text = NULL;
641                                 return;
642                         }
643                         mkq->text = text;
644                 }
645                 text[mkq->length++] = value;
646         }
647 }
648
649 static void _mkq_add_hex_(struct _mkq_ *mkq, char value)
650 {
651         _mkq_add_(mkq, (char)(value < 10 ? value + '0' : value + 'A' - 10));
652 }
653
654 static void _mkq_add_esc_(struct _mkq_ *mkq, char value)
655 {
656         _mkq_add_(mkq, '%');
657         _mkq_add_hex_(mkq, (char)((value >> 4) & 15));
658         _mkq_add_hex_(mkq, (char)(value & 15));
659 }
660
661 static void _mkq_add_char_(struct _mkq_ *mkq, char value)
662 {
663         if (value <= ' ' || value >= 127)
664                 _mkq_add_esc_(mkq, value);
665         else
666                 switch(value) {
667                 case '=':
668                 case '&':
669                 case '%':
670                         _mkq_add_esc_(mkq, value);
671                         break;
672                 default:
673                         _mkq_add_(mkq, value);
674                 }
675 }
676
677 static void _mkq_append_(struct _mkq_ *mkq, const char *value)
678 {
679         while(*value)
680                 _mkq_add_char_(mkq, *value++);
681 }
682
683 static int _mkquery_(struct _mkq_ *mkq, enum MHD_ValueKind kind, const char *key, const char *value)
684 {
685         _mkq_add_(mkq, mkq->count++ ? '&' : '?');
686         _mkq_append_(mkq, key);
687         if (value != NULL) {
688                 _mkq_add_(mkq, '=');
689                 _mkq_append_(mkq, value);
690         }
691         return 1;
692 }
693
694 static char *url_with_query(struct afb_hreq *hreq, const char *url)
695 {
696         struct _mkq_ mkq;
697
698         mkq.count = 0;
699         mkq.length = strlen(url);
700         mkq.alloc = mkq.length + 1000;
701         mkq.text = malloc(mkq.alloc);
702         if (mkq.text != NULL) {
703                 strcpy(mkq.text, url);
704                 MHD_get_connection_values(hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_mkquery_, &mkq);
705                 _mkq_add_(&mkq, 0);
706         }
707         return mkq.text;
708 }
709
710 void afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url, int add_query_part)
711 {
712         const char *to;
713         char *wqp;
714
715         wqp = add_query_part ? url_with_query(hreq, url) : NULL;
716         to = wqp ? : url;
717         afb_hreq_reply_static(hreq, MHD_HTTP_MOVED_PERMANENTLY, 0, NULL,
718                         MHD_HTTP_HEADER_LOCATION, to, NULL);
719         DEBUG("redirect from [%s] to [%s]", hreq->url, url);
720         free(wqp);
721 }
722
723 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
724 {
725         return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
726 }
727
728 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
729 {
730         struct hreq_data *data = get_data(hreq, name, 0);
731         return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
732 }
733
734 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
735 {
736         return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
737 }
738
739 const char *afb_hreq_get_authorization_bearer(struct afb_hreq *hreq)
740 {
741         static const char bearer[] = "Bearer";
742         const char *value = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_AUTHORIZATION);
743         if (value) {
744                 if (strncasecmp(value, bearer, sizeof bearer - 1) == 0) {
745                         value += sizeof bearer - 1;
746                         if (isblank(*value++)) {
747                                 while (isblank(*value))
748                                         value++;
749                                 if (*value)
750                                         return value;
751                         }
752                 }
753         }
754         return NULL;
755 }
756
757 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
758 {
759         void *p;
760         struct hreq_data *hdat = get_data(hreq, key, 1);
761         if (hdat->path != NULL) {
762                 return 0;
763         }
764         p = realloc(hdat->value, hdat->length + size + 1);
765         if (p == NULL) {
766                 return 0;
767         }
768         hdat->value = p;
769         memcpy(&hdat->value[hdat->length], data, size);
770         hdat->length += size;
771         hdat->value[hdat->length] = 0;
772         return 1;
773 }
774
775 int afb_hreq_init_download_path(const char *directory)
776 {
777         struct stat st;
778         size_t n;
779         char *p;
780
781         if (access(directory, R_OK|W_OK)) {
782                 /* no read/write access */
783                 return -1;
784         }
785         if (stat(directory, &st)) {
786                 /* can't get info */
787                 return -1;
788         }
789         if (!S_ISDIR(st.st_mode)) {
790                 /* not a directory */
791                 errno = ENOTDIR;
792                 return -1;
793         }
794         n = strlen(directory);
795         while(n > 1 && directory[n-1] == '/') n--;
796         p = malloc(n + 8);
797         if (p == NULL) {
798                 /* can't allocate memory */
799                 errno = ENOMEM;
800                 return -1;
801         }
802         memcpy(p, directory, n);
803         p[n++] = '/';
804         p[n++] = 'X';
805         p[n++] = 'X';
806         p[n++] = 'X';
807         p[n++] = 'X';
808         p[n++] = 'X';
809         p[n++] = 'X';
810         p[n] = 0;
811         free(tmp_pattern);
812         tmp_pattern = p;
813         return 0;
814 }
815
816 static int opentempfile(char **path)
817 {
818         int fd;
819         char *fname;
820
821         fname = strdup(tmp_pattern ? : "XXXXXX"); /* TODO improve the path */
822         if (fname == NULL)
823                 return -1;
824
825         fd = mkostemp(fname, O_CLOEXEC|O_WRONLY);
826         if (fd < 0)
827                 free(fname);
828         else
829                 *path = fname;
830         return fd;
831 }
832
833 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
834 {
835         int fd;
836         ssize_t sz;
837         struct hreq_data *hdat = get_data(hreq, key, 1);
838
839         if (hdat->value == NULL) {
840                 hdat->value = strdup(file);
841                 if (hdat->value == NULL)
842                         return 0;
843                 fd = opentempfile(&hdat->path);
844         } else if (strcmp(hdat->value, file) || hdat->path == NULL) {
845                 return 0;
846         } else {
847                 fd = open(hdat->path, O_WRONLY|O_APPEND);
848         }
849         if (fd < 0)
850                 return 0;
851         while (size) {
852                 sz = write(fd, data, size);
853                 if (sz >= 0) {
854                         hdat->length += (size_t)sz;
855                         size -= (size_t)sz;
856                         data += sz;
857                 } else if (errno != EINTR)
858                         break;
859         }
860         close(fd);
861         return !size;
862 }
863
864 static struct afb_arg req_get(struct afb_xreq *xreq, const char *name)
865 {
866         const char *value;
867         struct afb_hreq *hreq = CONTAINER_OF_XREQ(struct afb_hreq, xreq);
868         struct hreq_data *hdat = get_data(hreq, name, 0);
869         if (hdat)
870                 return (struct afb_arg){
871                         .name = hdat->key,
872                         .value = hdat->value,
873                         .path = hdat->path
874                 };
875
876         value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
877         return (struct afb_arg){
878                 .name = value == NULL ? NULL : name,
879                 .value = value,
880                 .path = NULL
881         };
882 }
883
884 static int _iterargs_(struct json_object *obj, enum MHD_ValueKind kind, const char *key, const char *value)
885 {
886         json_object_object_add(obj, key, value ? json_object_new_string(value) : NULL);
887         return 1;
888 }
889
890 static struct json_object *req_json(struct afb_xreq *xreq)
891 {
892         struct hreq_data *hdat;
893         struct json_object *obj, *val;
894         struct afb_hreq *hreq = CONTAINER_OF_XREQ(struct afb_hreq, xreq);
895
896         obj = hreq->json;
897         if (obj == NULL) {
898                 hreq->json = obj = json_object_new_object();
899                 if (obj == NULL) {
900                 } else {
901                         MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, obj);
902                         for (hdat = hreq->data ; hdat ; hdat = hdat->next) {
903                                 if (hdat->path == NULL)
904                                         val = hdat->value ? json_object_new_string(hdat->value) : NULL;
905                                 else {
906                                         val = json_object_new_object();
907                                         if (val == NULL) {
908                                         } else {
909                                                 json_object_object_add(val, "file", json_object_new_string(hdat->value));
910                                                 json_object_object_add(val, "path", json_object_new_string(hdat->path));
911                                         }
912                                 }
913                                 json_object_object_add(obj, hdat->key, val);
914                         }
915                 }
916         }
917         return obj;
918 }
919
920 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
921 {
922         ssize_t len = stpncpy(buf, json_object_to_json_string_ext(obj, JSON_C_TO_STRING_PLAIN|JSON_C_TO_STRING_NOSLASHESCAPE)+pos, max) - buf;
923         return len ? : (ssize_t)MHD_CONTENT_READER_END_OF_STREAM;
924 }
925
926 static void req_reply(struct afb_xreq *xreq, struct json_object *object, const char *error, const char *info)
927 {
928         struct afb_hreq *hreq = CONTAINER_OF_XREQ(struct afb_hreq, xreq);
929         struct json_object *sub, *reply;
930         const char *reqid;
931         struct MHD_Response *response;
932
933         /* create the reply */
934         reply = afb_msg_json_reply(object, error, info, &xreq->context);
935
936         /* append the req id on need */
937         reqid = afb_hreq_get_argument(hreq, long_key_for_reqid);
938         if (reqid == NULL)
939                 reqid = afb_hreq_get_argument(hreq, short_key_for_reqid);
940         if (reqid != NULL && json_object_object_get_ex(reply, "request", &sub))
941                 json_object_object_add(sub, "reqid", json_object_new_string(reqid));
942
943         response = MHD_create_response_from_callback((uint64_t)strlen(json_object_to_json_string_ext(reply, JSON_C_TO_STRING_PLAIN|JSON_C_TO_STRING_NOSLASHESCAPE)), SIZE_RESPONSE_BUFFER, (void*)send_json_cb, reply, (void*)json_object_put);
944         afb_hreq_reply(hreq, MHD_HTTP_OK, response, NULL);
945 }
946
947 void afb_hreq_call(struct afb_hreq *hreq, struct afb_apiset *apiset, const char *api, size_t lenapi, const char *verb, size_t lenverb)
948 {
949         hreq->xreq.request.called_api = strndup(api, lenapi);
950         hreq->xreq.request.called_verb = strndup(verb, lenverb);
951         if (hreq->xreq.request.called_api == NULL || hreq->xreq.request.called_verb == NULL) {
952                 ERROR("Out of memory");
953                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
954         } else if (afb_hreq_init_context(hreq) < 0) {
955                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
956         } else {
957                 afb_xreq_unhooked_addref(&hreq->xreq);
958                 afb_xreq_process(&hreq->xreq, apiset);
959         }
960 }
961
962 int afb_hreq_init_context(struct afb_hreq *hreq)
963 {
964         const char *uuid;
965         const char *token;
966
967         if (hreq->xreq.context.session != NULL)
968                 return 0;
969
970         /* get the uuid of the session */
971         uuid = afb_hreq_get_header(hreq, long_key_for_uuid);
972         if (uuid == NULL) {
973                 uuid = afb_hreq_get_argument(hreq, long_key_for_uuid);
974                 if (uuid == NULL) {
975                         uuid = afb_hreq_get_cookie(hreq, cookie_name);
976                         if (uuid == NULL)
977                                 uuid = afb_hreq_get_argument(hreq, short_key_for_uuid);
978                 }
979         }
980
981         /* get the authorisation token */
982         token = afb_hreq_get_authorization_bearer(hreq);
983         if (token == NULL) {
984                 token = afb_hreq_get_header(hreq, long_key_for_token);
985                 if (token == NULL) {
986                         token = afb_hreq_get_argument(hreq, long_key_for_token);
987                         if (token == NULL)
988                                 token = afb_hreq_get_argument(hreq, short_key_for_token);
989                 }
990         }
991
992         return afb_context_connect(&hreq->xreq.context, uuid, token);
993 }
994
995 int afb_hreq_init_cookie(int port, const char *path, int maxage)
996 {
997         int rc;
998
999         free(cookie_name);
1000         free(cookie_setter);
1001         cookie_name = NULL;
1002         cookie_setter = NULL;
1003
1004         path = path ? : "/";
1005         rc = asprintf(&cookie_name, "%s-%d", long_key_for_uuid, port);
1006         if (rc < 0)
1007                 return 0;
1008         rc = asprintf(&cookie_setter, "%s=%%s; Path=%s; Max-Age=%d; HttpOnly",
1009                         cookie_name, path, maxage);
1010         if (rc < 0)
1011                 return 0;
1012         return 1;
1013 }
1014
1015 struct afb_xreq *afb_hreq_to_xreq(struct afb_hreq *hreq)
1016 {
1017         return &hreq->xreq;
1018 }
1019
1020 struct afb_hreq *afb_hreq_create()
1021 {
1022         struct afb_hreq *hreq = calloc(1, sizeof *hreq);
1023         if (hreq) {
1024                 /* init the request */
1025                 afb_xreq_init(&hreq->xreq, &afb_hreq_xreq_query_itf);
1026                 hreq->reqid = ++global_reqids;
1027         }
1028         return hreq;
1029 }
1030