2 * Copyright (C) 2015 "IoT.bzh"
3 * Author "Fulup Ar Foll"
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 * http://stackoverflow.com/questions/25971505/how-to-delete-element-from-hsearch
24 #include "local-def.h"
29 #include <sys/types.h>
34 // Session UUID are store in a simple array [for 10 sessions this should be enough]
36 pthread_mutex_t mutex; // declare a mutex to protect hash table
37 AFB_clientCtx **store; // sessions store
38 int count; // current number of sessions
42 static const char key_uuid[] = "uuid";
43 static const char key_token[] = "token";
45 // Free context [XXXX Should be protected again memory abort XXXX]
46 static void ctxUuidFreeCB (AFB_clientCtx *client)
49 AFB_plugin **plugins = client->plugins;
50 AFB_freeCtxCB freeCtxCB;
53 // If application add a handle let's free it now
54 if (client->contexts != NULL) {
56 // Free client handle with a standard Free function, with app callback or ignore it
57 for (idx=0; client->plugins[idx] != NULL; idx ++) {
58 if (client->contexts[idx] != NULL) {
59 freeCtxCB = client->plugins[idx]->freeCtxCB;
60 if (freeCtxCB == NULL)
61 free (client->contexts[idx]);
62 else if (freeCtxCB != (void*)-1)
63 freeCtxCB(client->contexts[idx], plugins[idx]->handle, client->uuid);
69 // Create a new store in RAM, not that is too small it will be automatically extended
70 void ctxStoreInit (int nbSession)
73 // let's create as store as hashtable does not have any
74 sessions.store = calloc (1 + (unsigned)nbSession, sizeof(AFB_clientCtx));
75 sessions.max = nbSession;
78 static AFB_clientCtx *ctxStoreSearch (const char* uuid)
81 AFB_clientCtx *client;
86 pthread_mutex_lock(&sessions.mutex);
88 for (idx=0; idx < sessions.max; idx++) {
89 if (sessions.store[idx] && (0 == strcmp (uuid, sessions.store[idx]->uuid))) break;
92 if (idx == sessions.max) client=NULL;
93 else client= sessions.store[idx];
94 pthread_mutex_unlock(&sessions.mutex);
99 static AFB_error ctxStoreDel (AFB_clientCtx *client)
107 pthread_mutex_lock(&sessions.mutex);
109 for (idx=0; idx < sessions.max; idx++) {
110 if (sessions.store[idx] && (0 == strcmp (client->uuid, sessions.store[idx]->uuid))) break;
113 if (idx == sessions.max)
117 ctxUuidFreeCB (sessions.store[idx]);
118 sessions.store[idx]=NULL;
119 status = AFB_SUCCESS;
122 pthread_mutex_unlock(&sessions.mutex);
126 static AFB_error ctxStoreAdd (AFB_clientCtx *client)
133 //fprintf (stderr, "ctxStoreAdd request uuid=%s count=%d\n", client->uuid, sessions.count);
135 pthread_mutex_lock(&sessions.mutex);
137 for (idx=0; idx < sessions.max; idx++) {
138 if (NULL == sessions.store[idx]) break;
141 if (idx == sessions.max) status=AFB_FAIL;
145 sessions.store[idx]= client;
148 pthread_mutex_unlock(&sessions.mutex);
152 // Check if context timeout or not
153 static int ctxStoreToOld (AFB_clientCtx *ctx, int timeout)
156 time_t now = time(NULL);
157 res = (ctx->timeStamp + timeout) <= now;
161 // Loop on every entry and remove old context sessions.hash
162 void ctxStoreGarbage (const int timeout)
167 // Loop on Sessions Table and remove anything that is older than timeout
168 for (idx=0; idx < sessions.max; idx++) {
169 ctx=sessions.store[idx];
170 if ((ctx != NULL) && (ctxStoreToOld(ctx, timeout))) {
176 // This function will return exiting client context or newly created client context
177 AFB_clientCtx *ctxClientGet (AFB_request *request, int idx)
179 AFB_clientCtx *clientCtx=NULL;
183 if (request->config->token == NULL) return NULL;
185 // Check if client as a context or not inside the URL
186 uuid = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_uuid);
188 // if UUID in query we're restfull with no cookies otherwise check for cookie
190 request->restfull = TRUE;
193 request->restfull = FALSE;
194 snprintf(cookie, sizeof cookie, "%s-%d", COOKIE_NAME, request->config->httpdPort);
195 uuid = MHD_lookup_connection_value (request->connection, MHD_COOKIE_KIND, cookie);
198 // Warning when no cookie defined MHD_lookup_connection_value may return something !!!
199 if ((uuid != NULL) && (strnlen (uuid, 10) >= 10)) {
200 // search if client context exist and it not timeout let's use it
201 clientCtx = ctxStoreSearch (uuid);
204 if (ctxStoreToOld (clientCtx, request->config->cntxTimeout)) {
205 // this session is too old let's delete it
206 ctxStoreDel (clientCtx);
209 request->context=clientCtx->contexts[idx];
210 request->handle = clientCtx->plugins[idx]->handle;
217 // we have no session let's create one otherwise let's clean any exiting values
218 if (clientCtx == NULL) {
219 clientCtx = calloc(1, sizeof(AFB_clientCtx)); // init NULL clientContext
220 clientCtx->contexts = calloc (1, (unsigned)request->config->pluginCount * (sizeof (void*)));
221 clientCtx->plugins = request->plugins;
224 uuid_generate(newuuid); // create a new UUID
225 uuid_unparse_lower(newuuid, clientCtx->uuid);
227 // if table is full at 50% let's clean it up
228 if(sessions.count > (sessions.max / 2)) ctxStoreGarbage(request->config->cntxTimeout);
230 // finally add uuid into hashtable
231 if (AFB_SUCCESS != ctxStoreAdd (clientCtx)) {
236 // if (verbose) fprintf (stderr, "ctxClientGet New uuid=[%s] token=[%s] timestamp=%d\n", clientCtx->uuid, clientCtx->token, clientCtx->timeStamp);
237 request->context = clientCtx->contexts[idx];
238 request->handle = clientCtx->plugins[idx]->handle;
239 request->uuid=clientCtx->uuid;
243 // Sample Generic Ping Debug API
244 AFB_error ctxTokenCheck (AFB_clientCtx *clientCtx, AFB_request *request)
248 if (clientCtx->contexts == NULL)
251 // this time have to extract token from query list
252 token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_token);
254 // if not token is providing we refuse the exchange
255 if ((token == NULL) || (clientCtx->token == NULL))
258 // compare current token with previous one
259 if ((0 == strcmp (token, clientCtx->token)) && (!ctxStoreToOld (clientCtx, request->config->cntxTimeout))) {
263 // Token is not valid let move level of assurance to zero and free attached client handle
267 // Free Client Session Context
268 AFB_error ctxTokenReset (AFB_clientCtx *clientCtx, AFB_request *request)
270 if (clientCtx == NULL)
272 //if (verbose) fprintf (stderr, "ctxClientReset New uuid=[%s] token=[%s] timestamp=%d\n", clientCtx->uuid, clientCtx->token, clientCtx->timeStamp);
274 // Search for an existing client with the same UUID
275 clientCtx = ctxStoreSearch (clientCtx->uuid);
276 if (clientCtx == NULL)
279 // Remove client from table
280 ctxStoreDel (clientCtx);
285 // generate a new token
286 AFB_error ctxTokenCreate (AFB_clientCtx *clientCtx, AFB_request *request)
291 if (clientCtx == NULL)
294 // if config->token!="" then verify that we have the right initial share secret
295 if (request->config->token[0] != '\0') {
297 // check for initial token secret and return if not presented
298 token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_token);
302 // verify that it fits with initial tokens fit
303 if (strcmp(request->config->token, token))
307 // create a UUID as token value
308 uuid_generate(newuuid);
309 uuid_unparse_lower(newuuid, clientCtx->token);
311 // keep track of time for session timeout and further clean up
312 clientCtx->timeStamp=time(NULL);
314 // Token is also store in context but it might be convenient for plugin to access it directly
319 // generate a new token and update client context
320 AFB_error ctxTokenRefresh (AFB_clientCtx *clientCtx, AFB_request *request)
324 if (clientCtx == NULL)
327 // Check if the old token is valid
328 if (ctxTokenCheck (clientCtx, request) != AFB_SUCCESS)
331 // Old token was valid let's regenerate a new one
332 uuid_generate(newuuid); // create a new UUID
333 uuid_unparse_lower(newuuid, clientCtx->token);
335 // keep track of time for session timeout and further clean up
336 clientCtx->timeStamp=time(NULL);