Removes uses of readdir_r
[src/app-framework-binder.git] / src / session.c
index 9569b46..7e1e4c6 100644 (file)
 /*
- * Copyright (C) 2015 "IoT.bzh"
+ * Copyright (C) 2015, 2016, 2017 "IoT.bzh"
  * Author "Fulup Ar Foll"
  *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
- * Reference:
- * http://stackoverflow.com/questions/25971505/how-to-delete-element-from-hsearch
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
 
-
-#include "local-def.h"
-#include <dirent.h>
-#include <string.h>
+#define _GNU_SOURCE
+#include <stdio.h>
 #include <time.h>
-#include <sys/stat.h>
-#include <sys/types.h>
 #include <pthread.h>
-#include <search.h>
+#include <stdlib.h>
+#include <string.h>
+#include <uuid/uuid.h>
+#include <assert.h>
+#include <errno.h>
 
-#include "afb-apis.h"
+#include <json-c/json.h>
+
+#include "session.h"
+#include "verbose.h"
+
+#define NOW (time(NULL))
+
+struct client_value
+{
+       void *value;
+       void (*free_value)(void*);
+};
+
+struct cookie
+{
+       struct cookie *next;
+       const void *key;
+       void *value;
+       void (*free_value)(void*);
+};
+
+struct AFB_clientCtx
+{
+       unsigned refcount;
+       unsigned loa;
+       int timeout;
+       time_t expiration;    // expiration time of the token
+       time_t access;
+       char uuid[37];        // long term authentication of remote client
+       char token[37];       // short term authentication of remote client
+       struct client_value *values;
+       struct cookie *cookies;
+};
 
 // Session UUID are store in a simple array [for 10 sessions this should be enough]
 static struct {
   pthread_mutex_t mutex;          // declare a mutex to protect hash table
-  AFB_clientCtx **store;          // sessions store
+  struct AFB_clientCtx **store;          // sessions store
   int count;                      // current number of sessions
   int max;
+  int timeout;
+  int apicount;
+  char initok[37];
 } sessions;
 
-static const char key_uuid[] = "uuid";
-static const char key_token[] = "token";
+/* generate a uuid */
+static void new_uuid(char uuid[37])
+{
+       uuid_t newuuid;
+       uuid_generate(newuuid);
+       uuid_unparse_lower(newuuid, uuid);
+}
 
 // Free context [XXXX Should be protected again memory abort XXXX]
-static void ctxUuidFreeCB (AFB_clientCtx *client)
+static void ctxUuidFreeCB (struct AFB_clientCtx *client)
 {
-    int idx, cnt;
-
-    // If application add a handle let's free it now
-    if (client->contexts != NULL) {
-
-       cnt = afb_apis_count();
-        // Free client handle with a standard Free function, with app callback or ignore it
-        for (idx=0; idx < cnt; idx ++) {
-            if (client->contexts[idx] != NULL) {
-               afb_apis_free_context(idx, client->contexts[idx]);
-            }
-        }
-    }
+       int idx;
+       struct cookie *cookie;
+
+       // If application add a handle let's free it now
+       assert (client->values != NULL);
+
+       // Free client handle with a standard Free function, with app callback or ignore it
+       for (idx=0; idx < sessions.apicount; idx ++)
+               ctxClientValueSet(client, idx, NULL, NULL);
+
+       // free cookies
+       cookie = client->cookies;
+       while (cookie != NULL) {
+               client->cookies = cookie->next;
+               if (cookie->value != NULL && cookie->free_value != NULL)
+                       cookie->free_value(cookie->value);
+               free(cookie);
+               cookie = client->cookies;
+       }
 }
 
 // Create a new store in RAM, not that is too small it will be automatically extended
