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>
36 // Session UUID are store in a simple array [for 10 sessions this should be enough]
38 pthread_mutex_t mutex; // declare a mutex to protect hash table
39 AFB_clientCtx **store; // sessions store
40 int count; // current number of sessions
46 static const char key_uuid[] = "uuid";
47 static const char key_token[] = "token";
49 // Free context [XXXX Should be protected again memory abort XXXX]
50 static void ctxUuidFreeCB (AFB_clientCtx *client)
54 // If application add a handle let's free it now
55 if (client->contexts != NULL) {
57 // Free client handle with a standard Free function, with app callback or ignore it
58 for (idx=0; idx < sessions.apicount; idx ++) {
59 if (client->contexts[idx] != NULL) {
60 afb_apis_free_context(idx, client->contexts[idx]);
66 // Create a new store in RAM, not that is too small it will be automatically extended
67 void ctxStoreInit (int nbSession, int timeout, int apicount)
70 // let's create as store as hashtable does not have any
71 sessions.store = calloc (1 + (unsigned)nbSession, sizeof(AFB_clientCtx));
72 sessions.max = nbSession;
73 sessions.timeout = timeout;
74 sessions.apicount = apicount;
77 static AFB_clientCtx *ctxStoreSearch (const char* uuid)
80 AFB_clientCtx *client;
85 pthread_mutex_lock(&sessions.mutex);
87 for (idx=0; idx < sessions.max; idx++) {
88 if (sessions.store[idx] && (0 == strcmp (uuid, sessions.store[idx]->uuid))) break;
91 if (idx == sessions.max) client=NULL;
92 else client= sessions.store[idx];
93 pthread_mutex_unlock(&sessions.mutex);
98 static AFB_error ctxStoreDel (AFB_clientCtx *client)
106 pthread_mutex_lock(&sessions.mutex);
108 for (idx=0; idx < sessions.max; idx++) {
109 if (sessions.store[idx] && (0 == strcmp (client->uuid, sessions.store[idx]->uuid))) break;
112 if (idx == sessions.max)
116 ctxUuidFreeCB (sessions.store[idx]);
117 sessions.store[idx]=NULL;
118 status = AFB_SUCCESS;
121 pthread_mutex_unlock(&sessions.mutex);
125 static AFB_error ctxStoreAdd (AFB_clientCtx *client)
132 //fprintf (stderr, "ctxStoreAdd request uuid=%s count=%d\n", client->uuid, sessions.count);
134 pthread_mutex_lock(&sessions.mutex);
136 for (idx=0; idx < sessions.max; idx++) {
137 if (NULL == sessions.store[idx]) break;
140 if (idx == sessions.max) status=AFB_FAIL;
144 sessions.store[idx]= client;
147 pthread_mutex_unlock(&sessions.mutex);
151 // Check if context timeout or not
152 static int ctxStoreTooOld (AFB_clientCtx *ctx, int timeout)
155 time_t now = time(NULL);
156 res = (ctx->timeStamp + timeout) <= now;
160 // Loop on every entry and remove old context sessions.hash
161 void ctxStoreGarbage (const int timeout)
166 // Loop on Sessions Table and remove anything that is older than timeout
167 for (idx=0; idx < sessions.max; idx++) {
168 ctx = sessions.store[idx];
169 if ((ctx != NULL) && (ctxStoreTooOld(ctx, timeout))) {
175 // This function will return exiting client context or newly created client context
176 AFB_clientCtx *ctxClientGet (AFB_request *request)
178 AFB_clientCtx *clientCtx=NULL;
182 if (request->config->token == NULL) return NULL;
184 // Check if client as a context or not inside the URL
185 uuid = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_uuid);
187 // if UUID in query we're restfull with no cookies otherwise check for cookie
189 request->restfull = TRUE;
192 request->restfull = FALSE;
193 snprintf(cookie, sizeof cookie, "%s-%d", COOKIE_NAME, request->config->httpdPort);
194 uuid = MHD_lookup_connection_value (request->connection, MHD_COOKIE_KIND, cookie);
197 // Warning when no cookie defined MHD_lookup_connection_value may return something !!!
198 if ((uuid != NULL) && (strnlen (uuid, 10) >= 10)) {
199 // search if client context exist and it not timeout let's use it
200 clientCtx = ctxStoreSearch (uuid);
203 if (ctxStoreTooOld (clientCtx, sessions.timeout)) {
204 // this session is too old let's delete it
205 ctxStoreDel (clientCtx);
213 // we have no session let's create one otherwise let's clean any exiting values
214 if (clientCtx == NULL) {
215 clientCtx = calloc(1, sizeof(AFB_clientCtx)); // init NULL clientContext
216 clientCtx->contexts = calloc ((unsigned)sessions.apicount, sizeof (void*));
219 uuid_generate(newuuid); // create a new UUID
220 uuid_unparse_lower(newuuid, clientCtx->uuid);
222 // if table is full at 50% let's clean it up
223 if(sessions.count > (sessions.max / 2)) ctxStoreGarbage(sessions.timeout);
225 // finally add uuid into hashtable
226 if (AFB_SUCCESS != ctxStoreAdd (clientCtx)) {
233 // Sample Generic Ping Debug API
234 AFB_error ctxTokenCheck (AFB_clientCtx *clientCtx, AFB_request *request)
238 if (clientCtx->contexts == NULL)
241 // this time have to extract token from query list
242 token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_token);
244 // if not token is providing we refuse the exchange
245 if ((token == NULL) || (clientCtx->token == NULL))
248 // compare current token with previous one
249 if ((0 == strcmp (token, clientCtx->token)) && (!ctxStoreTooOld (clientCtx, sessions.timeout))) {
253 // Token is not valid let move level of assurance to zero and free attached client handle
257 // Free Client Session Context
258 AFB_error ctxTokenReset (AFB_clientCtx *clientCtx, AFB_request *request)
260 if (clientCtx == NULL)
262 //if (verbose) fprintf (stderr, "ctxClientReset New uuid=[%s] token=[%s] timestamp=%d\n", clientCtx->uuid, clientCtx->token, clientCtx->timeStamp);
264 // Search for an existing client with the same UUID
265 clientCtx = ctxStoreSearch (clientCtx->uuid);
266 if (clientCtx == NULL)
269 // Remove client from table
270 ctxStoreDel (clientCtx);
275 // generate a new token
276 AFB_error ctxTokenCreate (AFB_clientCtx *clientCtx, AFB_request *request)
281 if (clientCtx == NULL)
284 // if config->token!="" then verify that we have the right initial share secret
285 if (request->config->token[0] != '\0') {
287 // check for initial token secret and return if not presented
288 token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_token);
292 // verify that it fits with initial tokens fit
293 if (strcmp(request->config->token, token))
297 // create a UUID as token value
298 uuid_generate(newuuid);
299 uuid_unparse_lower(newuuid, clientCtx->token);
301 // keep track of time for session timeout and further clean up
302 clientCtx->timeStamp=time(NULL);
304 // Token is also store in context but it might be convenient for plugin to access it directly
309 // generate a new token and update client context
310 AFB_error ctxTokenRefresh (AFB_clientCtx *clientCtx, AFB_request *request)
314 if (clientCtx == NULL)
317 // Check if the old token is valid
318 if (ctxTokenCheck (clientCtx, request) != AFB_SUCCESS)
321 // Old token was valid let's regenerate a new one
322 uuid_generate(newuuid); // create a new UUID
323 uuid_unparse_lower(newuuid, clientCtx->token);
325 // keep track of time for session timeout and further clean up
326 clientCtx->timeStamp=time(NULL);