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