-void ctxStoreInit (int nbSession)
+void ctxStoreInit (int max_session_count, int timeout, const char *initok, int context_count)
 {
-
-   // let's create as store as hashtable does not have any
-   sessions.store = calloc (1 + (unsigned)nbSession, sizeof(AFB_clientCtx));
-   sessions.max = nbSession;
+       // let's create as store as hashtable does not have any
+       sessions.store = calloc (1 + (unsigned)max_session_count, sizeof(struct AFB_clientCtx));
+       sessions.max = max_session_count;
+       sessions.timeout = timeout;
+       sessions.apicount = context_count;
+       if (initok == NULL)
+               /* without token, a secret is made to forbid creation of sessions */
+               new_uuid(sessions.initok);
+       else if (strlen(initok) < sizeof(sessions.store[0]->token))
+               strcpy(sessions.initok, initok);
+       else {
+               ERROR("initial token '%s' too long (max length 36)", initok);
+               exit(1);
+       }
 }
 
-static AFB_clientCtx *ctxStoreSearch (const char* uuid)
+static struct AFB_clientCtx *ctxStoreSearch (const char* uuid)
 {
     int  idx;
-    AFB_clientCtx *client;
+    struct AFB_clientCtx *client;
 
-    if (uuid == NULL)
-       return NULL;
+    assert (uuid != NULL);
 
     pthread_mutex_lock(&sessions.mutex);
 
     for (idx=0; idx < sessions.max; idx++) {
-        if (sessions.store[idx] && (0 == strcmp (uuid, sessions.store[idx]->uuid))) break;
+       client = sessions.store[idx];
+        if (client && (0 == strcmp (uuid, client->uuid)))
+               goto found;
     }
+    client = NULL;
 
-    if (idx == sessions.max) client=NULL;
-    else client= sessions.store[idx];
+found:
     pthread_mutex_unlock(&sessions.mutex);
-
     return client;
 }
 
-static AFB_error ctxStoreDel (AFB_clientCtx *client)
+static int ctxStoreDel (struct AFB_clientCtx *client)
 {
     int idx;
     int status;
 
-    if (client == NULL)
-       return AFB_FAIL;
+    assert (client != NULL);
 
     pthread_mutex_lock(&sessions.mutex);
 
     for (idx=0; idx < sessions.max; idx++) {
-        if (sessions.store[idx] && (0 == strcmp (client->uuid, sessions.store[idx]->uuid))) break;
+        if (sessions.store[idx] == client) {
+               sessions.store[idx] = NULL;
+               sessions.count--;
+               status = 1;
+               goto deleted;
+       }
     }
-
-    if (idx == sessions.max)
-       status = AFB_FAIL;
-    else {
-        sessions.count--;
-        ctxUuidFreeCB (sessions.store[idx]);
-        sessions.store[idx]=NULL;
-        status = AFB_SUCCESS;
-    }
-
+    status = 0;
+deleted:
     pthread_mutex_unlock(&sessions.mutex);
     return status;
 }
 
-static AFB_error ctxStoreAdd (AFB_clientCtx *client)
+static int ctxStoreAdd (struct AFB_clientCtx *client)
 {
     int idx;
     int status;
-    if (client == NULL)
-       return AFB_FAIL;
 
-    //fprintf (stderr, "ctxStoreAdd request uuid=%s count=%d\n", client->uuid, sessions.count);
+    assert (client != NULL);
 
     pthread_mutex_lock(&sessions.mutex);
 
     for (idx=0; idx < sessions.max; idx++) {
-        if (NULL == sessions.store[idx]) break;
-    }
-
-    if (idx == sessions.max) status=AFB_FAIL;
-    else {
-        status=AFB_SUCCESS;
-        sessions.count ++;
-        sessions.store[idx]= client;
+        if (NULL == sessions.store[idx]) {
+               sessions.store[idx] = client;
+               sessions.count++;
+               status = 1;
+               goto added;
+       }
     }
-
+    status = 0;
+added:
     pthread_mutex_unlock(&sessions.mutex);
     return status;
 }
 
 // Check if context timeout or not
-static int ctxStoreTooOld (AFB_clientCtx *ctx, int timeout)
+static int ctxStoreTooOld (struct AFB_clientCtx *ctx, time_t now)
 {
-    int res;
-    time_t now =  time(NULL);
-    res = (ctx->timeStamp + timeout) <= now;
-    return res;
+    assert (ctx != NULL);
+    return ctx->expiration < now;
 }
 
