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