3ebd9826b2f024d91ecbdc3a43a2bb33dc5bd5c5
[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 #include "afb-apis.h"
34 #include "session.h"
35
36 // Session UUID are store in a simple array [for 10 sessions this should be enough]
37 static struct {
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
41   int max;
42   int timeout;
43   int apicount;
44 } sessions;
45
46 static const char key_uuid[] = "uuid";
47 static const char key_token[] = "token";
48
49 // Free context [XXXX Should be protected again memory abort XXXX]
50 static void ctxUuidFreeCB (AFB_clientCtx *client)
51 {
52     int idx;
53
54     // If application add a handle let's free it now
55     if (client->contexts != NULL) {
56
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]);
61             }
62         }
63     }
64 }
65
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)
68 {
69
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;
75 }
76
77 static AFB_clientCtx *ctxStoreSearch (const char* uuid)
78 {
79     int  idx;
80     AFB_clientCtx *client;
81
82     if (uuid == NULL)
83         return NULL;
84
85     pthread_mutex_lock(&sessions.mutex);
86
87     for (idx=0; idx < sessions.max; idx++) {
88         if (sessions.store[idx] && (0 == strcmp (uuid, sessions.store[idx]->uuid))) break;
89     }
90
91     if (idx == sessions.max) client=NULL;
92     else client= sessions.store[idx];
93     pthread_mutex_unlock(&sessions.mutex);
94
95     return client;
96 }
97
98 static AFB_error ctxStoreDel (AFB_clientCtx *client)
99 {
100     int idx;
101     int status;
102
103     if (client == NULL)
104         return AFB_FAIL;
105
106     pthread_mutex_lock(&sessions.mutex);
107
108     for (idx=0; idx < sessions.max; idx++) {
109         if (sessions.store[idx] && (0 == strcmp (client->uuid, sessions.store[idx]->uuid))) break;
110     }
111
112     if (idx == sessions.max)
113         status = AFB_FAIL;
114     else {
115         sessions.count--;
116         ctxUuidFreeCB (sessions.store[idx]);
117         sessions.store[idx]=NULL;
118         status = AFB_SUCCESS;
119     }
120
121     pthread_mutex_unlock(&sessions.mutex);
122     return status;
123 }
124
125 static AFB_error ctxStoreAdd (AFB_clientCtx *client)
126 {
127     int idx;
128     int status;
129     if (client == NULL)
130         return AFB_FAIL;
131
132     //fprintf (stderr, "ctxStoreAdd request uuid=%s count=%d\n", client->uuid, sessions.count);
133
134     pthread_mutex_lock(&sessions.mutex);
135
136     for (idx=0; idx < sessions.max; idx++) {
137         if (NULL == sessions.store[idx]) break;
138     }
139
140     if (idx == sessions.max) status=AFB_FAIL;
141     else {
142         status=AFB_SUCCESS;
143         sessions.count ++;
144         sessions.store[idx]= client;
145     }
146
147     pthread_mutex_unlock(&sessions.mutex);
148     return status;
149 }
150
151 // Check if context timeout or not
152 static int ctxStoreTooOld (AFB_clientCtx *ctx, int timeout)
153 {
154     int res;
155     time_t now =  time(NULL);
156     res = (ctx->timeStamp + timeout) <= now;
157     return res;
158 }
159
160 // Loop on every entry and remove old context sessions.hash
161 void ctxStoreGarbage (const int timeout)
162 {
163     AFB_clientCtx *ctx;
164     long idx;
165
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))) {
170             ctxStoreDel (ctx);
171         }
172     }
173 }
174
175 // This function will return exiting client context or newly created client context
176 AFB_clientCtx *ctxClientGet (AFB_request *request)
177 {
178   AFB_clientCtx *clientCtx=NULL;
179   const char *uuid;
180   uuid_t newuuid;
181
182     if (request->config->token == NULL) return NULL;
183
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);
186
187     // if UUID in query we're restfull with no cookies otherwise check for cookie
188     if (uuid != NULL)
189         request->restfull = TRUE;
190     else {
191         char cookie[64];
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);
195     };
196
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);
201
202         if (clientCtx) {
203             if (ctxStoreTooOld (clientCtx, sessions.timeout)) {
204                  // this session is too old let's delete it
205                 ctxStoreDel (clientCtx);
206                 clientCtx = NULL;
207             } else {
208                 return clientCtx;
209             }
210         }
211     }
212
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*));
217     }
218
219     uuid_generate(newuuid);         // create a new UUID
220     uuid_unparse_lower(newuuid, clientCtx->uuid);
221
222     // if table is full at 50% let's clean it up
223     if(sessions.count > (sessions.max / 2)) ctxStoreGarbage(sessions.timeout);
224
225     // finally add uuid into hashtable
226     if (AFB_SUCCESS != ctxStoreAdd (clientCtx)) {
227         free (clientCtx);
228         return NULL;
229     }
230     return clientCtx;
231 }
232
233 // Sample Generic Ping Debug API
234 AFB_error ctxTokenCheck (AFB_clientCtx *clientCtx, AFB_request *request)
235 {
236     const char *token;
237
238     if (clientCtx->contexts == NULL)
239         return AFB_EMPTY;
240
241     // this time have to extract token from query list
242     token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_token);
243
244     // if not token is providing we refuse the exchange
245     if ((token == NULL) || (clientCtx->token == NULL))
246         return AFB_FALSE;
247
248     // compare current token with previous one
249     if ((0 == strcmp (token, clientCtx->token)) && (!ctxStoreTooOld (clientCtx, sessions.timeout))) {
250        return AFB_SUCCESS;
251     }
252
253     // Token is not valid let move level of assurance to zero and free attached client handle
254     return AFB_FAIL;
255 }
256
257 // Free Client Session Context
258 AFB_error ctxTokenReset (AFB_clientCtx *clientCtx, AFB_request *request)
259 {
260     if (clientCtx == NULL)
261        return AFB_EMPTY;
262     //if (verbose) fprintf (stderr, "ctxClientReset New uuid=[%s] token=[%s] timestamp=%d\n", clientCtx->uuid, clientCtx->token, clientCtx->timeStamp);
263
264     // Search for an existing client with the same UUID
265     clientCtx = ctxStoreSearch (clientCtx->uuid);
266     if (clientCtx == NULL)
267        return AFB_FALSE;
268
269     // Remove client from table
270     ctxStoreDel (clientCtx);
271
272     return AFB_SUCCESS;
273 }
274
275 // generate a new token
276 AFB_error ctxTokenCreate (AFB_clientCtx *clientCtx, AFB_request *request)
277 {
278     uuid_t newuuid;
279     const char *token;
280
281     if (clientCtx == NULL)
282        return AFB_EMPTY;
283
284     // if config->token!="" then verify that we have the right initial share secret
285     if (request->config->token[0] != '\0') {
286
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);
289         if (token == NULL)
290            return AFB_UNAUTH;
291
292         // verify that it fits with initial tokens fit
293         if (strcmp(request->config->token, token))
294            return AFB_UNAUTH;
295     }
296
297     // create a UUID as token value
298     uuid_generate(newuuid);
299     uuid_unparse_lower(newuuid, clientCtx->token);
300
301     // keep track of time for session timeout and further clean up
302     clientCtx->timeStamp=time(NULL);
303
304     // Token is also store in context but it might be convenient for plugin to access it directly
305     return AFB_SUCCESS;
306 }
307
308
309 // generate a new token and update client context
310 AFB_error ctxTokenRefresh (AFB_clientCtx *clientCtx, AFB_request *request)
311 {
312     uuid_t newuuid;
313
314     if (clientCtx == NULL)
315         return AFB_EMPTY;
316
317     // Check if the old token is valid
318     if (ctxTokenCheck (clientCtx, request) != AFB_SUCCESS)
319         return AFB_FAIL;
320
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);
324
325     // keep track of time for session timeout and further clean up
326     clientCtx->timeStamp=time(NULL);
327
328     return AFB_SUCCESS;
329 }
330