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