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