-// Loop on every entry and remove old context sessions.hash
-void ctxStoreGarbage (const int timeout)
+// Check if context is active or not
+static int ctxIsActive (struct AFB_clientCtx *ctx, time_t now)
 {
-    AFB_clientCtx *ctx;
-    long idx;
-
-    // Loop on Sessions Table and remove anything that is older than timeout
-    for (idx=0; idx < sessions.max; idx++) {
-        ctx = sessions.store[idx];
-        if ((ctx != NULL) && (ctxStoreTooOld(ctx, timeout))) {
-            ctxStoreDel (ctx);
-        }
-    }
+    assert (ctx != NULL);
+    return ctx->uuid[0] != 0 && ctx->expiration >= now;
 }
 
-// This function will return exiting client context or newly created client context
-AFB_clientCtx *ctxClientGet (AFB_request *request, int apiidx)
+// Loop on every entry and remove old context sessions.hash
+static void ctxStoreCleanUp (time_t now)
 {
-  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;
-            }
-        }
-    }
+       struct AFB_clientCtx *ctx;
+       long idx;
+
+       // Loop on Sessions Table and remove anything that is older than timeout
+       for (idx=0; idx < sessions.max; idx++) {
+               ctx = sessions.store[idx];
+               if (ctx != NULL && ctxStoreTooOld(ctx, now)) {
+                       ctxClientClose (ctx);
+               }
+       }
+}
 
-    // 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*));
-    }
+static struct AFB_clientCtx *new_context (const char *uuid, int timeout, time_t now)
+{
+       struct AFB_clientCtx *clientCtx;
+
+       /* allocates 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 {
+               if (strlen(uuid) >= sizeof clientCtx->uuid) {
+                       errno = EINVAL;
+                       goto error2;
+               }
+               strcpy(clientCtx->uuid, uuid);
+       }
+
+       /* init the token */
+       strcpy(clientCtx->token, sessions.initok);
+       clientCtx->timeout = timeout;
+       if (timeout != 0)
+               clientCtx->expiration = now + timeout;
+       else {
+               clientCtx->expiration = (time_t)(~(time_t)0);
+               if (clientCtx->expiration < 0)
+                       clientCtx->expiration = (time_t)(((unsigned long long)clientCtx->expiration) >> 1);
+       }
+       if (!ctxStoreAdd (clientCtx)) {
+               errno = ENOMEM;
+               goto error2;
+       }
+
+       clientCtx->access = now;
+       clientCtx->refcount = 1;
+       return clientCtx;
+
+error2:
+       free(clientCtx);
+error:
+       return NULL;
+}
 
-    uuid_generate(newuuid);         // create a new UUID
-    uuid_unparse_lower(newuuid, clientCtx->uuid);
+struct AFB_clientCtx *ctxClientCreate (const char *uuid, int timeout)
+{
+       time_t now;
 
-    // if table is full at 50% let's clean it up
-    if(sessions.count > (sessions.max / 2)) ctxStoreGarbage(request->config->cntxTimeout);
+       /* cleaning */
+       now = NOW;
+       ctxStoreCleanUp (now);
 
-    // finally add uuid into hashtable
-    if (AFB_SUCCESS != ctxStoreAdd (clientCtx)) {
-        free (clientCtx);
-        return NULL;
-    }
+       /* search for an existing one not too old */
+       if (uuid != NULL && ctxStoreSearch(uuid) != NULL) {
+               errno = EEXIST;
+               return NULL;
+       }
 
-    // if (verbose) fprintf (stderr, "ctxClientGet New uuid=[%s] token=[%s] timestamp=%d\n", clientCtx->uuid, clientCtx->token, clientCtx->timeStamp);
-    request->context = clientCtx->contexts[apiidx];
-    request->uuid = clientCtx->uuid;
-    return clientCtx;
+       return new_context(uuid, timeout, now);
 }
 
