Add warning detection and improve
[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    
342    // let's create as store as hashtable does not have any
343    sessions.store = calloc (1 + (unsigned)nbSession, sizeof(AFB_clientCtx));
344    sessions.max=nbSession;
345 }
346
347 STATIC AFB_clientCtx *ctxStoreSearch (const char* uuid) {
348     int  idx;
349     AFB_clientCtx *client;
350     
351     if (uuid == NULL) return NULL;
352     
353     pthread_mutex_lock(&sessions.mutex);
354     
355     for (idx=0; idx < sessions.max; idx++) {
356         if (sessions.store[idx] && (0 == strcmp (uuid, sessions.store[idx]->uuid))) break;
357     }
358     
359     if (idx == sessions.max) client=NULL;
360     else client= sessions.store[idx];
361     pthread_mutex_unlock(&sessions.mutex);
362     
363     return (client);
364 }
365
366
367 STATIC AFB_error ctxStoreDel (AFB_clientCtx *client) {
368     int idx;
369     int status;
370     if (client == NULL) return (AFB_FAIL);
371     
372     pthread_mutex_lock(&sessions.mutex);
373     
374     for (idx=0; idx < sessions.max; idx++) {
375         if (sessions.store[idx] && (0 == strcmp (client->uuid, sessions.store[idx]->uuid))) break;
376     }
377     
378     if (idx == sessions.max) status=AFB_FAIL;
379     else {
380         sessions.count --;
381         ctxUuidFreeCB (sessions.store[idx]);
382         sessions.store[idx]=NULL;
383         status=AFB_SUCCESS;
384     }
385     
386     pthread_mutex_unlock(&sessions.mutex);   
387     return (status);
388 }
389
390 STATIC AFB_error ctxStoreAdd (AFB_clientCtx *client) {
391     int idx;
392     int status;
393     if (client == NULL) return (AFB_FAIL);
394
395     //fprintf (stderr, "ctxStoreAdd request uuid=%s count=%d\n", client->uuid, sessions.count);
396     
397     pthread_mutex_lock(&sessions.mutex);
398     
399     for (idx=0; idx < sessions.max; idx++) {
400         if (NULL == sessions.store[idx]) break;
401     }
402     
403     if (idx == sessions.max) status=AFB_FAIL;
404     else {
405         status=AFB_SUCCESS;
406         sessions.count ++;
407         sessions.store[idx]= client;
408     }
409     
410     pthread_mutex_unlock(&sessions.mutex);   
411     return (status);
412 }
413
414 // Check if context timeout or not
415 STATIC int ctxStoreToOld (AFB_clientCtx *ctx, int timeout) {
416     int res;
417     time_t now =  time(NULL);
418     res = ((ctx->timeStamp + timeout) <= now);
419     return (res);    
420 }
421
422 // Loop on every entry and remove old context sessions.hash
423 PUBLIC void ctxStoreGarbage (const int timeout) {
424     AFB_clientCtx *ctx;
425     long idx;
426     
427     // Loop on Sessions Table and remove anything that is older than timeout
428     for (idx=0; idx < sessions.max; idx++) {
429         ctx=sessions.store[idx];
430         if ((ctx != NULL) && (ctxStoreToOld(ctx, timeout))) {
431             ctxStoreDel (ctx);
432         }
433     }
434 }
435
436 // This function will return exiting client context or newly created client context
437 PUBLIC AFB_clientCtx *ctxClientGet (AFB_request *request, int idx) {
438   AFB_clientCtx *clientCtx=NULL;
439   const char *uuid;
440   uuid_t newuuid;
441   
442     if (request->config->token == NULL) return NULL;
443
444     // Check if client as a context or not inside the URL
445     uuid  = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, "uuid");
446        
447     // if UUID in query we're restfull with no cookies otherwise check for cookie
448     if (uuid != NULL) request->restfull = TRUE;
449     else {
450         char cookie[64];
451         request->restfull = FALSE;
452         snprintf(cookie, sizeof cookie, "%s-%d", COOKIE_NAME, request->config->httpdPort);
453         uuid = MHD_lookup_connection_value (request->connection, MHD_COOKIE_KIND, cookie);  
454     };
455     
456     // Warning when no cookie defined MHD_lookup_connection_value may return something !!!
457     if ((uuid != NULL) && (strnlen (uuid, 10) >= 10))   {
458         // search if client context exist and it not timeout let's use it
459         clientCtx = ctxStoreSearch (uuid);
460
461         if (clientCtx) {
462             if (ctxStoreToOld (clientCtx, request->config->cntxTimeout)) {
463                  // this session is too old let's delete it
464                 ctxStoreDel (clientCtx);
465                 clientCtx=NULL;
466             } else {
467                 request->context=clientCtx->contexts[idx];
468                 request->handle  = clientCtx->plugins[idx]->handle;
469                 request->uuid= uuid;
470                 return (clientCtx);            
471             }
472         }
473     }
474    
475     // we have no session let's create one otherwise let's clean any exiting values
476     if (clientCtx == NULL) {        
477         clientCtx = calloc(1, sizeof(AFB_clientCtx)); // init NULL clientContext
478         clientCtx->contexts = calloc (1, (unsigned)request->config->pluginCount * (sizeof (void*)));
479         clientCtx->plugins  = request->plugins;  
480     }
481     
482     uuid_generate(newuuid);         // create a new UUID
483     uuid_unparse_lower(newuuid, clientCtx->uuid);
484     
485     // if table is full at 50% let's clean it up
486     if(sessions.count > (sessions.max / 2)) ctxStoreGarbage(request->config->cntxTimeout);
487     
488     // finally add uuid into hashtable
489     if (AFB_SUCCESS != ctxStoreAdd (clientCtx)) {
490         free (clientCtx);
491         return(NULL);
492     }
493     
494     // if (verbose) fprintf (stderr, "ctxClientGet New uuid=[%s] token=[%s] timestamp=%d\n", clientCtx->uuid, clientCtx->token, clientCtx->timeStamp);      
495     request->context = clientCtx->contexts[idx];
496     request->handle  = clientCtx->plugins[idx]->handle;
497     request->uuid=clientCtx->uuid;
498     return(clientCtx);
499 }
500
501 // Sample Generic Ping Debug API
502 PUBLIC AFB_error ctxTokenCheck (AFB_clientCtx *clientCtx, AFB_request *request) {
503     const char *token;
504     
505     if (clientCtx->contexts == NULL) return AFB_EMPTY;
506     
507     // this time have to extract token from query list
508     token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, "token");
509     
510     // if not token is providing we refuse the exchange
511     if ((token == NULL) || (clientCtx->token == NULL)) return (AFB_FALSE);
512     
513     // compare current token with previous one
514     if ((0 == strcmp (token, clientCtx->token)) && (!ctxStoreToOld (clientCtx, request->config->cntxTimeout))) {
515        return (AFB_SUCCESS);
516     }
517     
518     // Token is not valid let move level of assurance to zero and free attached client handle
519     return (AFB_FAIL);
520 }
521
522 // Free Client Session Context
523 PUBLIC AFB_error ctxTokenReset (AFB_clientCtx *clientCtx, AFB_request *request) {
524
525     if (clientCtx == NULL) return AFB_EMPTY;
526     //if (verbose) fprintf (stderr, "ctxClientReset New uuid=[%s] token=[%s] timestamp=%d\n", clientCtx->uuid, clientCtx->token, clientCtx->timeStamp);      
527     
528     // Search for an existing client with the same UUID
529     clientCtx = ctxStoreSearch (clientCtx->uuid);
530     if (clientCtx == NULL) return AFB_FALSE;
531
532     // Remove client from table
533     ctxStoreDel (clientCtx);    
534     
535     return (AFB_SUCCESS);
536 }
537
538 // generate a new token
539 PUBLIC AFB_error ctxTokenCreate (AFB_clientCtx *clientCtx, AFB_request *request) {
540     uuid_t newuuid;
541     const char *token;
542
543     if (clientCtx == NULL) return AFB_EMPTY;
544
545     // if config->token!="" then verify that we have the right initial share secret   
546     if (request->config->token[0] != '\0') {
547         
548         // check for initial token secret and return if not presented
549         token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, "token");
550         if (token == NULL) return AFB_UNAUTH;
551         
552         // verify that it fits with initial tokens fit
553         if (strcmp(request->config->token, token)) return AFB_UNAUTH;       
554     }
555     
556     // create a UUID as token value
557     uuid_generate(newuuid); 
558     uuid_unparse_lower(newuuid, clientCtx->token);
559     
560     // keep track of time for session timeout and further clean up
561     clientCtx->timeStamp=time(NULL);
562     
563     // Token is also store in context but it might be convenient for plugin to access it directly
564     return (AFB_SUCCESS);
565 }
566
567
568 // generate a new token and update client context
569 PUBLIC AFB_error ctxTokenRefresh (AFB_clientCtx *clientCtx, AFB_request *request) {
570     uuid_t newuuid;
571
572     if (clientCtx == NULL) return AFB_EMPTY;
573     
574     // Check if the old token is valid
575     if (ctxTokenCheck (clientCtx, request) != AFB_SUCCESS) return (AFB_FAIL);
576         
577     // Old token was valid let's regenerate a new one    
578     uuid_generate(newuuid);         // create a new UUID
579     uuid_unparse_lower(newuuid, clientCtx->token);
580     
581     // keep track of time for session timeout and further clean up
582     clientCtx->timeStamp=time(NULL);
583     
584     return (AFB_SUCCESS);    
585     
586 }
587