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