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