- AFB_clientCtx *clientCtx=NULL;
- const char *uuid;
- uuid_t newuuid;
-
- if (request->config->token == NULL) return NULL;
-
- // Check if client as a context or not inside the URL
- uuid = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_uuid);
-
- // if UUID in query we're restfull with no cookies otherwise check for cookie
- if (uuid != NULL)
- request->restfull = TRUE;
- else {
- char cookie[64];
- request->restfull = FALSE;
- snprintf(cookie, sizeof cookie, "%s-%d", COOKIE_NAME, request->config->httpdPort);
- uuid = MHD_lookup_connection_value (request->connection, MHD_COOKIE_KIND, cookie);
- };
-
- // Warning when no cookie defined MHD_lookup_connection_value may return something !!!
- if ((uuid != NULL) && (strnlen (uuid, 10) >= 10)) {
- // search if client context exist and it not timeout let's use it
- clientCtx = ctxStoreSearch (uuid);
-
- if (clientCtx) {
- if (ctxStoreTooOld (clientCtx, request->config->cntxTimeout)) {
- // this session is too old let's delete it
- ctxStoreDel (clientCtx);
- clientCtx = NULL;
- } else {
- request->context = clientCtx->contexts[apiidx];
- request->uuid = uuid;
- return clientCtx;
- }
- }
- }
-
- // we have no session let's create one otherwise let's clean any exiting values
- if (clientCtx == NULL) {
- clientCtx = calloc(1, sizeof(AFB_clientCtx)); // init NULL clientContext
- clientCtx->contexts = calloc ((unsigned)afb_apis_count(), sizeof (void*));
- }
-
- uuid_generate(newuuid); // create a new UUID
- uuid_unparse_lower(newuuid, clientCtx->uuid);
+ struct AFB_clientCtx *clientCtx;
+ time_t now;
+
+ /* cleaning */
+ now = NOW;
+ ctxStoreCleanUp (now);
+
+ /* search for an existing one not too old */
+ if (uuid != NULL) {
+ if (strlen(uuid) >= sizeof clientCtx->uuid) {
+ errno = EINVAL;
+ goto error;
+ }
+ clientCtx = ctxStoreSearch(uuid);
+ if (clientCtx != NULL) {
+ *created = 0;
+ goto found;
+ }
+ }
+
+ /* returns a new one */
+ clientCtx = calloc(1, sizeof(struct AFB_clientCtx) + ((unsigned)sessions.apicount * sizeof(*clientCtx->values)));
+ if (clientCtx == NULL) {
+ errno = ENOMEM;
+ goto error;
+ }
+ clientCtx->values = (void*)(clientCtx + 1);
+
+ /* generate the uuid */
+ if (uuid == NULL) {
+ new_uuid(clientCtx->uuid);
+ } else {
+ strcpy(clientCtx->uuid, uuid);
+ }
+
+ /* init the token */
+ strcpy(clientCtx->token, sessions.initok);
+ clientCtx->expiration = now + sessions.timeout;
+ if (!ctxStoreAdd (clientCtx)) {
+ errno = ENOMEM;
+ goto error2;
+ }
+ *created = 1;
+
+found:
+ clientCtx->access = now;
+ clientCtx->refcount++;
+ return clientCtx;
+
+error2:
+ free(clientCtx);
+error:
+ return NULL;
+}