Merge origin/master
[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 #define AFB_SESSION_JTYPE "AFB_session"
35 #define AFB_SESSION_JLIST "AFB_sessions.hash"
36 #define AFB_SESSION_JINFO "AFB_infos"
37
38
39 #define AFB_CURRENT_SESSION "active-session"  // file link name within sndcard dir
40 #define AFB_DEFAULT_SESSION "current-session" // should be in sync with UI
41
42 // Session UUID are store in a simple array [for 10 sessions this should be enough]
43 static struct {
44   pthread_mutex_t mutex;          // declare a mutex to protect hash table
45   AFB_clientCtx **store;          // sessions store
46   int count;                      // current number of sessions
47   int max;
48 } sessions;
49
50 // verify we can read/write in session dir
51 PUBLIC AFB_error sessionCheckdir (AFB_session *session) {
52
53    int err;
54
55    // in case session dir would not exist create one
56    if (verbose) fprintf (stderr, "AFB:notice checking session dir [%s]\n", session->config->sessiondir);
57    mkdir(session->config->sessiondir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
58
59    // change for session directory
60    err = chdir(session->config->sessiondir);
61    if (err) {
62      fprintf(stderr,"AFB: Fail to chdir to %s error=%s\n", session->config->sessiondir, strerror(err));
63      return err;
64    }
65
66    // verify we can write session in directory
67    json_object *dummy= json_object_new_object();
68    json_object_object_add (dummy, "checked"  , json_object_new_int (getppid()));
69    err = json_object_to_file ("./AFB-probe.json", dummy);
70    if (err < 0) return err;
71
72    return AFB_SUCCESS;
73 }
74
75 // let's return only sessions.hash files
76 STATIC int fileSelect (const struct dirent *entry) {
77    return (strstr (entry->d_name, ".afb") != NULL);
78 }
79
80 STATIC  json_object *checkCardDirExit (AFB_session *session, AFB_request *request ) {
81     int  sessionDir, cardDir;
82
83     // card name should be more than 3 character long !!!!
84     if (strlen (request->prefix) < 3) {
85        return (jsonNewMessage (AFB_FAIL,"Fail invalid plugin=%s", request->prefix));
86     }
87
88     // open session directory
89     sessionDir = open (session->config->sessiondir, O_DIRECTORY);
90     if (sessionDir < 0) {
91           return (jsonNewMessage (AFB_FAIL,"Fail to open directory [%s] error=%s", session->config->sessiondir, strerror(sessionDir)));
92     }
93
94    // create session sndcard directory if it does not exit
95     cardDir = openat (sessionDir, request->prefix,  O_DIRECTORY);
96     if (cardDir < 0) {
97           cardDir  = mkdirat (sessionDir, request->prefix, O_RDWR | S_IRWXU | S_IRGRP);
98           if (cardDir < 0) {
99               return (jsonNewMessage (AFB_FAIL,"Fail to create directory [%s/%s] error=%s", session->config->sessiondir, request->prefix, strerror(cardDir)));
100           }
101     }
102     close (sessionDir);
103     return NULL;
104 }
105
106 // create a session in current directory
107 PUBLIC json_object *sessionList (AFB_session *session, AFB_request *request) {
108     json_object *sessionsJ, *ajgResponse;
109     struct stat fstat;
110     struct dirent **namelist;
111     int  count, sessionDir;
112
113     // if directory for card's sessions.hash does not exist create it
114     ajgResponse = checkCardDirExit (session, request);
115     if (ajgResponse != NULL) return ajgResponse;
116
117     // open session directory
118     sessionDir = open (session->config->sessiondir, O_DIRECTORY);
119     if (sessionDir < 0) {
120           return (jsonNewMessage (AFB_FAIL,"Fail to open directory [%s] error=%s", session->config->sessiondir, strerror(sessionDir)));
121     }
122
123     count = scandirat (sessionDir, request->prefix, &namelist, fileSelect, alphasort);
124     close (sessionDir);
125
126     if (count < 0) {
127         return (jsonNewMessage (AFB_FAIL,"Fail to scan sessions.hash directory [%s/%s] error=%s", session->config->sessiondir, request->prefix, strerror(sessionDir)));
128     }
129     if (count == 0) return (jsonNewMessage (AFB_EMPTY,"[%s] no session at [%s]", request->prefix, session->config->sessiondir));
130
131     // loop on each session file, retrieve its date and push it into json response object
132     sessionsJ = json_object_new_array();
133     while (count--) {
134          json_object *sessioninfo;
135          char timestamp [64];
136          char *filename;
137
138          // extract file name and last modification date
139          filename = namelist[count]->d_name;
140          printf("%s\n", filename);
141          stat(filename,&fstat);
142          strftime (timestamp, sizeof(timestamp), "%c", localtime (&fstat.st_mtime));
143          filename[strlen(filename)-4] = '\0'; // remove .afb extension from filename
144
145          // create an object by session with last update date
146          sessioninfo = json_object_new_object();
147          json_object_object_add (sessioninfo, "date" , json_object_new_string (timestamp));
148          json_object_object_add (sessioninfo, "session" , json_object_new_string (filename));
149          json_object_array_add (sessionsJ, sessioninfo);
150
151          free(namelist[count]);
152     }
153
154     // free scandir structure
155     free(namelist);
156
157     // everything is OK let's build final response
158     ajgResponse = json_object_new_object();
159     json_object_object_add (ajgResponse, "jtype" , json_object_new_string (AFB_SESSION_JLIST));
160     json_object_object_add (ajgResponse, "status"  , jsonNewStatus(AFB_SUCCESS));
161     json_object_object_add (ajgResponse, "data"    , sessionsJ);
162
163     return (ajgResponse);
164 }
165
166 // Create a link toward last used sessionname within sndcard directory
167 STATIC void makeSessionLink (const char *cardname, const char *sessionname) {
168    char linkname [256], filename [256];
169    int err;
170    // create a link to keep track of last uploaded sessionname for this card
171    strncpy (filename, sessionname, sizeof(filename));
172    strncat (filename, ".afb", sizeof(filename));
173
174    strncpy (linkname, cardname, sizeof(linkname));
175    strncat (linkname, "/", sizeof(filename));
176    strncat (linkname, AFB_CURRENT_SESSION, sizeof(linkname));
177    strncat (linkname, ".afb", sizeof(filename));
178    unlink (linkname); // remove previous link if any
179    err = symlink (filename, linkname);
180    if (err < 0) fprintf (stderr, "Fail to create link %s->%s error=%s\n", linkname, filename, strerror(errno));
181 }
182
183 // Load Json session object from disk
184 PUBLIC json_object *sessionFromDisk (AFB_session *session, AFB_request *request, char *name) {
185     json_object *jsonSession, *jtype, *response;
186     const char *ajglabel;
187     char filename [256];
188     int defsession;
189
190     if (name == NULL) {
191         return  (jsonNewMessage (AFB_FATAL,"session name missing &session=MySessionName"));
192     }
193
194     // check for current session request
195     defsession = (strcmp (name, AFB_DEFAULT_SESSION) ==0);
196
197     // if directory for card's sessions.hash does not exist create it
198     response = checkCardDirExit (session, request);
199     if (response != NULL) return response;
200
201     // add name and file extension to session name
202     strncpy (filename, request->prefix, sizeof(filename));
203     strncat (filename, "/", sizeof(filename));
204     if (defsession) strncat (filename, AFB_CURRENT_SESSION, sizeof(filename)-1);
205     else strncat (filename, name, sizeof(filename)-1);
206     strncat (filename, ".afb", sizeof(filename));
207
208     // just upload json object and return without any further processing
209     jsonSession = json_object_from_file (filename);
210
211     if (jsonSession == NULL)  return (jsonNewMessage (AFB_EMPTY,"File [%s] not found", filename));
212
213     // verify that file is a JSON ALSA session type
214     if (!json_object_object_get_ex (jsonSession, "jtype", &jtype)) {
215         json_object_put   (jsonSession);
216         return  (jsonNewMessage (AFB_EMPTY,"File [%s] 'jtype' descriptor not found", filename));
217     }
218
219     // check type value is AFB_SESSION_JTYPE
220     ajglabel = json_object_get_string (jtype);
221     if (strcmp (AFB_SESSION_JTYPE, ajglabel)) {
222        json_object_put   (jsonSession);
223        return  (jsonNewMessage (AFB_FATAL,"File [%s] jtype=[%s] != [%s]", filename, ajglabel, AFB_SESSION_JTYPE));
224     }
225
226     // create a link to keep track of last uploaded session for this card
227     if (!defsession) makeSessionLink (request->prefix, name);
228
229     return (jsonSession);
230 }
231
232 // push Json session object to disk
233 PUBLIC json_object * sessionToDisk (AFB_session *session, AFB_request *request, char *name, json_object *jsonSession) {
234    char filename [256];
235    time_t rawtime;
236    struct tm * timeinfo;
237    int err, defsession;
238    static json_object *response;
239
240    // we should have a session name
241    if (name == NULL) return (jsonNewMessage (AFB_FATAL,"session name missing &session=MySessionName"));
242
243    // check for current session request
244    defsession = (strcmp (name, AFB_DEFAULT_SESSION) ==0);
245
246    // if directory for card's sessions.hash does not exist create it
247    response = checkCardDirExit (session, request);
248    if (response != NULL) return response;
249
250    // add cardname and file extension to session name
251    strncpy (filename, request->prefix, sizeof(filename));
252    strncat (filename, "/", sizeof(filename));
253    if (defsession) strncat (filename, AFB_CURRENT_SESSION, sizeof(filename)-1);
254    else strncat (filename, name, sizeof(filename)-1);
255    strncat (filename, ".afb", sizeof(filename)-1);
256
257
258    json_object_object_add(jsonSession, "jtype", json_object_new_string (AFB_SESSION_JTYPE));
259
260    // add a timestamp and store session on disk
261    time ( &rawtime );  timeinfo = localtime ( &rawtime );
262    // A copy of the string is made and the memory is managed by the json_object
263    json_object_object_add (jsonSession, "timestamp", json_object_new_string (asctime (timeinfo)));
264
265
266    // do we have extra session info ?
267    if (request->post->type == AFB_POST_JSON) {
268        static json_object *info, *jtype;
269        const char  *ajglabel;
270
271        // extract session info from args
272        info = json_tokener_parse (request->post->data);
273        if (!info) {
274             response = jsonNewMessage (AFB_FATAL,"sndcard=%s session=%s invalid json args=%s", request->prefix, name, request->post);
275             goto OnErrorExit;
276        }
277
278        // info is a valid AFB_info type
279        if (!json_object_object_get_ex (info, "jtype", &jtype)) {
280             response = jsonNewMessage (AFB_EMPTY,"sndcard=%s session=%s No 'AFB_pluginT' args=%s", request->prefix, name, request->post);
281             goto OnErrorExit;
282        }
283
284        // check type value is AFB_INFO_JTYPE
285        ajglabel = json_object_get_string (jtype);
286        if (strcmp (AFB_SESSION_JINFO, ajglabel)) {
287               json_object_put   (info); // release info json object
288               response = jsonNewMessage (AFB_FATAL,"File [%s] jtype=[%s] != [%s] data=%s", filename, ajglabel, AFB_SESSION_JTYPE, request->post);
289               goto OnErrorExit;
290        }
291
292        // this is valid info data for our session
293        json_object_object_add (jsonSession, "info", info);
294    }
295
296    // Finally save session on disk
297    err = json_object_to_file (filename, jsonSession);
298    if (err < 0) {
299         response = jsonNewMessage (AFB_FATAL,"Fail save session = [%s] to disk", filename);
300         goto OnErrorExit;
301    }
302
303
304    // create a link to keep track of last uploaded session for this card
305    if (!defsession) makeSessionLink (request->prefix, name);
306
307    // we're donne let's return status message
308    response = jsonNewMessage (AFB_SUCCESS,"Session= [%s] saved on disk", filename);
309    json_object_put (jsonSession);
310    return (response);
311
312 OnErrorExit:
313    json_object_put (jsonSession);
314    return response;
315 }
316
317
318 // Free context [XXXX Should be protected again memory abort XXXX]
319 STATIC void ctxUuidFreeCB (AFB_clientCtx *client) {
320
321     AFB_plugin **plugins = client->plugins;
322     AFB_freeCtxCB freeCtxCB;
323     int idx;
324     
325     // If application add a handle let's free it now
326     if (client->contexts != NULL) {
327      
328         // Free client handle with a standard Free function, with app callback or ignore it
329         for (idx=0; client->plugins[idx] != NULL; idx ++) {
330             if (client->contexts[idx] != NULL) {               
331                 freeCtxCB = client->plugins[idx]->freeCtxCB;
332                 if (freeCtxCB == NULL) free (client->contexts[idx]); 
333                 else if (freeCtxCB != (void*)-1) freeCtxCB(client->contexts[idx], plugins[idx]->handle, client->uuid); 
334             }
335         }
336     }
337 }
338
339 // Create a new store in RAM, not that is too small it will be automatically extended
340 PUBLIC void ctxStoreInit (int nbSession) {
341    int res;
342    
343    // let's create as store as hashtable does not have any
344    sessions.store = calloc (nbSession+1, sizeof(AFB_clientCtx));
345    sessions.max=nbSession;
346 }
347
348 STATIC AFB_clientCtx *ctxStoreSearch (const char* uuid) {
349     int  idx;
350     AFB_clientCtx *client;
351     
352     if (uuid == NULL) return NULL;
353     
354     pthread_mutex_lock(&sessions.mutex);
355     
356     for (idx=0; idx < sessions.max; idx++) {
357         if (sessions.store[idx] && (0 == strcmp (uuid, sessions.store[idx]->uuid))) break;
358     }
359     
360     if (idx == sessions.max) client=NULL;
361     else client= sessions.store[idx];
362     pthread_mutex_unlock(&sessions.mutex);
363     
364     return (client);
365 }
366
367
368 STATIC AFB_error ctxStoreDel (AFB_clientCtx *client) {
369     int idx;
370     int status;
371     if (client == NULL) return (AFB_FAIL);
372     
373     pthread_mutex_lock(&sessions.mutex);
374     
375     for (idx=0; idx < sessions.max; idx++) {
376         if (sessions.store[idx] && (0 == strcmp (client->uuid, sessions.store[idx]->uuid))) break;
377     }
378     
379     if (idx == sessions.max) status=AFB_FAIL;
380     else {
381         sessions.count --;
382         ctxUuidFreeCB (sessions.store[idx]);
383         sessions.store[idx]=NULL;
384         status=AFB_SUCCESS;
385     }
386     
387     pthread_mutex_unlock(&sessions.mutex);   
388     return (status);
389 }
390
391 STATIC AFB_error ctxStoreAdd (AFB_clientCtx *client) {
392     int idx;
393     int status;
394     if (client == NULL) return (AFB_FAIL);
395
396     //fprintf (stderr, "ctxStoreAdd request uuid=%s count=%d\n", client->uuid, sessions.count);
397     
398     pthread_mutex_lock(&sessions.mutex);
399     
400     for (idx=0; idx < sessions.max; idx++) {
401         if (NULL == sessions.store[idx]) break;
402     }
403     
404     if (idx == sessions.max) status=AFB_FAIL;
405     else {
406         status=AFB_SUCCESS;
407         sessions.count ++;
408         sessions.store[idx]= client;
409     }
410     
411     pthread_mutex_unlock(&sessions.mutex);   
412     return (status);
413 }
414
415 // Check if context timeout or not
416 STATIC int ctxStoreToOld (AFB_clientCtx *ctx, int timeout) {
417     int res;
418     time_t now =  time(NULL);
419     res = ((ctx->timeStamp + timeout) <= now);
420     return (res);    
421 }
422
423 // Loop on every entry and remove old context sessions.hash
424 PUBLIC int ctxStoreGarbage (const int timeout) {
425     AFB_clientCtx *ctx;
426     long idx;
427     
428     // Loop on Sessions Table and remove anything that is older than timeout
429     for (idx=0; idx < sessions.max; idx++) {
430         ctx=sessions.store[idx];
431         if ((ctx != NULL) && (ctxStoreToOld(ctx, timeout))) {
432             ctxStoreDel (ctx);
433         }
434     }
435 }
436
437 // This function will return exiting client context or newly created client context
438 PUBLIC AFB_clientCtx *ctxClientGet (AFB_request *request, int idx) {
439   AFB_clientCtx *clientCtx=NULL;
440   const char *uuid;
441   uuid_t newuuid;
442   int ret;
443   
444     if (request->config->token == NULL) return NULL;
445
446     // Check if client as a context or not inside the URL
447     uuid  = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, "uuid");
448        
449     // if UUID in query we're restfull with no cookies otherwise check for cookie
450     if (uuid != NULL) request->restfull = TRUE;
451     else {
452         request->restfull = FALSE;
453         uuid = MHD_lookup_connection_value (request->connection, MHD_COOKIE_KIND, COOKIE_NAME);  
454     };
455     
456     // Warning when no cookie defined MHD_lookup_connection_value may return something !!!
457     if ((uuid != NULL) && (strnlen (uuid, 10) >= 10))   {
458         int search;
459         // search if client context exist and it not timeout let's use it
460         clientCtx = ctxStoreSearch (uuid);
461
462         if (clientCtx) {
463             if (ctxStoreToOld (clientCtx, request->config->cntxTimeout)) {
464                  // this session is too old let's delete it
465                 ctxStoreDel (clientCtx);
466                 clientCtx=NULL;
467             } else {
468                 request->context=clientCtx->contexts[idx];
469                 request->handle  = clientCtx->plugins[idx]->handle;
470                 request->uuid= uuid;
471                 return (clientCtx);            
472             }
473         }
474     }
475    
476     // we have no session let's create one otherwise let's clean any exiting values
477     if (clientCtx == NULL) {        
478         clientCtx = calloc(1, sizeof(AFB_clientCtx)); // init NULL clientContext
479         clientCtx->contexts = calloc (1, request->config->pluginCount * (sizeof (void*)));        
480         clientCtx->plugins  = request->plugins;  
481     }
482     
483     uuid_generate(newuuid);         // create a new UUID
484     uuid_unparse_lower(newuuid, clientCtx->uuid);
485     
486     // if table is full at 50% let's clean it up
487     if(sessions.count > (sessions.max / 2)) ctxStoreGarbage(request->config->cntxTimeout);
488     
489     // finally add uuid into hashtable
490     if (AFB_SUCCESS != ctxStoreAdd (clientCtx)) {
491         free (clientCtx);
492         return(NULL);
493     }
494     
495     // if (verbose) fprintf (stderr, "ctxClientGet New uuid=[%s] token=[%s] timestamp=%d\n", clientCtx->uuid, clientCtx->token, clientCtx->timeStamp);      
496     request->context = clientCtx->contexts[idx];
497     request->handle  = clientCtx->plugins[idx]->handle;
498     request->uuid=clientCtx->uuid;
499     return(clientCtx);
500 }
501
502 // Sample Generic Ping Debug API
503 PUBLIC AFB_error ctxTokenCheck (AFB_clientCtx *clientCtx, AFB_request *request) {
504     const char *token;
505     
506     if (clientCtx->contexts == NULL) return AFB_EMPTY;
507     
508     // this time have to extract token from query list
509     token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, "token");
510     
511     // if not token is providing we refuse the exchange
512     if ((token == NULL) || (clientCtx->token == NULL)) return (AFB_FALSE);
513     
514     // compare current token with previous one
515     if ((0 == strcmp (token, clientCtx->token)) && (!ctxStoreToOld (clientCtx, request->config->cntxTimeout))) {
516        return (AFB_SUCCESS);
517     }
518     
519     // Token is not valid let move level of assurance to zero and free attached client handle
520     return (AFB_FAIL);
521 }
522
523 // Free Client Session Context
524 PUBLIC AFB_error ctxTokenReset (AFB_clientCtx *clientCtx, AFB_request *request) {
525     int ret;
526
527     if (clientCtx == NULL) return AFB_EMPTY;
528     //if (verbose) fprintf (stderr, "ctxClientReset New uuid=[%s] token=[%s] timestamp=%d\n", clientCtx->uuid, clientCtx->token, clientCtx->timeStamp);      
529     
530     // Search for an existing client with the same UUID
531     clientCtx = ctxStoreSearch (clientCtx->uuid);
532     if (clientCtx == NULL) return AFB_FALSE;
533
534     // Remove client from table
535     ctxStoreDel (clientCtx);    
536     
537     return (AFB_SUCCESS);
538 }
539
540 // generate a new token
541 PUBLIC AFB_error ctxTokenCreate (AFB_clientCtx *clientCtx, AFB_request *request) {
542     int oldTnkValid;
543     const char *ornew;
544     uuid_t newuuid;
545     const char *token;
546
547     if (clientCtx == NULL) return AFB_EMPTY;
548
549     // if config->token!="" then verify that we have the right initial share secret   
550     if (request->config->token[0] != '\0') {
551         
552         // check for initial token secret and return if not presented
553         token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, "token");
554         if (token == NULL) return AFB_UNAUTH;
555         
556         // verify that it fits with initial tokens fit
557         if (strcmp(request->config->token, token)) return AFB_UNAUTH;       
558     }
559     
560     // create a UUID as token value
561     uuid_generate(newuuid); 
562     uuid_unparse_lower(newuuid, clientCtx->token);
563     
564     // keep track of time for session timeout and further clean up
565     clientCtx->timeStamp=time(NULL);
566     
567     // Token is also store in context but it might be convenient for plugin to access it directly
568     return (AFB_SUCCESS);
569 }
570
571
572 // generate a new token and update client context
573 PUBLIC AFB_error ctxTokenRefresh (AFB_clientCtx *clientCtx, AFB_request *request) {
574     int oldTnkValid;
575     const char *oldornew;
576     uuid_t newuuid;
577
578     if (clientCtx == NULL) return AFB_EMPTY;
579     
580     // Check if the old token is valid
581     if (ctxTokenCheck (clientCtx, request) != AFB_SUCCESS) return (AFB_FAIL);
582         
583     // Old token was valid let's regenerate a new one    
584     uuid_generate(newuuid);         // create a new UUID
585     uuid_unparse_lower(newuuid, clientCtx->token);
586     
587     // keep track of time for session timeout and further clean up
588     clientCtx->timeStamp=time(NULL);
589     
590     return (AFB_SUCCESS);    
591     
592 }
593