-// Sample Generic Ping Debug API
-AFB_error ctxTokenCheck (AFB_clientCtx *clientCtx, AFB_request *request)
+// This function will return exiting client context or newly created client context
+struct AFB_clientCtx *ctxClientGetSession (const char *uuid, int *created)
 {
-    const char *token;
-
-    if (clientCtx->contexts == NULL)
-       return AFB_EMPTY;
-
-    // this time have to extract token from query list
-    token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_token);
-
-    // if not token is providing we refuse the exchange
-    if ((token == NULL) || (clientCtx->token == NULL))
-       return AFB_FALSE;
+       struct AFB_clientCtx *clientCtx;
+       time_t now;
+
+       /* cleaning */
+       now = NOW;
+       ctxStoreCleanUp (now);
+
+       /* search for an existing one not too old */
+       if (uuid != NULL) {
+               clientCtx = ctxStoreSearch(uuid);
+               if (clientCtx != NULL) {
+                       *created = 0;
+                       clientCtx->access = now;
+                       clientCtx->refcount++;
+                       return clientCtx;
+               }
+       }
+
+       *created = 1;
+       return new_context(uuid, sessions.timeout, now);
+}
 
-    // compare current token with previous one
-    if ((0 == strcmp (token, clientCtx->token)) && (!ctxStoreTooOld (clientCtx, request->config->cntxTimeout))) {
-       return AFB_SUCCESS;
-    }
+struct AFB_clientCtx *ctxClientAddRef(struct AFB_clientCtx *clientCtx)
+{
+       if (clientCtx != NULL)
+               clientCtx->refcount++;
+       return clientCtx;
+}
 
-    // Token is not valid let move level of assurance to zero and free attached client handle
-    return AFB_FAIL;
+void ctxClientUnref(struct AFB_clientCtx *clientCtx)
+{
+       if (clientCtx != NULL) {
+               assert(clientCtx->refcount != 0);
+               --clientCtx->refcount;
+                       if (clientCtx->refcount == 0 && clientCtx->uuid[0] == 0) {
+                       ctxStoreDel (clientCtx);
+                       free(clientCtx);
+               }
+       }
 }
 
 // Free Client Session Context
-AFB_error ctxTokenReset (AFB_clientCtx *clientCtx, AFB_request *request)
+void ctxClientClose (struct AFB_clientCtx *clientCtx)
 {
-    if (clientCtx == NULL)
-       return AFB_EMPTY;
-    //if (verbose) fprintf (stderr, "ctxClientReset New uuid=[%s] token=[%s] timestamp=%d\n", clientCtx->uuid, clientCtx->token, clientCtx->timeStamp);
-
-    // Search for an existing client with the same UUID
-    clientCtx = ctxStoreSearch (clientCtx->uuid);
-    if (clientCtx == NULL)
-       return AFB_FALSE;
-
-    // Remove client from table
-    ctxStoreDel (clientCtx);
-
-    return AFB_SUCCESS;
+       assert(clientCtx != NULL);
+       if (clientCtx->uuid[0] != 0) {
+               clientCtx->uuid[0] = 0;
+               ctxUuidFreeCB (clientCtx);
+                       if (clientCtx->refcount == 0) {
+                       ctxStoreDel (clientCtx);
+                       free(clientCtx);
+               }
+       }
 }
 
-// generate a new token
-AFB_error ctxTokenCreate (AFB_clientCtx *clientCtx, AFB_request *request)
+// Sample Generic Ping Debug API
+int ctxTokenCheck (struct AFB_clientCtx *clientCtx, const char *token)
 {
-    uuid_t newuuid;
-    const char *token;
+       assert(clientCtx != NULL);
+       assert(token != NULL);
 
-    if (clientCtx == NULL)
-       return AFB_EMPTY;
+       // compare current token with previous one
+       if (!ctxIsActive (clientCtx, NOW))
+               return 0;
 
-    // if config->token!="" then verify that we have the right initial share secret
-    if (request->config->token[0] != '\0') {
+       if (clientCtx->token[0] && strcmp (token, clientCtx->token) != 0)
+               return 0;
 
-        // check for initial token secret and return if not presented
-        token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_token);
-        if (token == NULL)
-           return AFB_UNAUTH;
+       return 1;
+}
 
