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
44 static const char key_uuid[] = "uuid";
45 static const char key_token[] = "token";
47 // Free context [XXXX Should be protected again memory abort XXXX]
48 static void ctxUuidFreeCB (AFB_clientCtx *client)
52 // If application add a handle let's free it now
53 if (client->contexts != NULL) {
55 cnt = afb_apis_count();
56 // Free client handle with a standard Free function, with app callback or ignore it
57 for (idx=0; idx < cnt; idx ++) {
58 if (client->contexts[idx] != NULL) {
59 afb_apis_free_context(idx, client->contexts[idx]);
65 // Create a new store in RAM, not that is too small it will be automatically extended
66 void ctxStoreInit (int nbSession)
69 // let's create as store as hashtable does not have any
70 sessions.store = calloc (1 + (unsigned)nbSession, sizeof(AFB_clientCtx));
71 sessions.max = nbSession;
74 static AFB_clientCtx *ctxStoreSearch (const char* uuid)
77 AFB_clientCtx *client;
82 pthread_mutex_lock(&sessions.mutex);
84 for (idx=0; idx < sessions.max; idx++) {
85 if (sessions.store[idx] && (0 == strcmp (uuid, sessions.store[idx]->uuid))) break;
88 if (idx == sessions.max) client=NULL;
89 else client= sessions.store[idx];
90 pthread_mutex_unlock(&sessions.mutex);
95 static AFB_error ctxStoreDel (AFB_clientCtx *client)
103 pthread_mutex_lock(&sessions.mutex);
105 for (idx=0; idx < sessions.max; idx++) {
106 if (sessions.store[idx] && (0 == strcmp (client->uuid, sessions.store[idx]->uuid))) break;
109 if (idx == sessions.max)
113 ctxUuidFreeCB (sessions.store[idx]);
114 sessions.store[idx]=NULL;
115 status = AFB_SUCCESS;
118 pthread_mutex_unlock(&sessions.mutex);
122 static AFB_error ctxStoreAdd (AFB_clientCtx *client)
129 //fprintf (stderr, "ctxStoreAdd request uuid=%s count=%d\n", client->uuid, sessions.count);
131 pthread_mutex_lock(&sessions.mutex);
133 for (idx=0; idx < sessions.max; idx++) {
134 if (NULL == sessions.store[idx]) break;
137 if (idx == sessions.max) status=AFB_FAIL;
141 sessions.store[idx]= client;
144 pthread_mutex_unlock(&sessions.mutex);
148 // Check if context timeout or not
149 static int ctxStoreTooOld (AFB_clientCtx *ctx, int timeout)
152 time_t now = time(NULL);
153 res = (ctx->timeStamp + timeout) <= now;
157 // Loop on every entry and remove old context sessions.hash
158 void ctxStoreGarbage (const int timeout)
163 // Loop on Sessions Table and remove anything that is older than timeout
164 for (idx=0; idx < sessions.max; idx++) {
165 ctx = sessions.store[idx];
166 if ((ctx != NULL) && (ctxStoreTooOld(ctx, timeout))) {
172 // This function will return exiting client context or newly created client context
173 AFB_clientCtx *ctxClientGet (AFB_request *request)
175 AFB_clientCtx *clientCtx=NULL;
179 if (request->config->token == NULL) return NULL;
181 // Check if client as a context or not inside the URL
182 uuid = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_uuid);
184 // if UUID in query we're restfull with no cookies otherwise check for cookie
186 request->restfull = TRUE;
189 request->restfull = FALSE;
190 snprintf(cookie, sizeof cookie, "%s-%d", COOKIE_NAME, request->config->httpdPort);
191 uuid = MHD_lookup_connection_value (request->connection, MHD_COOKIE_KIND, cookie);
194 // Warning when no cookie defined MHD_lookup_connection_value may return something !!!
195 if ((uuid != NULL) && (strnlen (uuid, 10) >= 10)) {
196 // search if client context exist and it not timeout let's use it
197 clientCtx = ctxStoreSearch (uuid);
200 if (ctxStoreTooOld (clientCtx, request->config->cntxTimeout)) {
201 // this session is too old let's delete it
202 ctxStoreDel (clientCtx);
210 // we have no session let's create one otherwise let's clean any exiting values
211 if (clientCtx == NULL) {
212 clientCtx = calloc(1, sizeof(AFB_clientCtx)); // init NULL clientContext
213 clientCtx->contexts = calloc ((unsigned)afb_apis_count(), sizeof (void*));
216 uuid_generate(newuuid); // create a new UUID
217 uuid_unparse_lower(newuuid, clientCtx->uuid);
219 // if table is full at 50% let's clean it up
220 if(sessions.count > (sessions.max / 2)) ctxStoreGarbage(request->config->cntxTimeout);
222 // finally add uuid into hashtable
223 if (AFB_SUCCESS != ctxStoreAdd (clientCtx)) {
230 // Sample Generic Ping Debug API
231 AFB_error ctxTokenCheck (AFB_clientCtx *clientCtx, AFB_request *request)
235 if (clientCtx->contexts == NULL)
238 // this time have to extract token from query list
239 token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_token);
241 // if not token is providing we refuse the exchange
242 if ((token == NULL) || (clientCtx->token == NULL))
245 // compare current token with previous one
246 if ((0 == strcmp (token, clientCtx->token)) && (!ctxStoreTooOld (clientCtx, request->config->cntxTimeout))) {
250 // Token is not valid let move level of assurance to zero and free attached client handle
254 // Free Client Session Context
255 AFB_error ctxTokenReset (AFB_clientCtx *clientCtx, AFB_request *request)
257 if (clientCtx == NULL)
259 //if (verbose) fprintf (stderr, "ctxClientReset New uuid=[%s] token=[%s] timestamp=%d\n", clientCtx->uuid, clientCtx->token, clientCtx->timeStamp);
261 // Search for an existing client with the same UUID
262 clientCtx = ctxStoreSearch (clientCtx->uuid);
263 if (clientCtx == NULL)
266 // Remove client from table
267 ctxStoreDel (clientCtx);
272 // generate a new token
273 AFB_error ctxTokenCreate (AFB_clientCtx *clientCtx, AFB_request *request)
278 if (clientCtx == NULL)
281 // if config->token!="" then verify that we have the right initial share secret
282 if (request->config->token[0] != '\0') {
284 // check for initial token secret and return if not presented
285 token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_token);
289 // verify that it fits with initial tokens fit
290 if (strcmp(request->config->token, token))
294 // create a UUID as token value
295 uuid_generate(newuuid);
296 uuid_unparse_lower(newuuid, clientCtx->token);
298 // keep track of time for session timeout and further clean up
299 clientCtx->timeStamp=time(NULL);
301 // Token is also store in context but it might be convenient for plugin to access it directly
306 // generate a new token and update client context
307 AFB_error ctxTokenRefresh (AFB_clientCtx *clientCtx, AFB_request *request)
311 if (clientCtx == NULL)
314 // Check if the old token is valid
315 if (ctxTokenCheck (clientCtx, request) != AFB_SUCCESS)
318 // Old token was valid let's regenerate a new one
319 uuid_generate(newuuid); // create a new UUID
320 uuid_unparse_lower(newuuid, clientCtx->token);
322 // keep track of time for session timeout and further clean up
323 clientCtx->timeStamp=time(NULL);