try to avoid unnecessary copy
[src/app-framework-binder.git] / src / afb-hreq.c
1 /*
2  * Copyright 2016 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.h>
30
31 #if defined(USE_MAGIC_MIME_TYPE)
32 #include <magic.h>
33 #endif
34
35 #include "afb-method.h"
36 #include "afb-req-itf.h"
37 #include "afb-msg-json.h"
38 #include "afb-hreq.h"
39 #include "session.h"
40 #include "verbose.h"
41
42 #define SIZE_RESPONSE_BUFFER   8192
43
44 static char empty_string[] = "";
45
46 static const char uuid_header[] = "x-afb-uuid";
47 static const char uuid_arg[] = "uuid";
48 static const char uuid_cookie[] = "uuid";
49
50 static const char token_header[] = "x-afb-token";
51 static const char token_arg[] = "token";
52 static const char token_cookie[] = "token";
53
54 static char *cookie_name = NULL;
55 static char *cookie_setter = NULL;
56 static char *tmp_pattern = NULL;
57
58 struct hreq_data {
59         struct hreq_data *next;
60         char *key;
61         size_t length;
62         char *value;
63         char *path;
64 };
65
66 static struct json_object *req_json(struct afb_hreq *hreq);
67 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name);
68 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info);
69 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info);
70 static const char *req_raw(struct afb_hreq *hreq, size_t *size);
71 static void req_send(struct afb_hreq *hreq, const char *buffer, size_t size);
72 static int req_session_create(struct afb_hreq *hreq);
73 static int req_session_check(struct afb_hreq *hreq, int refresh);
74 static void req_session_close(struct afb_hreq *hreq);
75
76 static const struct afb_req_itf afb_hreq_itf = {
77         .json = (void*)req_json,
78         .get = (void*)req_get,
79         .success = (void*)req_success,
80         .fail = (void*)req_fail,
81         .raw = (void*)req_raw,
82         .send = (void*)req_send,
83         .session_create = (void*)req_session_create,
84         .session_check = (void*)req_session_check,
85         .session_close = (void*)req_session_close,
86         .context_get = (void*)afb_context_get,
87         .context_set = (void*)afb_context_set
88 };
89
90 static struct hreq_data *get_data(struct afb_hreq *hreq, const char *key, int create)
91 {
92         struct hreq_data *data = hreq->data;
93         while (data != NULL) {
94                 if (!strcasecmp(data->key, key))
95                         return data;
96                 data = data->next;
97         }
98         if (create) {
99                 data = calloc(1, sizeof *data);
100                 if (data != NULL) {
101                         data->key = strdup(key);
102                         if (data->key == NULL) {
103                                 free(data);
104                                 data = NULL;
105                         } else {
106                                 data->next = hreq->data;
107                                 hreq->data = data;
108                         }
109                 }
110         }
111         return data;
112 }
113
114 /* a valid subpath is a relative path not looking deeper than root using .. */
115 static int validsubpath(const char *subpath)
116 {
117         int l = 0, i = 0;
118
119         while (subpath[i]) {
120                 switch (subpath[i++]) {
121                 case '.':
122                         if (!subpath[i])
123                                 break;
124                         if (subpath[i] == '/') {
125                                 i++;
126                                 break;
127                         }
128                         if (subpath[i++] == '.') {
129                                 if (!subpath[i]) {
130                                         if (--l < 0)
131                                                 return 0;
132                                         break;
133                                 }
134                                 if (subpath[i++] == '/') {
135                                         if (--l < 0)
136                                                 return 0;
137                                         break;
138                                 }
139                         }
140                 default:
141                         while (subpath[i] && subpath[i] != '/')
142                                 i++;
143                         l++;
144                 case '/':
145                         break;
146                 }
147         }
148         return 1;
149 }
150
151 static void afb_hreq_reply_v(struct afb_hreq *hreq, unsigned status, struct MHD_Response *response, va_list args)
152 {
153         char *cookie;
154         const char *k, *v;
155
156         if (hreq->replied != 0)
157                 return;
158
159         k = va_arg(args, const char *);
160         while (k != NULL) {
161                 v = va_arg(args, const char *);
162                 MHD_add_response_header(response, k, v);
163                 k = va_arg(args, const char *);
164         }
165         if (hreq->context != NULL && asprintf(&cookie, cookie_setter, hreq->context->uuid)) {
166                 MHD_add_response_header(response, MHD_HTTP_HEADER_SET_COOKIE, cookie);
167                 free(cookie);
168         }
169         MHD_queue_response(hreq->connection, status, response);
170         MHD_destroy_response(response);
171
172         hreq->replied = 1;
173         if (hreq->suspended != 0) {
174                 extern void run_micro_httpd(struct afb_hsrv *hsrv);
175                 MHD_resume_connection (hreq->connection);
176                 hreq->suspended = 0;
177                 run_micro_httpd(hreq->hsrv);
178         }
179 }
180
181 void afb_hreq_reply(struct afb_hreq *hreq, unsigned status, struct MHD_Response *response, ...)
182 {
183         va_list args;
184         va_start(args, response);
185         afb_hreq_reply_v(hreq, status, response, args);
186         va_end(args);
187 }
188
189 void afb_hreq_reply_empty(struct afb_hreq *hreq, unsigned status, ...)
190 {
191         va_list args;
192         va_start(args, status);
193         afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT), args);
194         va_end(args);
195 }
196
197 void afb_hreq_reply_static(struct afb_hreq *hreq, unsigned status, size_t size, const char *buffer, ...)
198 {
199         va_list args;
200         va_start(args, buffer);
201         afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, (char*)buffer, MHD_RESPMEM_PERSISTENT), args);
202         va_end(args);
203 }
204
205 void afb_hreq_reply_copy(struct afb_hreq *hreq, unsigned status, size_t size, const char *buffer, ...)
206 {
207         va_list args;
208         va_start(args, buffer);
209         afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, (char*)buffer, MHD_RESPMEM_MUST_COPY), args);
210         va_end(args);
211 }
212
213 void afb_hreq_reply_free(struct afb_hreq *hreq, unsigned status, size_t size, char *buffer, ...)
214 {
215         va_list args;
216         va_start(args, buffer);
217         afb_hreq_reply_v(hreq, status, MHD_create_response_from_buffer((unsigned)size, buffer, MHD_RESPMEM_MUST_FREE), args);
218         va_end(args);
219 }
220
221 #if defined(USE_MAGIC_MIME_TYPE)
222
223 #if !defined(MAGIC_DB)
224 #define MAGIC_DB "/usr/share/misc/magic.mgc"
225 #endif
226
227 static magic_t lazy_libmagic()
228 {
229         static int done = 0;
230         static magic_t result = NULL;
231
232         if (!done) {
233                 done = 1;
234                 /* MAGIC_MIME tells magic to return a mime of the file,
235                          but you can specify different things */
236                 if (verbosity)
237                         fprintf(stderr, "Loading mimetype default magic database\n");
238
239                 result = magic_open(MAGIC_MIME_TYPE);
240                 if (result == NULL) {
241                         fprintf(stderr,"ERROR: unable to initialize magic library\n");
242                 }
243                 /* Warning: should not use NULL for DB
244                                 [libmagic bug wont pass efence check] */
245                 else if (magic_load(result, MAGIC_DB) != 0) {
246                         fprintf(stderr,"cannot load magic database - %s\n",
247                                         magic_error(result));
248                         magic_close(result);
249                         result = NULL;
250                 }
251         }
252
253         return result;
254 }
255
256 static const char *magic_mimetype_fd(int fd)
257 {
258         magic_t lib = lazy_libmagic();
259         return lib ? magic_descriptor(lib, fd) : NULL;
260 }
261
262 #endif
263
264 static const char *mimetype_fd_name(int fd, const char *filename)
265 {
266         const char *result = NULL;
267
268 #if defined(INFER_EXTENSION)
269         const char *extension = strrchr(filename, '.');
270         if (extension) {
271                 static const char *const known[][2] = {
272                         { ".js",   "text/javascript" },
273                         { ".html", "text/html" },
274                         { ".css",  "text/css" },
275                         { NULL, NULL }
276                 };
277                 int i = 0;
278                 while (known[i][0]) {
279                         if (!strcasecmp(extension, known[i][0])) {
280                                 result = known[i][1];
281                                 break;
282                         }
283                         i++;
284                 }
285         }
286 #endif
287 #if defined(USE_MAGIC_MIME_TYPE)
288         if (result == NULL)
289                 result = magic_mimetype_fd(fd);
290 #endif
291         return result;
292 }
293
294 void afb_hreq_free(struct afb_hreq *hreq)
295 {
296         struct hreq_data *data;
297         if (hreq != NULL) {
298                 if (hreq->postform != NULL)
299                         MHD_destroy_post_processor(hreq->postform);
300                 for (data = hreq->data; data; data = hreq->data) {
301                         hreq->data = data->next;
302                         if (data->path) {
303                                 unlink(data->path);
304                                 free(data->path);
305                         }
306                         free(data->key);
307                         free(data->value);
308                         free(data);
309                 }
310                 ctxClientPut(hreq->context);
311                 json_object_put(hreq->json);
312                 free(hreq);
313         }
314 }
315
316 /*
317  * Removes the 'prefix' of 'length' from the tail of 'hreq'
318  * if and only if the prefix exists and is terminated by a leading
319  * slash
320  */
321 int afb_hreq_unprefix(struct afb_hreq *hreq, const char *prefix, size_t length)
322 {
323         /* check the prefix ? */
324         if (length > hreq->lentail || (hreq->tail[length] && hreq->tail[length] != '/')
325             || strncasecmp(prefix, hreq->tail, length))
326                 return 0;
327
328         /* removes successives / */
329         while (length < hreq->lentail && hreq->tail[length + 1] == '/')
330                 length++;
331
332         /* update the tail */
333         hreq->lentail -= length;
334         hreq->tail += length;
335         return 1;
336 }
337
338 int afb_hreq_valid_tail(struct afb_hreq *hreq)
339 {
340         return validsubpath(hreq->tail);
341 }
342
343 void afb_hreq_reply_error(struct afb_hreq *hreq, unsigned int status)
344 {
345         afb_hreq_reply_empty(hreq, status, NULL);
346 }
347
348 int afb_hreq_reply_file_if_exist(struct afb_hreq *hreq, int dirfd, const char *filename)
349 {
350         int rc;
351         int fd;
352         unsigned int status;
353         struct stat st;
354         char etag[1 + 2 * sizeof(int)];
355         const char *inm;
356         struct MHD_Response *response;
357         const char *mimetype;
358
359         /* Opens the file or directory */
360         if (filename[0]) {
361                 fd = openat(dirfd, filename, O_RDONLY);
362                 if (fd < 0) {
363                         if (errno == ENOENT)
364                                 return 0;
365                         afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
366                         return 1;
367                 }
368         } else {
369                 fd = dup(dirfd);
370                 if (fd < 0) {
371                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
372                         return 1;
373                 }
374         }
375
376         /* Retrieves file's status */
377         if (fstat(fd, &st) != 0) {
378                 close(fd);
379                 afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
380                 return 1;
381         }
382
383         /* serve directory */
384         if (S_ISDIR(st.st_mode)) {
385                 static const char *indexes[] = { "index.html", NULL };
386                 int i = 0;
387                 rc = 0;
388                 while (indexes[i] != NULL) {
389                         if (faccessat(fd, indexes[i], R_OK, 0) == 0) {
390                                 if (hreq->url[hreq->lenurl - 1] != '/') {
391                                         /* the redirect is needed for reliability of relative path */
392                                         char *tourl = alloca(hreq->lenurl + 2);
393                                         memcpy(tourl, hreq->url, hreq->lenurl);
394                                         tourl[hreq->lenurl] = '/';
395                                         tourl[hreq->lenurl + 1] = 0;
396                                         rc = afb_hreq_redirect_to(hreq, tourl);
397                                 } else {
398                                         rc = afb_hreq_reply_file_if_exist(hreq, fd, indexes[i]);
399                                 }
400                                 break;
401                         }
402                         i++;
403                 }
404                 close(fd);
405                 return rc;
406         }
407
408         /* Don't serve special files */
409         if (!S_ISREG(st.st_mode)) {
410                 close(fd);
411                 afb_hreq_reply_error(hreq, MHD_HTTP_FORBIDDEN);
412                 return 1;
413         }
414
415         /* Check the method */
416         if ((hreq->method & (afb_method_get | afb_method_head)) == 0) {
417                 close(fd);
418                 afb_hreq_reply_error(hreq, MHD_HTTP_METHOD_NOT_ALLOWED);
419                 return 1;
420         }
421
422         /* computes the etag */
423         sprintf(etag, "%08X%08X", ((int)(st.st_mtim.tv_sec) ^ (int)(st.st_mtim.tv_nsec)), (int)(st.st_size));
424
425         /* checks the etag */
426         inm = MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
427         if (inm && 0 == strcmp(inm, etag)) {
428                 /* etag ok, return NOT MODIFIED */
429                 close(fd);
430                 if (verbosity)
431                         fprintf(stderr, "Not Modified: [%s]\n", filename);
432                 response = MHD_create_response_from_buffer(0, empty_string, MHD_RESPMEM_PERSISTENT);
433                 status = MHD_HTTP_NOT_MODIFIED;
434         } else {
435                 /* check the size */
436                 if (st.st_size != (off_t) (size_t) st.st_size) {
437                         close(fd);
438                         afb_hreq_reply_error(hreq, MHD_HTTP_INTERNAL_SERVER_ERROR);
439                         return 1;
440                 }
441
442                 /* create the response */
443                 response = MHD_create_response_from_fd((size_t) st.st_size, fd);
444                 status = MHD_HTTP_OK;
445
446                 /* set the type */
447                 mimetype = mimetype_fd_name(fd, filename);
448                 if (mimetype != NULL)
449                         MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
450         }
451
452         /* fills the value and send */
453         afb_hreq_reply(hreq, status, response,
454                         MHD_HTTP_HEADER_CACHE_CONTROL, hreq->cacheTimeout,
455                         MHD_HTTP_HEADER_ETAG, etag,
456                         NULL);
457         return 1;
458 }
459
460 int afb_hreq_reply_file(struct afb_hreq *hreq, int dirfd, const char *filename)
461 {
462         int rc = afb_hreq_reply_file_if_exist(hreq, dirfd, filename);
463         if (rc == 0)
464                 afb_hreq_reply_error(hreq, MHD_HTTP_NOT_FOUND);
465         return 1;
466 }
467
468 int afb_hreq_redirect_to(struct afb_hreq *hreq, const char *url)
469 {
470         afb_hreq_reply_static(hreq, MHD_HTTP_MOVED_PERMANENTLY, 0, NULL,
471                         MHD_HTTP_HEADER_LOCATION, url, NULL);
472         if (verbosity)
473                 fprintf(stderr, "redirect from [%s] to [%s]\n", hreq->url, url);
474         return 1;
475 }
476
477 const char *afb_hreq_get_cookie(struct afb_hreq *hreq, const char *name)
478 {
479         return MHD_lookup_connection_value(hreq->connection, MHD_COOKIE_KIND, name);
480 }
481
482 const char *afb_hreq_get_argument(struct afb_hreq *hreq, const char *name)
483 {
484         struct hreq_data *data = get_data(hreq, name, 0);
485         return data ? data->value : MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name);
486 }
487
488 const char *afb_hreq_get_header(struct afb_hreq *hreq, const char *name)
489 {
490         return MHD_lookup_connection_value(hreq->connection, MHD_HEADER_KIND, name);
491 }
492
493 int afb_hreq_post_add(struct afb_hreq *hreq, const char *key, const char *data, size_t size)
494 {
495         void *p;
496         struct hreq_data *hdat = get_data(hreq, key, 1);
497         if (hdat->path != NULL) {
498                 return 0;
499         }
500         p = realloc(hdat->value, hdat->length + size + 1);
501         if (p == NULL) {
502                 return 0;
503         }
504         hdat->value = p;
505         memcpy(&hdat->value[hdat->length], data, size);
506         hdat->length += size;
507         hdat->value[hdat->length] = 0;
508         return 1;
509 }
510
511 int afb_hreq_init_download_path(const char *directory)
512 {
513         struct stat st;
514         size_t n;
515         char *p;
516
517         if (access(directory, R_OK|W_OK)) {
518                 /* no read/write access */
519                 return -1;
520         }
521         if (stat(directory, &st)) {
522                 /* can't get info */
523                 return -1;
524         }
525         if (!S_ISDIR(st.st_mode)) {
526                 /* not a directory */
527                 errno = ENOTDIR;
528                 return -1;
529         }
530         n = strlen(directory);
531         while(n > 1 && directory[n-1] == '/') n--;
532         p = malloc(n + 8);
533         if (p == NULL) {
534                 /* can't allocate memory */
535                 errno = ENOMEM;
536                 return -1;
537         }
538         memcpy(p, directory, n);
539         p[n++] = '/';
540         p[n++] = 'X';
541         p[n++] = 'X';
542         p[n++] = 'X';
543         p[n++] = 'X';
544         p[n++] = 'X';
545         p[n++] = 'X';
546         p[n] = 0;
547         free(tmp_pattern);
548         tmp_pattern = p;
549         return 0;
550 }
551
552 static int opentempfile(char **path)
553 {
554         int fd;
555         char *fname;
556
557         fname = strdup(tmp_pattern ? : "XXXXXX"); /* TODO improve the path */
558         if (fname == NULL)
559                 return -1;
560
561         fd = mkostemp(fname, O_CLOEXEC|O_WRONLY);
562         if (fd < 0)
563                 free(fname);
564         else
565                 *path = fname;
566         return fd;
567 }
568
569 int afb_hreq_post_add_file(struct afb_hreq *hreq, const char *key, const char *file, const char *data, size_t size)
570 {
571         int fd;
572         ssize_t sz;
573         struct hreq_data *hdat = get_data(hreq, key, 1);
574
575         if (hdat->value == NULL) {
576                 hdat->value = strdup(file);
577                 if (hdat->value == NULL)
578                         return 0;
579                 fd = opentempfile(&hdat->path);
580         } else if (strcmp(hdat->value, file) || hdat->path == NULL) {
581                 return 0;
582         } else {
583                 fd = open(hdat->path, O_WRONLY|O_APPEND);
584         }
585         if (fd < 0)
586                 return 0;
587         while (size) {
588                 sz = write(fd, data, size);
589                 if (sz >= 0) {
590                         hdat->length += (size_t)sz;
591                         size -= (size_t)sz;
592                         data += sz;
593                 } else if (errno != EINTR)
594                         break;
595         }
596         close(fd);
597         return !size;
598 }
599
600 struct afb_req afb_hreq_to_req(struct afb_hreq *hreq)
601 {
602         return (struct afb_req){ .itf = &afb_hreq_itf, .req_closure = hreq };
603 }
604
605 static struct afb_arg req_get(struct afb_hreq *hreq, const char *name)
606 {
607         struct hreq_data *hdat = get_data(hreq, name, 0);
608         if (hdat)
609                 return (struct afb_arg){
610                         .name = hdat->key,
611                         .value = hdat->value,
612                         .path = hdat->path
613                 };
614                 
615         return (struct afb_arg){
616                 .name = name,
617                 .value = MHD_lookup_connection_value(hreq->connection, MHD_GET_ARGUMENT_KIND, name),
618                 .path = NULL
619         };
620 }
621
622 static int _iterargs_(struct json_object *obj, enum MHD_ValueKind kind, const char *key, const char *value)
623 {
624         json_object_object_add(obj, key, value ? json_object_new_string(value) : NULL);
625         return 1;
626 }
627
628 static struct json_object *req_json(struct afb_hreq *hreq)
629 {
630         struct hreq_data *hdat;
631         struct json_object *obj, *val;
632
633         obj = hreq->json;
634         if (obj == NULL) {
635                 hreq->json = obj = json_object_new_object();
636                 if (obj == NULL) {
637                 } else {
638                         MHD_get_connection_values (hreq->connection, MHD_GET_ARGUMENT_KIND, (void*)_iterargs_, obj);
639                         for (hdat = hreq->data ; hdat ; hdat = hdat->next) {
640                                 if (hdat->path == NULL)
641                                         val = hdat->value ? json_object_new_string(hdat->value) : NULL;
642                                 else {
643                                         val = json_object_new_object();
644                                         if (val == NULL) {
645                                         } else {
646                                                 json_object_object_add(val, "file", json_object_new_string(hdat->value));
647                                                 json_object_object_add(val, "path", json_object_new_string(hdat->path));
648                                         }
649                                 }
650                                 json_object_object_add(obj, hdat->key, val);
651                         }
652                 }
653         }
654         return obj;
655 }
656
657 static const char *req_raw(struct afb_hreq *hreq, size_t *size)
658 {
659         const char *result = json_object_get_string(req_json(hreq));
660         *size = result ? strlen(result) : 0;
661         return result;
662 }
663
664 static void req_send(struct afb_hreq *hreq, const char *buffer, size_t size)
665 {
666         afb_hreq_reply_free(hreq, MHD_HTTP_OK, size, buffer, NULL);
667 }
668
669 static ssize_t send_json_cb(json_object *obj, uint64_t pos, char *buf, size_t max)
670 {
671         ssize_t len = stpncpy(buf, json_object_to_json_string(obj)+pos, max) - buf;
672         return len ? : (ssize_t)MHD_CONTENT_READER_END_OF_STREAM;
673 }
674
675 static void req_reply(struct afb_hreq *hreq, unsigned retcode, const char *status, const char *info, json_object *resp)
676 {
677         struct json_object *reply;
678         const char *token, *uuid;
679         struct MHD_Response *response;
680
681         if (hreq->context == NULL) {
682                 token = uuid = NULL;
683         } else {
684                 token = hreq->context->token;
685                 uuid = hreq->context->uuid;
686         }
687         reply = afb_msg_json_reply(status, info, resp, token, uuid);
688         response = MHD_create_response_from_callback((uint64_t)strlen(json_object_to_json_string(reply)), SIZE_RESPONSE_BUFFER, (void*)send_json_cb, reply, (void*)json_object_put);
689         afb_hreq_reply(hreq, retcode, response, NULL);
690 }
691
692 static void req_fail(struct afb_hreq *hreq, const char *status, const char *info)
693 {
694         req_reply(hreq, MHD_HTTP_OK, status, info, NULL);
695 }
696
697 static void req_success(struct afb_hreq *hreq, json_object *obj, const char *info)
698 {
699         req_reply(hreq, MHD_HTTP_OK, "success", info, obj);
700 }
701
702 struct AFB_clientCtx *afb_hreq_context(struct afb_hreq *hreq)
703 {
704         const char *uuid;
705
706         if (hreq->context == NULL) {
707                 uuid = afb_hreq_get_header(hreq, uuid_header);
708                 if (uuid == NULL)
709                         uuid = afb_hreq_get_argument(hreq, uuid_arg);
710                 if (uuid == NULL)
711                         uuid = afb_hreq_get_cookie(hreq, cookie_name);
712                 hreq->context = ctxClientGetForUuid(uuid);
713         }
714         return hreq->context;
715 }
716
717 static int req_session_create(struct afb_hreq *hreq)
718 {
719         struct AFB_clientCtx *context = afb_hreq_context(hreq);
720         if (context == NULL)
721                 return 0;
722         if (context->created)
723                 return 0;
724         return req_session_check(hreq, 1);
725 }
726
727 static int req_session_check(struct afb_hreq *hreq, int refresh)
728 {
729         const char *token;
730
731         struct AFB_clientCtx *context = afb_hreq_context(hreq);
732
733         if (context == NULL)
734                 return 0;
735
736         token = afb_hreq_get_header(hreq, token_header);
737         if (token == NULL)
738                 token = afb_hreq_get_argument(hreq, token_arg);
739         if (token == NULL)
740                 token = afb_hreq_get_cookie(hreq, token_cookie);
741         if (token == NULL)
742                 return 0;
743
744         if (!ctxTokenCheck (context, token))
745                 return 0;
746
747         if (refresh) {
748                 ctxTokenNew (context);
749         }
750
751         return 1;
752 }
753
754 static void req_session_close(struct afb_hreq *hreq)
755 {
756         struct AFB_clientCtx *context = afb_hreq_context(hreq);
757         if (context != NULL)
758                 ctxClientClose(context);
759 }
760
761 int afb_hreq_init_cookie(int port, const char *path, int maxage)
762 {
763         int rc;
764
765         free(cookie_name);
766         free(cookie_setter);
767         cookie_name = NULL;
768         cookie_setter = NULL;
769
770         path = path ? : "/";
771         rc = asprintf(&cookie_name, "x-afb-uuid-%d", port);
772         if (rc < 0)
773                 return 0;
774         rc = asprintf(&cookie_setter, "%s=%%s; Path=%s; Max-Age=%d; HttpOnly",
775                         cookie_name, path, maxage);
776         if (rc < 0)
777                 return 0;
778         return 1;
779 }
780
781