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