session: fix bug
[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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363 #if defined(ALLOWS_SESSION_FILES)
364
365 #define AFB_SESSION_JTYPE "AFB_session"
366 #define AFB_SESSION_JLIST "AFB_sessions.hash"
367 #define AFB_SESSION_JINFO "AFB_infos"
368
369
370 #define AFB_CURRENT_SESSION "active-session"  // file link name within sndcard dir
371 #define AFB_DEFAULT_SESSION "current-session" // should be in sync with UI
372
373 // let's return only sessions.hash files
374 static int fileSelect (const struct dirent *entry) {
375    return (strstr (entry->d_name, ".afb") != NULL);
376 }
377
378 static  json_object *checkCardDirExit (AFB_session *session, AFB_request *request ) {
379     int  sessionDir, cardDir;
380
381     // card name should be more than 3 character long !!!!
382     if (strlen (request->prefix) < 3) {
383        return (jsonNewMessage (AFB_FAIL,"Fail invalid plugin=%s", request->prefix));
384     }
385
386     // open session directory
387     sessionDir = open (session->config->sessiondir, O_DIRECTORY);
388     if (sessionDir < 0) {
389           return (jsonNewMessage (AFB_FAIL,"Fail to open directory [%s] error=%s", session->config->sessiondir, strerror(sessionDir)));
390     }
391
392    // create session sndcard directory if it does not exit
393     cardDir = openat (sessionDir, request->prefix,  O_DIRECTORY);
394     if (cardDir < 0) {
395           cardDir  = mkdirat (sessionDir, request->prefix, O_RDWR | S_IRWXU | S_IRGRP);
396           if (cardDir < 0) {
397               return (jsonNewMessage (AFB_FAIL,"Fail to create directory [%s/%s] error=%s", session->config->sessiondir, request->prefix, strerror(cardDir)));
398           }
399     }
400     close (sessionDir);
401     return NULL;
402 }
403
404 // Create a link toward last used sessionname within sndcard directory
405 static void makeSessionLink (const char *cardname, const char *sessionname) {
406    char linkname [256], filename [256];
407    int err;
408    // create a link to keep track of last uploaded sessionname for this card
409    strncpy (filename, sessionname, sizeof(filename));
410    strncat (filename, ".afb", sizeof(filename));
411
412    strncpy (linkname, cardname, sizeof(linkname));
413    strncat (linkname, "/", sizeof(filename));
414    strncat (linkname, AFB_CURRENT_SESSION, sizeof(linkname));
415    strncat (linkname, ".afb", sizeof(filename));
416    unlink (linkname); // remove previous link if any
417    err = symlink (filename, linkname);
418    if (err < 0) fprintf (stderr, "Fail to create link %s->%s error=%s\n", linkname, filename, strerror(errno));
419 }
420
421 // verify we can read/write in session dir
422 AFB_error sessionCheckdir (AFB_session *session) {
423
424    int err;
425
426    // in case session dir would not exist create one
427    if (verbose) fprintf (stderr, "AFB:notice checking session dir [%s]\n", session->config->sessiondir);
428    mkdir(session->config->sessiondir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
429
430    // change for session directory
431    err = chdir(session->config->sessiondir);
432    if (err) {
433      fprintf(stderr,"AFB: Fail to chdir to %s error=%s\n", session->config->sessiondir, strerror(err));
434      return err;
435    }
436
437    // verify we can write session in directory
438    json_object *dummy= json_object_new_object();
439    json_object_object_add (dummy, "checked"  , json_object_new_int (getppid()));
440    err = json_object_to_file ("./AFB-probe.json", dummy);
441    if (err < 0) return err;
442
443    return AFB_SUCCESS;
444 }
445
446 // create a session in current directory
447 json_object *sessionList (AFB_session *session, AFB_request *request) {
448     json_object *sessionsJ, *ajgResponse;
449     struct stat fstat;
450     struct dirent **namelist;
451     int  count, sessionDir;
452
453     // if directory for card's sessions.hash does not exist create it
454     ajgResponse = checkCardDirExit (session, request);
455     if (ajgResponse != NULL) return ajgResponse;
456
457     // open session directory
458     sessionDir = open (session->config->sessiondir, O_DIRECTORY);
459     if (sessionDir < 0) {
460           return (jsonNewMessage (AFB_FAIL,"Fail to open directory [%s] error=%s", session->config->sessiondir, strerror(sessionDir)));
461     }
462
463     count = scandirat (sessionDir, request->prefix, &namelist, fileSelect, alphasort);
464     close (sessionDir);
465
466     if (count < 0) {
467         return (jsonNewMessage (AFB_FAIL,"Fail to scan sessions.hash directory [%s/%s] error=%s", session->config->sessiondir, request->prefix, strerror(sessionDir)));
468     }
469     if (count == 0) return (jsonNewMessage (AFB_EMPTY,"[%s] no session at [%s]", request->prefix, session->config->sessiondir));
470
471     // loop on each session file, retrieve its date and push it into json response object
472     sessionsJ = json_object_new_array();
473     while (count--) {
474          json_object *sessioninfo;
475          char timestamp [64];
476          char *filename;
477
478          // extract file name and last modification date
479          filename = namelist[count]->d_name;
480          printf("%s\n", filename);
481          stat(filename,&fstat);
482          strftime (timestamp, sizeof(timestamp), "%c", localtime (&fstat.st_mtime));
483          filename[strlen(filename)-4] = '\0'; // remove .afb extension from filename
484
485          // create an object by session with last update date
486          sessioninfo = json_object_new_object();
487          json_object_object_add (sessioninfo, "date" , json_object_new_string (timestamp));
488          json_object_object_add (sessioninfo, "session" , json_object_new_string (filename));
489          json_object_array_add (sessionsJ, sessioninfo);
490
491          free(namelist[count]);
492     }
493
494     // free scandir structure
495     free(namelist);
496
497     // everything is OK let's build final response
498     ajgResponse = json_object_new_object();
499     json_object_object_add (ajgResponse, "jtype" , json_object_new_string (AFB_SESSION_JLIST));
500     json_object_object_add (ajgResponse, "status"  , jsonNewStatus(AFB_SUCCESS));
501     json_object_object_add (ajgResponse, "data"    , sessionsJ);
502
503     return (ajgResponse);
504 }
505
506 // Load Json session object from disk
507 json_object *sessionFromDisk (AFB_session *session, AFB_request *request, char *name) {
508     json_object *jsonSession, *jtype, *response;
509     const char *ajglabel;
510     char filename [256];
511     int defsession;
512
513     if (name == NULL) {
514         return  (jsonNewMessage (AFB_FATAL,"session name missing &session=MySessionName"));
515     }
516
517     // check for current session request
518     defsession = (strcmp (name, AFB_DEFAULT_SESSION) ==0);
519
520     // if directory for card's sessions.hash does not exist create it
521     response = checkCardDirExit (session, request);
522     if (response != NULL) return response;
523
524     // add name and file extension to session name
525     strncpy (filename, request->prefix, sizeof(filename));
526     strncat (filename, "/", sizeof(filename));
527     if (defsession) strncat (filename, AFB_CURRENT_SESSION, sizeof(filename)-1);
528     else strncat (filename, name, sizeof(filename)-1);
529     strncat (filename, ".afb", sizeof(filename));
530
531     // just upload json object and return without any further processing
532     jsonSession = json_object_from_file (filename);
533
534     if (jsonSession == NULL)  return (jsonNewMessage (AFB_EMPTY,"File [%s] not found", filename));
535
536     // verify that file is a JSON ALSA session type
537     if (!json_object_object_get_ex (jsonSession, "jtype", &jtype)) {
538         json_object_put   (jsonSession);
539         return  (jsonNewMessage (AFB_EMPTY,"File [%s] 'jtype' descriptor not found", filename));
540     }
541
542     // check type value is AFB_SESSION_JTYPE
543     ajglabel = json_object_get_string (jtype);
544     if (strcmp (AFB_SESSION_JTYPE, ajglabel)) {
545        json_object_put   (jsonSession);
546        return  (jsonNewMessage (AFB_FATAL,"File [%s] jtype=[%s] != [%s]", filename, ajglabel, AFB_SESSION_JTYPE));
547     }
548
549     // create a link to keep track of last uploaded session for this card
550     if (!defsession) makeSessionLink (request->prefix, name);
551
552     return (jsonSession);
553 }
554
555 // push Json session object to disk
556 json_object * sessionToDisk (AFB_session *session, AFB_request *request, char *name, json_object *jsonSession) {
557    char filename [256];
558    time_t rawtime;
559    struct tm * timeinfo;
560    int err, defsession;
561    static json_object *response;
562
563    // we should have a session name
564    if (name == NULL) return (jsonNewMessage (AFB_FATAL,"session name missing &session=MySessionName"));
565
566    // check for current session request
567    defsession = (strcmp (name, AFB_DEFAULT_SESSION) ==0);
568
569    // if directory for card's sessions.hash does not exist create it
570    response = checkCardDirExit (session, request);
571    if (response != NULL) return response;
572
573    // add cardname and file extension to session name
574    strncpy (filename, request->prefix, sizeof(filename));
575    strncat (filename, "/", sizeof(filename));
576    if (defsession) strncat (filename, AFB_CURRENT_SESSION, sizeof(filename)-1);
577    else strncat (filename, name, sizeof(filename)-1);
578    strncat (filename, ".afb", sizeof(filename)-1);
579
580
581    json_object_object_add(jsonSession, "jtype", json_object_new_string (AFB_SESSION_JTYPE));
582
583    // add a timestamp and store session on disk
584    time ( &rawtime );  timeinfo = localtime ( &rawtime );
585    // A copy of the string is made and the memory is managed by the json_object
586    json_object_object_add (jsonSession, "timestamp", json_object_new_string (asctime (timeinfo)));
587
588
589    // do we have extra session info ?
590    if (request->post->type == AFB_POST_JSON) {
591        static json_object *info, *jtype;
592        const char  *ajglabel;
593
594        // extract session info from args
595        info = json_tokener_parse (request->post->data);
596        if (!info) {
597             response = jsonNewMessage (AFB_FATAL,"sndcard=%s session=%s invalid json args=%s", request->prefix, name, request->post);
598             goto OnErrorExit;
599        }
600
601        // info is a valid AFB_info type
602        if (!json_object_object_get_ex (info, "jtype", &jtype)) {
603             response = jsonNewMessage (AFB_EMPTY,"sndcard=%s session=%s No 'AFB_pluginT' args=%s", request->prefix, name, request->post);
604             goto OnErrorExit;
605        }
606
607        // check type value is AFB_INFO_JTYPE
608        ajglabel = json_object_get_string (jtype);
609        if (strcmp (AFB_SESSION_JINFO, ajglabel)) {
610               json_object_put   (info); // release info json object
611               response = jsonNewMessage (AFB_FATAL,"File [%s] jtype=[%s] != [%s] data=%s", filename, ajglabel, AFB_SESSION_JTYPE, request->post);
612               goto OnErrorExit;
613        }
614
615        // this is valid info data for our session
616        json_object_object_add (jsonSession, "info", info);
617    }
618
619    // Finally save session on disk
620    err = json_object_to_file (filename, jsonSession);
621    if (err < 0) {
622         response = jsonNewMessage (AFB_FATAL,"Fail save session = [%s] to disk", filename);
623         goto OnErrorExit;
624    }
625
626
627    // create a link to keep track of last uploaded session for this card
628    if (!defsession) makeSessionLink (request->prefix, name);
629
630    // we're donne let's return status message
631    response = jsonNewMessage (AFB_SUCCESS,"Session= [%s] saved on disk", filename);
632    json_object_put (jsonSession);
633    return (response);
634
635 OnErrorExit:
636    json_object_put (jsonSession);
637    return response;
638 }
639 #endif
640