-        // verify that it fits with initial tokens fit
-        if (strcmp(request->config->token, token))
-           return AFB_UNAUTH;
-    }
+// generate a new token and update client context
+void ctxTokenNew (struct AFB_clientCtx *clientCtx)
+{
+       assert(clientCtx != NULL);
 
-    // create a UUID as token value
-    uuid_generate(newuuid);
-    uuid_unparse_lower(newuuid, clientCtx->token);
+       // Old token was valid let's regenerate a new one
+       new_uuid(clientCtx->token);
 
-    // keep track of time for session timeout and further clean up
-    clientCtx->timeStamp=time(NULL);
+       // keep track of time for session timeout and further clean up
+       if (clientCtx->timeout != 0)
+               clientCtx->expiration = NOW + clientCtx->timeout;
+}
 
-    // Token is also store in context but it might be convenient for plugin to access it directly
-    return AFB_SUCCESS;
+const char *ctxClientGetUuid (struct AFB_clientCtx *clientCtx)
+{
+       assert(clientCtx != NULL);
+       return clientCtx->uuid;
 }
 
+const char *ctxClientGetToken (struct AFB_clientCtx *clientCtx)
+{
+       assert(clientCtx != NULL);
+       return clientCtx->token;
+}
 
-// generate a new token and update client context
-AFB_error ctxTokenRefresh (AFB_clientCtx *clientCtx, AFB_request *request)
+unsigned ctxClientGetLOA (struct AFB_clientCtx *clientCtx)
 {
-    uuid_t newuuid;
+       assert(clientCtx != NULL);
+       return clientCtx->loa;
+}
 
-    if (clientCtx == NULL)
-        return AFB_EMPTY;
+void ctxClientSetLOA (struct AFB_clientCtx *clientCtx, unsigned loa)
+{
+       assert(clientCtx != NULL);
+       clientCtx->loa = loa;
+}
 
-    // Check if the old token is valid
-    if (ctxTokenCheck (clientCtx, request) != AFB_SUCCESS)
-        return AFB_FAIL;
+void *ctxClientValueGet(struct AFB_clientCtx *clientCtx, int index)
+{
+       assert(clientCtx != NULL);
+       assert(index >= 0);
+       assert(index < sessions.apicount);
+       return clientCtx->values[index].value;
+}
 
-    // Old token was valid let's regenerate a new one
-    uuid_generate(newuuid);         // create a new UUID
-    uuid_unparse_lower(newuuid, clientCtx->token);
+void ctxClientValueSet(struct AFB_clientCtx *clientCtx, int index, void *value, void (*free_value)(void*))
+{
+       struct client_value prev;
+       assert(clientCtx != NULL);
+       assert(index >= 0);
+       assert(index < sessions.apicount);
+       prev = clientCtx->values[index];
+       clientCtx->values[index] = (struct client_value){.value = value, .free_value = free_value};
+       if (prev.value != NULL && prev.value != value && prev.free_value != NULL)
+               prev.free_value(prev.value);
+}
 
-    // keep track of time for session timeout and further clean up
-    clientCtx->timeStamp=time(NULL);
+void *ctxClientCookieGet(struct AFB_clientCtx *clientCtx, const void *key)
+{
+       struct cookie *cookie;
+
+       cookie = clientCtx->cookies;
+       while(cookie != NULL) {
+               if (cookie->key == key)
+                       return cookie->value;
+               cookie = cookie->next;
+       }
+       return NULL;
+}
 
-    return AFB_SUCCESS;
+int ctxClientCookieSet(struct AFB_clientCtx *clientCtx, const void *key, void *value, void (*free_value)(void*))
+{
+       struct cookie *cookie;
+
+       /* search for a replacement */
+       cookie = clientCtx->cookies;
+       while(cookie != NULL) {
+               if (cookie->key == key) {
+                       if (cookie->value != NULL && cookie->value != value && cookie->free_value != NULL)
+                               cookie->free_value(cookie->value);
+                       cookie->value = value;
+                       cookie->free_value = free_value;
+                       return 0;
+               }
+               cookie = cookie->next;
+       }
+
+       /* allocates */
+       cookie = malloc(sizeof *cookie);
+       if (cookie == NULL) {
+               errno = ENOMEM;
+               return -1;
+       }
+
+       cookie->key = key;
+       cookie->value = value;
+       cookie->free_value = free_value;
+       cookie->next = clientCtx->cookies;
+       clientCtx->cookies = cookie;
+       return 0;
 }