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