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