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