743f825470ac85cb848625f56cd0a639eec27fa7
[src/app-framework-binder.git] / src / session.c
1 /*
2  * Copyright (C) 2015 "IoT.bzh"
3  * Author "Fulup Ar Foll"
4  *
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.
9  *
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.
14  *
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/>.
17  *
18  * Reference:
19  * http://stackoverflow.com/questions/25971505/how-to-delete-element-from-hsearch
20  *
21  */
22
23
24 #include "local-def.h"
25 #include <dirent.h>
26 #include <string.h>
27 #include <time.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <pthread.h>
31 #include <search.h>
32
33
34 // Session UUID are store in a simple array [for 10 sessions this should be enough]
35 static struct {
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
39   int max;
40 } sessions;
41
42 static const char key_uuid[] = "uuid";
43 static const char key_token[] = "token";
44
45 // Free context [XXXX Should be protected again memory abort XXXX]
46 static void ctxUuidFreeCB (AFB_clientCtx *client)
47 {
48
49     AFB_plugin **plugins = client->plugins;
50     AFB_freeCtxCB freeCtxCB;
51     int idx;
52
53     // If application add a handle let's free it now
54     if (client->contexts != NULL) {
55
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);
64             }
65         }
66     }
67 }
68
69 // Create a new store in RAM, not that is too small it will be automatically extended
70 void ctxStoreInit (int nbSession)
71 {
72
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;
76 }
77
78 static AFB_clientCtx *ctxStoreSearch (const char* uuid)
79 {
80     int  idx;
81     AFB_clientCtx *client;
82
83     if (uuid == NULL)
84         return NULL;
85
86     pthread_mutex_lock(&sessions.mutex);
87
88     for (idx=0; idx < sessions.max; idx++) {
89         if (sessions.store[idx] && (0 == strcmp (uuid, sessions.store[idx]->uuid))) break;
90     }
91
92     if (idx == sessions.max) client=NULL;
93     else client= sessions.store[idx];
94     pthread_mutex_unlock(&sessions.mutex);
95
96     return client;
97 }
98
99 static AFB_error ctxStoreDel (AFB_clientCtx *client)
100 {
101     int idx;
102     int status;
103
104     if (client == NULL)
105         return AFB_FAIL;
106
107     pthread_mutex_lock(&sessions.mutex);
108
109     for (idx=0; idx < sessions.max; idx++) {
110         if (sessions.store[idx] && (0 == strcmp (client->uuid, sessions.store[idx]->uuid))) break;
111     }
112
113     if (idx == sessions.max)
114         status = AFB_FAIL;
115     else {
116         sessions.count--;
117         ctxUuidFreeCB (sessions.store[idx]);
118         sessions.store[idx]=NULL;
119         status = AFB_SUCCESS;
120     }
121
122     pthread_mutex_unlock(&sessions.mutex);
123     return status;
124 }
125
126 static AFB_error ctxStoreAdd (AFB_clientCtx *client)
127 {
128     int idx;
129     int status;
130     if (client == NULL)
131         return AFB_FAIL;
132
133     //fprintf (stderr, "ctxStoreAdd request uuid=%s count=%d\n", client->uuid, sessions.count);
134
135     pthread_mutex_lock(&sessions.mutex);
136
137     for (idx=0; idx < sessions.max; idx++) {
138         if (NULL == sessions.store[idx]) break;
139     }
140
141     if (idx == sessions.max) status=AFB_FAIL;
142     else {
143         status=AFB_SUCCESS;
144         sessions.count ++;
145         sessions.store[idx]= client;
146     }
147
148     pthread_mutex_unlock(&sessions.mutex);
149     return status;
150 }
151
152 // Check if context timeout or not
153 static int ctxStoreToOld (AFB_clientCtx *ctx, int timeout)
154 {
155     int res;
156     time_t now =  time(NULL);
157     res = (ctx->timeStamp + timeout) <= now;
158     return res;
159 }
160
161 // Loop on every entry and remove old context sessions.hash
162 void ctxStoreGarbage (const int timeout)
163 {
164     AFB_clientCtx *ctx;
165     long idx;
166
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))) {
171             ctxStoreDel (ctx);
172         }
173     }
174 }
175
176 // This function will return exiting client context or newly created client context
177 AFB_clientCtx *ctxClientGet (AFB_request *request, int idx)
178 {
179   AFB_clientCtx *clientCtx=NULL;
180   const char *uuid;
181   uuid_t newuuid;
182
183     if (request->config->token == NULL) return NULL;
184
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);
187
188     // if UUID in query we're restfull with no cookies otherwise check for cookie
189     if (uuid != NULL)
190         request->restfull = TRUE;
191     else {
192         char cookie[64];
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);
196     };
197
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);
202
203         if (clientCtx) {
204             if (ctxStoreToOld (clientCtx, request->config->cntxTimeout)) {
205                  // this session is too old let's delete it
206                 ctxStoreDel (clientCtx);
207                 clientCtx = NULL;
208             } else {
209                 request->context=clientCtx->contexts[idx];
210                 request->handle  = clientCtx->plugins[idx]->handle;
211                 request->uuid= uuid;
212                 return clientCtx;
213             }
214         }
215     }
216
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;
222     }
223
224     uuid_generate(newuuid);         // create a new UUID
225     uuid_unparse_lower(newuuid, clientCtx->uuid);
226
227     // if table is full at 50% let's clean it up
228     if(sessions.count > (sessions.max / 2)) ctxStoreGarbage(request->config->cntxTimeout);
229
230     // finally add uuid into hashtable
231     if (AFB_SUCCESS != ctxStoreAdd (clientCtx)) {
232         free (clientCtx);
233         return NULL;
234     }
235
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;
240     return clientCtx;
241 }
242
243 // Sample Generic Ping Debug API
244 AFB_error ctxTokenCheck (AFB_clientCtx *clientCtx, AFB_request *request)
245 {
246     const char *token;
247
248     if (clientCtx->contexts == NULL)
249         return AFB_EMPTY;
250
251     // this time have to extract token from query list
252     token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_token);
253
254     // if not token is providing we refuse the exchange
255     if ((token == NULL) || (clientCtx->token == NULL))
256         return AFB_FALSE;
257
258     // compare current token with previous one
259     if ((0 == strcmp (token, clientCtx->token)) && (!ctxStoreToOld (clientCtx, request->config->cntxTimeout))) {
260        return AFB_SUCCESS;
261     }
262
263     // Token is not valid let move level of assurance to zero and free attached client handle
264     return AFB_FAIL;
265 }
266
267 // Free Client Session Context
268 AFB_error ctxTokenReset (AFB_clientCtx *clientCtx, AFB_request *request)
269 {
270     if (clientCtx == NULL)
271        return AFB_EMPTY;
272     //if (verbose) fprintf (stderr, "ctxClientReset New uuid=[%s] token=[%s] timestamp=%d\n", clientCtx->uuid, clientCtx->token, clientCtx->timeStamp);
273
274     // Search for an existing client with the same UUID
275     clientCtx = ctxStoreSearch (clientCtx->uuid);
276     if (clientCtx == NULL)
277        return AFB_FALSE;
278
279     // Remove client from table
280     ctxStoreDel (clientCtx);
281
282     return AFB_SUCCESS;
283 }
284
285 // generate a new token
286 AFB_error ctxTokenCreate (AFB_clientCtx *clientCtx, AFB_request *request)
287 {
288     uuid_t newuuid;
289     const char *token;
290
291     if (clientCtx == NULL)
292        return AFB_EMPTY;
293
294     // if config->token!="" then verify that we have the right initial share secret
295     if (request->config->token[0] != '\0') {
296
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);
299         if (token == NULL)
300            return AFB_UNAUTH;
301
302         // verify that it fits with initial tokens fit
303         if (strcmp(request->config->token, token))
304            return AFB_UNAUTH;
305     }
306
307     // create a UUID as token value
308     uuid_generate(newuuid);
309     uuid_unparse_lower(newuuid, clientCtx->token);
310
311     // keep track of time for session timeout and further clean up
312     clientCtx->timeStamp=time(NULL);
313
314     // Token is also store in context but it might be convenient for plugin to access it directly
315     return AFB_SUCCESS;
316 }
317
318
319 // generate a new token and update client context
320 AFB_error ctxTokenRefresh (AFB_clientCtx *clientCtx, AFB_request *request)
321 {
322     uuid_t newuuid;
323
324     if (clientCtx == NULL)
325         return AFB_EMPTY;
326
327     // Check if the old token is valid
328     if (ctxTokenCheck (clientCtx, request) != AFB_SUCCESS)
329         return AFB_FAIL;
330
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);
334
335     // keep track of time for session timeout and further clean up
336     clientCtx->timeStamp=time(NULL);
337
338     return AFB_SUCCESS;
339 }
340