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