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 static const char key_uuid[] = "uuid";
43 static const char key_token[] = "token";
45 // Free context [XXXX Should be protected again memory abort XXXX]
46 static void ctxUuidFreeCB (AFB_clientCtx *client)
49 AFB_plugin **plugins = client->plugins;
50 AFB_freeCtxCB freeCtxCB;
53 // If application add a handle let's free it now
54 if (client->contexts != NULL) {
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);
69 // Create a new store in RAM, not that is too small it will be automatically extended
70 void ctxStoreInit (int nbSession)
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;
78 static AFB_clientCtx *ctxStoreSearch (const char* uuid)
81 AFB_clientCtx *client;
86 pthread_mutex_lock(&sessions.mutex);
88 for (idx=0; idx < sessions.max; idx++) {
89 if (sessions.store[idx] && (0 == strcmp (uuid, sessions.store[idx]->uuid))) break;
92 if (idx == sessions.max) client=NULL;
93 else client= sessions.store[idx];
94 pthread_mutex_unlock(&sessions.mutex);
99 static AFB_error ctxStoreDel (AFB_clientCtx *client)
107 pthread_mutex_lock(&sessions.mutex);
109 for (idx=0; idx < sessions.max; idx++) {
110 if (sessions.store[idx] && (0 == strcmp (client->uuid, sessions.store[idx]->uuid))) break;
113 if (idx == sessions.max)
117 ctxUuidFreeCB (sessions.store[idx]);
118 sessions.store[idx]=NULL;
119 status = AFB_SUCCESS;
122 pthread_mutex_unlock(&sessions.mutex);
126 static AFB_error ctxStoreAdd (AFB_clientCtx *client)
133 //fprintf (stderr, "ctxStoreAdd request uuid=%s count=%d\n", client->uuid, sessions.count);
135 pthread_mutex_lock(&sessions.mutex);
137 for (idx=0; idx < sessions.max; idx++) {
138 if (NULL == sessions.store[idx]) break;
141 if (idx == sessions.max) status=AFB_FAIL;
145 sessions.store[idx]= client;
148 pthread_mutex_unlock(&sessions.mutex);
152 // Check if context timeout or not
153 static int ctxStoreToOld (AFB_clientCtx *ctx, int timeout)
156 time_t now = time(NULL);
157 res = (ctx->timeStamp + timeout) <= now;
161 // Loop on every entry and remove old context sessions.hash
162 void ctxStoreGarbage (const int timeout)
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))) {
176 // This function will return exiting client context or newly created client context
177 AFB_clientCtx *ctxClientGet (AFB_request *request, int idx)
179 AFB_clientCtx *clientCtx=NULL;
183 if (request->config->token == NULL) return NULL;
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);
188 // if UUID in query we're restfull with no cookies otherwise check for cookie
190 request->restfull = TRUE;
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);
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);
204 if (ctxStoreToOld (clientCtx, request->config->cntxTimeout)) {
205 // this session is too old let's delete it
206 ctxStoreDel (clientCtx);
209 request->context=clientCtx->contexts[idx];
210 request->handle = clientCtx->plugins[idx]->handle;
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;
224 uuid_generate(newuuid); // create a new UUID
225 uuid_unparse_lower(newuuid, clientCtx->uuid);
227 // if table is full at 50% let's clean it up
228 if(sessions.count > (sessions.max / 2)) ctxStoreGarbage(request->config->cntxTimeout);
230 // finally add uuid into hashtable
231 if (AFB_SUCCESS != ctxStoreAdd (clientCtx)) {
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;
243 // Sample Generic Ping Debug API
244 AFB_error ctxTokenCheck (AFB_clientCtx *clientCtx, AFB_request *request)
248 if (clientCtx->contexts == NULL)
251 // this time have to extract token from query list
252 token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, key_token);
254 // if not token is providing we refuse the exchange
255 if ((token == NULL) || (clientCtx->token == NULL))
258 // compare current token with previous one
259 if ((0 == strcmp (token, clientCtx->token)) && (!ctxStoreToOld (clientCtx, request->config->cntxTimeout))) {
263 // Token is not valid let move level of assurance to zero and free attached client handle
267 // Free Client Session Context
268 AFB_error ctxTokenReset (AFB_clientCtx *clientCtx, AFB_request *request)
270 if (clientCtx == NULL)
272 //if (verbose) fprintf (stderr, "ctxClientReset New uuid=[%s] token=[%s] timestamp=%d\n", clientCtx->uuid, clientCtx->token, clientCtx->timeStamp);
274 // Search for an existing client with the same UUID
275 clientCtx = ctxStoreSearch (clientCtx->uuid);
276 if (clientCtx == NULL)
279 // Remove client from table
280 ctxStoreDel (clientCtx);
285 // generate a new token
286 AFB_error ctxTokenCreate (AFB_clientCtx *clientCtx, AFB_request *request)
291 if (clientCtx == NULL)
294 // if config->token!="" then verify that we have the right initial share secret
295 if (request->config->token[0] != '\0') {
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);
302 // verify that it fits with initial tokens fit
303 if (strcmp(request->config->token, token))
307 // create a UUID as token value
308 uuid_generate(newuuid);
309 uuid_unparse_lower(newuuid, clientCtx->token);
311 // keep track of time for session timeout and further clean up
312 clientCtx->timeStamp=time(NULL);
314 // Token is also store in context but it might be convenient for plugin to access it directly
319 // generate a new token and update client context
320 AFB_error ctxTokenRefresh (AFB_clientCtx *clientCtx, AFB_request *request)
324 if (clientCtx == NULL)
327 // Check if the old token is valid
328 if (ctxTokenCheck (clientCtx, request) != AFB_SUCCESS)
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);
335 // keep track of time for session timeout and further clean up
336 clientCtx->timeStamp=time(NULL);
363 #if defined(ALLOWS_SESSION_FILES)
365 #define AFB_SESSION_JTYPE "AFB_session"
366 #define AFB_SESSION_JLIST "AFB_sessions.hash"
367 #define AFB_SESSION_JINFO "AFB_infos"
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
373 // let's return only sessions.hash files
374 static int fileSelect (const struct dirent *entry) {
375 return (strstr (entry->d_name, ".afb") != NULL);
378 static json_object *checkCardDirExit (AFB_session *session, AFB_request *request ) {
379 int sessionDir, cardDir;
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));
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)));
392 // create session sndcard directory if it does not exit
393 cardDir = openat (sessionDir, request->prefix, O_DIRECTORY);
395 cardDir = mkdirat (sessionDir, request->prefix, O_RDWR | S_IRWXU | S_IRGRP);
397 return (jsonNewMessage (AFB_FAIL,"Fail to create directory [%s/%s] error=%s", session->config->sessiondir, request->prefix, strerror(cardDir)));
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];
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));
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));
421 // verify we can read/write in session dir
422 AFB_error sessionCheckdir (AFB_session *session) {
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);
430 // change for session directory
431 err = chdir(session->config->sessiondir);
433 fprintf(stderr,"AFB: Fail to chdir to %s error=%s\n", session->config->sessiondir, strerror(err));
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;
446 // create a session in current directory
447 json_object *sessionList (AFB_session *session, AFB_request *request) {
448 json_object *sessionsJ, *ajgResponse;
450 struct dirent **namelist;
451 int count, sessionDir;
453 // if directory for card's sessions.hash does not exist create it
454 ajgResponse = checkCardDirExit (session, request);
455 if (ajgResponse != NULL) return ajgResponse;
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)));
463 count = scandirat (sessionDir, request->prefix, &namelist, fileSelect, alphasort);
467 return (jsonNewMessage (AFB_FAIL,"Fail to scan sessions.hash directory [%s/%s] error=%s", session->config->sessiondir, request->prefix, strerror(sessionDir)));
469 if (count == 0) return (jsonNewMessage (AFB_EMPTY,"[%s] no session at [%s]", request->prefix, session->config->sessiondir));
471 // loop on each session file, retrieve its date and push it into json response object
472 sessionsJ = json_object_new_array();
474 json_object *sessioninfo;
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
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);
491 free(namelist[count]);
494 // free scandir structure
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);
503 return (ajgResponse);
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;
514 return (jsonNewMessage (AFB_FATAL,"session name missing &session=MySessionName"));
517 // check for current session request
518 defsession = (strcmp (name, AFB_DEFAULT_SESSION) ==0);
520 // if directory for card's sessions.hash does not exist create it
521 response = checkCardDirExit (session, request);
522 if (response != NULL) return response;
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));
531 // just upload json object and return without any further processing
532 jsonSession = json_object_from_file (filename);
534 if (jsonSession == NULL) return (jsonNewMessage (AFB_EMPTY,"File [%s] not found", filename));
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));
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));
549 // create a link to keep track of last uploaded session for this card
550 if (!defsession) makeSessionLink (request->prefix, name);
552 return (jsonSession);
555 // push Json session object to disk
556 json_object * sessionToDisk (AFB_session *session, AFB_request *request, char *name, json_object *jsonSession) {
559 struct tm * timeinfo;
561 static json_object *response;
563 // we should have a session name
564 if (name == NULL) return (jsonNewMessage (AFB_FATAL,"session name missing &session=MySessionName"));
566 // check for current session request
567 defsession = (strcmp (name, AFB_DEFAULT_SESSION) ==0);
569 // if directory for card's sessions.hash does not exist create it
570 response = checkCardDirExit (session, request);
571 if (response != NULL) return response;
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);
581 json_object_object_add(jsonSession, "jtype", json_object_new_string (AFB_SESSION_JTYPE));
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)));
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;
594 // extract session info from args
595 info = json_tokener_parse (request->post->data);
597 response = jsonNewMessage (AFB_FATAL,"sndcard=%s session=%s invalid json args=%s", request->prefix, name, request->post);
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);
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);
615 // this is valid info data for our session
616 json_object_object_add (jsonSession, "info", info);
619 // Finally save session on disk
620 err = json_object_to_file (filename, jsonSession);
622 response = jsonNewMessage (AFB_FATAL,"Fail save session = [%s] to disk", filename);
627 // create a link to keep track of last uploaded session for this card
628 if (!defsession) makeSessionLink (request->prefix, name);
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);
636 json_object_put (jsonSession);