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 #define AFB_SESSION_JTYPE "AFB_session"
35 #define AFB_SESSION_JLIST "AFB_sessions.hash"
36 #define AFB_SESSION_JINFO "AFB_infos"
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
42 // Session UUID are store in a simple array [for 10 sessions this should be enough]
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
50 // verify we can read/write in session dir
51 PUBLIC AFB_error sessionCheckdir (AFB_session *session) {
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);
59 // change for session directory
60 err = chdir(session->config->sessiondir);
62 fprintf(stderr,"AFB: Fail to chdir to %s error=%s\n", session->config->sessiondir, strerror(err));
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;
75 // let's return only sessions.hash files
76 STATIC int fileSelect (const struct dirent *entry) {
77 return (strstr (entry->d_name, ".afb") != NULL);
80 STATIC json_object *checkCardDirExit (AFB_session *session, AFB_request *request ) {
81 int sessionDir, cardDir;
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));
88 // open session directory
89 sessionDir = open (session->config->sessiondir, O_DIRECTORY);
91 return (jsonNewMessage (AFB_FAIL,"Fail to open directory [%s] error=%s", session->config->sessiondir, strerror(sessionDir)));
94 // create session sndcard directory if it does not exit
95 cardDir = openat (sessionDir, request->prefix, O_DIRECTORY);
97 cardDir = mkdirat (sessionDir, request->prefix, O_RDWR | S_IRWXU | S_IRGRP);
99 return (jsonNewMessage (AFB_FAIL,"Fail to create directory [%s/%s] error=%s", session->config->sessiondir, request->prefix, strerror(cardDir)));
106 // create a session in current directory
107 PUBLIC json_object *sessionList (AFB_session *session, AFB_request *request) {
108 json_object *sessionsJ, *ajgResponse;
110 struct dirent **namelist;
111 int count, sessionDir;
113 // if directory for card's sessions.hash does not exist create it
114 ajgResponse = checkCardDirExit (session, request);
115 if (ajgResponse != NULL) return ajgResponse;
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)));
123 count = scandirat (sessionDir, request->prefix, &namelist, fileSelect, alphasort);
127 return (jsonNewMessage (AFB_FAIL,"Fail to scan sessions.hash directory [%s/%s] error=%s", session->config->sessiondir, request->prefix, strerror(sessionDir)));
129 if (count == 0) return (jsonNewMessage (AFB_EMPTY,"[%s] no session at [%s]", request->prefix, session->config->sessiondir));
131 // loop on each session file, retrieve its date and push it into json response object
132 sessionsJ = json_object_new_array();
134 json_object *sessioninfo;
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
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);
151 free(namelist[count]);
154 // free scandir structure
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);
163 return (ajgResponse);
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];
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));
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));
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;
191 return (jsonNewMessage (AFB_FATAL,"session name missing &session=MySessionName"));
194 // check for current session request
195 defsession = (strcmp (name, AFB_DEFAULT_SESSION) ==0);
197 // if directory for card's sessions.hash does not exist create it
198 response = checkCardDirExit (session, request);
199 if (response != NULL) return response;
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));
208 // just upload json object and return without any further processing
209 jsonSession = json_object_from_file (filename);
211 if (jsonSession == NULL) return (jsonNewMessage (AFB_EMPTY,"File [%s] not found", filename));
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));
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));
226 // create a link to keep track of last uploaded session for this card
227 if (!defsession) makeSessionLink (request->prefix, name);
229 return (jsonSession);
232 // push Json session object to disk
233 PUBLIC json_object * sessionToDisk (AFB_session *session, AFB_request *request, char *name, json_object *jsonSession) {
236 struct tm * timeinfo;
238 static json_object *response;
240 // we should have a session name
241 if (name == NULL) return (jsonNewMessage (AFB_FATAL,"session name missing &session=MySessionName"));
243 // check for current session request
244 defsession = (strcmp (name, AFB_DEFAULT_SESSION) ==0);
246 // if directory for card's sessions.hash does not exist create it
247 response = checkCardDirExit (session, request);
248 if (response != NULL) return response;
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);
258 json_object_object_add(jsonSession, "jtype", json_object_new_string (AFB_SESSION_JTYPE));
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)));
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;
271 // extract session info from args
272 info = json_tokener_parse (request->post->data);
274 response = jsonNewMessage (AFB_FATAL,"sndcard=%s session=%s invalid json args=%s", request->prefix, name, request->post);
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);
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);
292 // this is valid info data for our session
293 json_object_object_add (jsonSession, "info", info);
296 // Finally save session on disk
297 err = json_object_to_file (filename, jsonSession);
299 response = jsonNewMessage (AFB_FATAL,"Fail save session = [%s] to disk", filename);
304 // create a link to keep track of last uploaded session for this card
305 if (!defsession) makeSessionLink (request->prefix, name);
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);
313 json_object_put (jsonSession);
318 // Free context [XXXX Should be protected again memory abort XXXX]
319 STATIC void ctxUuidFreeCB (AFB_clientCtx *client) {
321 AFB_plugin **plugins = client->plugins;
322 AFB_freeCtxCB freeCtxCB;
325 // If application add a handle let's free it now
326 if (client->contexts != NULL) {
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);
339 // Create a new store in RAM, not that is too small it will be automatically extended
340 PUBLIC void ctxStoreInit (int nbSession) {
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;
347 STATIC AFB_clientCtx *ctxStoreSearch (const char* uuid) {
349 AFB_clientCtx *client;
351 if (uuid == NULL) return NULL;
353 pthread_mutex_lock(&sessions.mutex);
355 for (idx=0; idx < sessions.max; idx++) {
356 if (sessions.store[idx] && (0 == strcmp (uuid, sessions.store[idx]->uuid))) break;
359 if (idx == sessions.max) client=NULL;
360 else client= sessions.store[idx];
361 pthread_mutex_unlock(&sessions.mutex);
367 STATIC AFB_error ctxStoreDel (AFB_clientCtx *client) {
370 if (client == NULL) return (AFB_FAIL);
372 pthread_mutex_lock(&sessions.mutex);
374 for (idx=0; idx < sessions.max; idx++) {
375 if (sessions.store[idx] && (0 == strcmp (client->uuid, sessions.store[idx]->uuid))) break;
378 if (idx == sessions.max) status=AFB_FAIL;
381 ctxUuidFreeCB (sessions.store[idx]);
382 sessions.store[idx]=NULL;
386 pthread_mutex_unlock(&sessions.mutex);
390 STATIC AFB_error ctxStoreAdd (AFB_clientCtx *client) {
393 if (client == NULL) return (AFB_FAIL);
395 //fprintf (stderr, "ctxStoreAdd request uuid=%s count=%d\n", client->uuid, sessions.count);
397 pthread_mutex_lock(&sessions.mutex);
399 for (idx=0; idx < sessions.max; idx++) {
400 if (NULL == sessions.store[idx]) break;
403 if (idx == sessions.max) status=AFB_FAIL;
407 sessions.store[idx]= client;
410 pthread_mutex_unlock(&sessions.mutex);
414 // Check if context timeout or not
415 STATIC int ctxStoreToOld (AFB_clientCtx *ctx, int timeout) {
417 time_t now = time(NULL);
418 res = ((ctx->timeStamp + timeout) <= now);
422 // Loop on every entry and remove old context sessions.hash
423 PUBLIC void ctxStoreGarbage (const int timeout) {
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))) {
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;
442 if (request->config->token == NULL) return NULL;
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");
447 // if UUID in query we're restfull with no cookies otherwise check for cookie
448 if (uuid != NULL) request->restfull = TRUE;
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);
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);
462 if (ctxStoreToOld (clientCtx, request->config->cntxTimeout)) {
463 // this session is too old let's delete it
464 ctxStoreDel (clientCtx);
467 request->context=clientCtx->contexts[idx];
468 request->handle = clientCtx->plugins[idx]->handle;
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;
482 uuid_generate(newuuid); // create a new UUID
483 uuid_unparse_lower(newuuid, clientCtx->uuid);
485 // if table is full at 50% let's clean it up
486 if(sessions.count > (sessions.max / 2)) ctxStoreGarbage(request->config->cntxTimeout);
488 // finally add uuid into hashtable
489 if (AFB_SUCCESS != ctxStoreAdd (clientCtx)) {
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;
501 // Sample Generic Ping Debug API
502 PUBLIC AFB_error ctxTokenCheck (AFB_clientCtx *clientCtx, AFB_request *request) {
505 if (clientCtx->contexts == NULL) return AFB_EMPTY;
507 // this time have to extract token from query list
508 token = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, "token");
510 // if not token is providing we refuse the exchange
511 if ((token == NULL) || (clientCtx->token == NULL)) return (AFB_FALSE);
513 // compare current token with previous one
514 if ((0 == strcmp (token, clientCtx->token)) && (!ctxStoreToOld (clientCtx, request->config->cntxTimeout))) {
515 return (AFB_SUCCESS);
518 // Token is not valid let move level of assurance to zero and free attached client handle
522 // Free Client Session Context
523 PUBLIC AFB_error ctxTokenReset (AFB_clientCtx *clientCtx, AFB_request *request) {
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);
528 // Search for an existing client with the same UUID
529 clientCtx = ctxStoreSearch (clientCtx->uuid);
530 if (clientCtx == NULL) return AFB_FALSE;
532 // Remove client from table
533 ctxStoreDel (clientCtx);
535 return (AFB_SUCCESS);
538 // generate a new token
539 PUBLIC AFB_error ctxTokenCreate (AFB_clientCtx *clientCtx, AFB_request *request) {
543 if (clientCtx == NULL) return AFB_EMPTY;
545 // if config->token!="" then verify that we have the right initial share secret
546 if (request->config->token[0] != '\0') {
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;
552 // verify that it fits with initial tokens fit
553 if (strcmp(request->config->token, token)) return AFB_UNAUTH;
556 // create a UUID as token value
557 uuid_generate(newuuid);
558 uuid_unparse_lower(newuuid, clientCtx->token);
560 // keep track of time for session timeout and further clean up
561 clientCtx->timeStamp=time(NULL);
563 // Token is also store in context but it might be convenient for plugin to access it directly
564 return (AFB_SUCCESS);
568 // generate a new token and update client context
569 PUBLIC AFB_error ctxTokenRefresh (AFB_clientCtx *clientCtx, AFB_request *request) {
572 if (clientCtx == NULL) return AFB_EMPTY;
574 // Check if the old token is valid
575 if (ctxTokenCheck (clientCtx, request) != AFB_SUCCESS) return (AFB_FAIL);
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);
581 // keep track of time for session timeout and further clean up
582 clientCtx->timeStamp=time(NULL);
584 return (AFB_SUCCESS);