2 * Copyright (C) 2015 "IoT.bzh"
3 * Author "Fulup Ar Foll"
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.
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.
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/>.
19 * http://stackoverflow.com/questions/25971505/how-to-delete-element-from-hsearch
24 #include "local-def.h"
29 #include <sys/types.h>
34 // Session UUID are store in a simple array [for 10 sessions this should be enough]
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
42 #if defined(ALLOWS_SESSION_FILES)
44 #define AFB_SESSION_JTYPE "AFB_session"
45 #define AFB_SESSION_JLIST "AFB_sessions.hash"
46 #define AFB_SESSION_JINFO "AFB_infos"
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
52 // let's return only sessions.hash files
53 STATIC int fileSelect (const struct dirent *entry) {
54 return (strstr (entry->d_name, ".afb") != NULL);
57 STATIC json_object *checkCardDirExit (AFB_session *session, AFB_request *request ) {
58 int sessionDir, cardDir;
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));
65 // open session directory
66 sessionDir = open (session->config->sessiondir, O_DIRECTORY);
68 return (jsonNewMessage (AFB_FAIL,"Fail to open directory [%s] error=%s", session->config->sessiondir, strerror(sessionDir)));
71 // create session sndcard directory if it does not exit
72 cardDir = openat (sessionDir, request->prefix, O_DIRECTORY);
74 cardDir = mkdirat (sessionDir, request->prefix, O_RDWR | S_IRWXU | S_IRGRP);
76 return (jsonNewMessage (AFB_FAIL,"Fail to create directory [%s/%s] error=%s", session->config->sessiondir, request->prefix, strerror(cardDir)));
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];
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));
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));
100 // verify we can read/write in session dir
101 PUBLIC AFB_error sessionCheckdir (AFB_session *session) {
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);
109 // change for session directory
110 err = chdir(session->config->sessiondir);
112 fprintf(stderr,"AFB: Fail to chdir to %s error=%s\n", session->config->sessiondir, strerror(err));
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;
125 // create a session in current directory
126 PUBLIC json_object *sessionList (AFB_session *session, AFB_request *request) {
127 json_object *sessionsJ, *ajgResponse;
129 struct dirent **namelist;
130 int count, sessionDir;
132 // if directory for card's sessions.hash does not exist create it
133 ajgResponse = checkCardDirExit (session, request);
134 if (ajgResponse != NULL) return ajgResponse;
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)));
142 count = scandirat (sessionDir, request->prefix, &namelist, fileSelect, alphasort);
146 return (jsonNewMessage (AFB_FAIL,"Fail to scan sessions.hash directory [%s/%s] error=%s", session->config->sessiondir, request->prefix, strerror(sessionDir)));
148 if (count == 0) return (jsonNewMessage (AFB_EMPTY,"[%s] no session at [%s]", request->prefix, session->config->sessiondir));
150 // loop on each session file, retrieve its date and push it into json response object
151 sessionsJ = json_object_new_array();
153 json_object *sessioninfo;
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
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);
170 free(namelist[count]);
173 // free scandir structure
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);
182 return (ajgResponse);
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;
193 return (jsonNewMessage (AFB_FATAL,"session name missing &session=MySessionName"));
196 // check for current session request
197 defsession = (strcmp (name, AFB_DEFAULT_SESSION) ==0);
199 // if directory for card's sessions.hash does not exist create it
200 response = checkCardDirExit (session, request);
201 if (response != NULL) return response;
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));
210 // just upload json object and return without any further processing
211 jsonSession = json_object_from_file (filename);
213 if (jsonSession == NULL) return (jsonNewMessage (AFB_EMPTY,"File [%s] not found", filename));
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));
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));
228 // create a link to keep track of last uploaded session for this card
229 if (!defsession) makeSessionLink (request->prefix, name);
231 return (jsonSession);
234 // push Json session object to disk
235 PUBLIC json_object * sessionToDisk (AFB_session *session, AFB_request *request, char *name, json_object *jsonSession) {
238 struct tm * timeinfo;
240 static json_object *response;
242 // we should have a session name
243 if (name == NULL) return (jsonNewMessage (AFB_FATAL,"session name missing &session=MySessionName"));
245 // check for current session request
246 defsession = (strcmp (name, AFB_DEFAULT_SESSION) ==0);
248 // if directory for card's sessions.hash does not exist create it
249 response = checkCardDirExit (session, request);
250 if (response != NULL) return response;
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);
260 json_object_object_add(jsonSession, "jtype", json_object_new_string (AFB_SESSION_JTYPE));
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)));
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;
273 // extract session info from args
274 info = json_tokener_parse (request->post->data);
276 response = jsonNewMessage (AFB_FATAL,"sndcard=%s session=%s invalid json args=%s", request->prefix, name, request->post);
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);
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);
294 // this is valid info data for our session
295 json_object_object_add (jsonSession, "info", info);
298 // Finally save session on disk
299 err = json_object_to_file (filename, jsonSession);
301 response = jsonNewMessage (AFB_FATAL,"Fail save session = [%s] to disk", filename);
306 // create a link to keep track of last uploaded session for this card
307 if (!defsession) makeSessionLink (request->prefix, name);
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);
315 json_object_put (jsonSession);
320 // Free context [XXXX Should be protected again memory abort XXXX]
321 STATIC void ctxUuidFreeCB (AFB_clientCtx *client) {
323 AFB_plugin **plugins = client->plugins;
324 AFB_freeCtxCB freeCtxCB;
327 // If application add a handle let's free it now
328 if (client->contexts != NULL) {
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);
341 // Create a new store in RAM, not that is too small it will be automatically extended
342 PUBLIC void ctxStoreInit (int nbSession) {
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;
349 STATIC AFB_clientCtx *ctxStoreSearch (const char* uuid) {
351 AFB_clientCtx *client;
353 if (uuid == NULL) return NULL;
355 pthread_mutex_lock(&sessions.mutex);
357 for (idx=0; idx < sessions.max; idx++) {
358 if (sessions.store[idx] && (0 == strcmp (uuid, sessions.store[idx]->uuid))) break;
361 if (idx == sessions.max) client=NULL;
362 else client= sessions.store[idx];
363 pthread_mutex_unlock(&sessions.mutex);
369 STATIC AFB_error ctxStoreDel (AFB_clientCtx *client) {
372 if (client == NULL) return (AFB_FAIL);
374 pthread_mutex_lock(&sessions.mutex);
376 for (idx=0; idx < sessions.max; idx++) {
377 if (sessions.store[idx] && (0 == strcmp (client->uuid, sessions.store[idx]->uuid))) break;
380 if (idx == sessions.max) status=AFB_FAIL;
383 ctxUuidFreeCB (sessions.store[idx]);
384 sessions.store[idx]=NULL;
388 pthread_mutex_unlock(&sessions.mutex);
392 STATIC AFB_error ctxStoreAdd (AFB_clientCtx *client) {
395 if (client == NULL) return (AFB_FAIL);
397 //fprintf (stderr, "ctxStoreAdd request uuid=%s count=%d\n", client->uuid, sessions.count);
399 pthread_mutex_lock(&sessions.mutex);
401 for (idx=0; idx < sessions.max; idx++) {
402 if (NULL == sessions.store[idx]) break;
405 if (idx == sessions.max) status=AFB_FAIL;
409 sessions.store[idx]= client;
412 pthread_mutex_unlock(&sessions.mutex);
416 // Check if context timeout or not
417 STATIC int ctxStoreToOld (AFB_clientCtx *ctx, int timeout) {
419 time_t now = time(NULL);
420 res = ((ctx->timeStamp + timeout) <= now);
424 // Loop on every entry and remove old context sessions.hash
425 PUBLIC void ctxStoreGarbage (const int timeout) {
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))) {
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;
444 if (request->config->token == NULL) return NULL;
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");
449 // if UUID in query we're restfull with no cookies otherwise check for cookie
450 if (uuid != NULL) request->restfull = TRUE;
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);
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);
464 if (ctxStoreToOld (clientCtx, request->config->cntxTimeout)) {
465 // this session is too old let's delete it
466 ctxStoreDel (clientCtx);
469 request->context=clientCtx->contexts[idx];
470 request->handle = clientCtx->plugins[idx]->handle;
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;
484 uuid_generate(newuuid); // create a new UUID
485 uuid_unparse_lower(newuuid, clientCtx->uuid);
487 // if table is full at 50% let's clean it up
488 if(sessions.count > (sessions.max / 2)) ctxStoreGarbage(request->config->cntxTimeout);
490 // finally add uuid into hashtable
491 if (AFB_SUCCESS != ctxStoreAdd (clientCtx)) {
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;
503 // Sample Generic Ping Debug API
504 PUBLIC AFB_error ctxTokenCheck (AFB_clientCtx *clientCtx, AFB_request *request) {
507 if (clientCtx->contexts == NULL) return AFB_EMPTY;
509 // this time have to extract token from query list
510 token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, "token");
512 // if not token is providing we refuse the exchange
513 if ((token == NULL) || (clientCtx->token == NULL)) return (AFB_FALSE);
515 // compare current token with previous one
516 if ((0 == strcmp (token, clientCtx->token)) && (!ctxStoreToOld (clientCtx, request->config->cntxTimeout))) {
517 return (AFB_SUCCESS);
520 // Token is not valid let move level of assurance to zero and free attached client handle
524 // Free Client Session Context
525 PUBLIC AFB_error ctxTokenReset (AFB_clientCtx *clientCtx, AFB_request *request) {
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);
530 // Search for an existing client with the same UUID
531 clientCtx = ctxStoreSearch (clientCtx->uuid);
532 if (clientCtx == NULL) return AFB_FALSE;
534 // Remove client from table
535 ctxStoreDel (clientCtx);
537 return (AFB_SUCCESS);
540 // generate a new token
541 PUBLIC AFB_error ctxTokenCreate (AFB_clientCtx *clientCtx, AFB_request *request) {
545 if (clientCtx == NULL) return AFB_EMPTY;
547 // if config->token!="" then verify that we have the right initial share secret
548 if (request->config->token[0] != '\0') {
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;
554 // verify that it fits with initial tokens fit
555 if (strcmp(request->config->token, token)) return AFB_UNAUTH;
558 // create a UUID as token value
559 uuid_generate(newuuid);
560 uuid_unparse_lower(newuuid, clientCtx->token);
562 // keep track of time for session timeout and further clean up
563 clientCtx->timeStamp=time(NULL);
565 // Token is also store in context but it might be convenient for plugin to access it directly
566 return (AFB_SUCCESS);
570 // generate a new token and update client context
571 PUBLIC AFB_error ctxTokenRefresh (AFB_clientCtx *clientCtx, AFB_request *request) {
574 if (clientCtx == NULL) return AFB_EMPTY;
576 // Check if the old token is valid
577 if (ctxTokenCheck (clientCtx, request) != AFB_SUCCESS) return (AFB_FAIL);
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);
583 // keep track of time for session timeout and further clean up
584 clientCtx->timeStamp=time(NULL);
586 return (AFB_SUCCESS);