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>
35 // Session UUID are store in a simple array [for 10 sessions this should be enough]
37 pthread_mutex_t mutex; // declare a mutex to protect hash table
38 AFB_clientCtx **store; // sessions store
39 int count; // current number of sessions
43 static const char key_uuid[] = "uuid";
44 static const char key_token[] = "token";
46 // Free context [XXXX Should be protected again memory abort XXXX]
47 static void ctxUuidFreeCB (AFB_clientCtx *client)
51 // If application add a handle let's free it now
52 if (client->contexts != NULL) {
54 cnt = afb_apis_count();
55 // Free client handle with a standard Free function, with app callback or ignore it
56 for (idx=0; idx < cnt; idx ++) {
57 if (client->contexts[idx] != NULL) {
58 afb_apis_free_context(idx, client->contexts[idx]);
64 // Create a new store in RAM, not that is too small it will be automatically extended
65 void ctxStoreInit (int nbSession)
68 // let's create as store as hashtable does not have any
69 sessions.store = calloc (1 + (unsigned)nbSession, sizeof(AFB_clientCtx));
70 sessions.max = nbSession;
73 static AFB_clientCtx *ctxStoreSearch (const char* uuid)
76 AFB_clientCtx *client;
81 pthread_mutex_lock(&sessions.mutex);
83 for (idx=0; idx < sessions.max; idx++) {
84 if (sessions.store[idx] && (0 == strcmp (uuid, sessions.store[idx]->uuid))) break;
87 if (idx == sessions.max) client=NULL;
88 else client= sessions.store[idx];
89 pthread_mutex_unlock(&sessions.mutex);
94 static AFB_error ctxStoreDel (AFB_clientCtx *client)
102 pthread_mutex_lock(&sessions.mutex);
104 for (idx=0; idx < sessions.max; idx++) {
105 if (sessions.store[idx] && (0 == strcmp (client->uuid, sessions.store[idx]->uuid))) break;
108 if (idx == sessions.max)
112 ctxUuidFreeCB (sessions.store[idx]);
113 sessions.store[idx]=NULL;
114 status = AFB_SUCCESS;
117 pthread_mutex_unlock(&sessions.mutex);
121 static AFB_error ctxStoreAdd (AFB_clientCtx *client)
128 //fprintf (stderr, "ctxStoreAdd request uuid=%s count=%d\n", client->uuid, sessions.count);
130 pthread_mutex_lock(&sessions.mutex);
132 for (idx=0; idx < sessions.max; idx++) {
133 if (NULL == sessions.store[idx]) break;
136 if (idx == sessions.max) status=AFB_FAIL;
140 sessions.store[idx]= client;
143 pthread_mutex_unlock(&sessions.mutex);
147 // Check if context timeout or not
148 static int ctxStoreTooOld (AFB_clientCtx *ctx, int timeout)
151 time_t now = time(NULL);
152 res = (ctx->timeStamp + timeout) <= now;
156 // Loop on every entry and remove old context sessions.hash
157 void ctxStoreGarbage (const int timeout)
162 // Loop on Sessions Table and remove anything that is older than timeout
163 for (idx=0; idx < sessions.max; idx++) {
164 ctx = sessions.store[idx];
165 if ((ctx != NULL) && (ctxStoreTooOld(ctx, timeout))) {
171 // This function will return exiting client context or newly created client context
172 AFB_clientCtx *ctxClientGet (AFB_request *request, int apiidx)
174 AFB_clientCtx *clientCtx=NULL;
178 if (request->config->token == NULL) return NULL;
180 // Check if client as a context or not inside the URL
181 uuid = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_uuid);
183 // if UUID in query we're restfull with no cookies otherwise check for cookie
185 request->restfull = TRUE;
188 request->restfull = FALSE;
189 snprintf(cookie, sizeof cookie, "%s-%d", COOKIE_NAME, request->config->httpdPort);
190 uuid = MHD_lookup_connection_value (request->connection, MHD_COOKIE_KIND, cookie);
193 // Warning when no cookie defined MHD_lookup_connection_value may return something !!!
194 if ((uuid != NULL) && (strnlen (uuid, 10) >= 10)) {
195 // search if client context exist and it not timeout let's use it
196 clientCtx = ctxStoreSearch (uuid);
199 if (ctxStoreTooOld (clientCtx, request->config->cntxTimeout)) {
200 // this session is too old let's delete it
201 ctxStoreDel (clientCtx);
204 request->context = clientCtx->contexts[apiidx];
205 request->uuid = uuid;
211 // we have no session let's create one otherwise let's clean any exiting values
212 if (clientCtx == NULL) {
213 clientCtx = calloc(1, sizeof(AFB_clientCtx)); // init NULL clientContext
214 clientCtx->contexts = calloc ((unsigned)afb_apis_count(), sizeof (void*));
217 uuid_generate(newuuid); // create a new UUID
218 uuid_unparse_lower(newuuid, clientCtx->uuid);
220 // if table is full at 50% let's clean it up
221 if(sessions.count > (sessions.max / 2)) ctxStoreGarbage(request->config->cntxTimeout);
223 // finally add uuid into hashtable
224 if (AFB_SUCCESS != ctxStoreAdd (clientCtx)) {
229 // if (verbose) fprintf (stderr, "ctxClientGet New uuid=[%s] token=[%s] timestamp=%d\n", clientCtx->uuid, clientCtx->token, clientCtx->timeStamp);
230 request->context = clientCtx->contexts[apiidx];
231 request->uuid = clientCtx->uuid;
235 // Sample Generic Ping Debug API
236 AFB_error ctxTokenCheck (AFB_clientCtx *clientCtx, AFB_request *request)
240 if (clientCtx->contexts == NULL)
243 // this time have to extract token from query list
244 token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_token);
246 // if not token is providing we refuse the exchange
247 if ((token == NULL) || (clientCtx->token == NULL))
250 // compare current token with previous one
251 if ((0 == strcmp (token, clientCtx->token)) && (!ctxStoreTooOld (clientCtx, request->config->cntxTimeout))) {
255 // Token is not valid let move level of assurance to zero and free attached client handle
259 // Free Client Session Context
260 AFB_error ctxTokenReset (AFB_clientCtx *clientCtx, AFB_request *request)
262 if (clientCtx == NULL)
264 //if (verbose) fprintf (stderr, "ctxClientReset New uuid=[%s] token=[%s] timestamp=%d\n", clientCtx->uuid, clientCtx->token, clientCtx->timeStamp);
266 // Search for an existing client with the same UUID
267 clientCtx = ctxStoreSearch (clientCtx->uuid);
268 if (clientCtx == NULL)
271 // Remove client from table
272 ctxStoreDel (clientCtx);
277 // generate a new token
278 AFB_error ctxTokenCreate (AFB_clientCtx *clientCtx, AFB_request *request)
283 if (clientCtx == NULL)
286 // if config->token!="" then verify that we have the right initial share secret
287 if (request->config->token[0] != '\0') {
289 // check for initial token secret and return if not presented
290 token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_token);
294 // verify that it fits with initial tokens fit
295 if (strcmp(request->config->token, token))
299 // create a UUID as token value
300 uuid_generate(newuuid);
301 uuid_unparse_lower(newuuid, clientCtx->token);
303 // keep track of time for session timeout and further clean up
304 clientCtx->timeStamp=time(NULL);
306 // Token is also store in context but it might be convenient for plugin to access it directly
311 // generate a new token and update client context
312 AFB_error ctxTokenRefresh (AFB_clientCtx *clientCtx, AFB_request *request)
316 if (clientCtx == NULL)
319 // Check if the old token is valid
320 if (ctxTokenCheck (clientCtx, request) != AFB_SUCCESS)
323 // Old token was valid let's regenerate a new one
324 uuid_generate(newuuid); // create a new UUID
325 uuid_unparse_lower(newuuid, clientCtx->token);
327 // keep track of time for session timeout and further clean up
328 clientCtx->timeStamp=time(NULL);