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