2 * Copyright (C) 2015, 2016, 2017 "IoT.bzh"
3 * Author "Fulup Ar Foll"
4 * Author: José Bollo <jose.bollo@iot.bzh>
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
25 #include <uuid/uuid.h>
29 #include <json-c/json.h>
31 #include "afb-session.h"
37 #define COOKEYMASK (COOKEYCOUNT - 1)
39 #define NOW (time(NULL))
46 void (*freecb)(void*);
51 struct afb_session *next; /* link to the next */
54 time_t expiration; // expiration time of the token
55 pthread_mutex_t mutex;
57 char uuid[SIZEUUID]; // long term authentication of remote client
58 char token[SIZEUUID]; // short term authentication of remote client
59 struct cookie *cookies[COOKEYCOUNT];
62 // Session UUID are store in a simple array [for 10 sessions this should be enough]
64 pthread_mutex_t mutex; // declare a mutex to protect hash table
65 struct afb_session *heads[HEADCOUNT]; // sessions
66 int count; // current number of sessions
69 char initok[SIZEUUID];
73 static void new_uuid(char uuid[SIZEUUID])
76 uuid_generate(newuuid);
77 uuid_unparse_lower(newuuid, uuid);
80 static inline void lock(struct afb_session *session)
82 pthread_mutex_lock(&session->mutex);
85 static inline void unlock(struct afb_session *session)
87 pthread_mutex_unlock(&session->mutex);
90 // Free context [XXXX Should be protected again memory abort XXXX]
91 static void remove_all_cookies(struct afb_session *session)
94 struct cookie *cookie, *next;
97 for (idx = 0 ; idx < COOKEYCOUNT ; idx++) {
98 cookie = session->cookies[idx];
99 session->cookies[idx] = NULL;
100 while (cookie != NULL) {
102 if (cookie->freecb != NULL)
103 cookie->freecb(cookie->value);
110 /* tiny hash function inspired from pearson */
111 static int pearson4(const char *text)
113 static uint8_t T[16] = {
114 4, 1, 6, 0, 9, 14, 11, 5,
115 2, 3, 12, 15, 10, 7, 8, 13
119 for (r = 0; (c = (uint8_t)*text) ; text++) {
123 return r; // % HEADCOUNT;
126 // Create a new store in RAM, not that is too small it will be automatically extended
127 void afb_session_init (int max_session_count, int timeout, const char *initok)
129 pthread_mutex_init(&sessions.mutex, NULL);
130 sessions.max = max_session_count;
131 sessions.timeout = timeout;
133 /* without token, a secret is made to forbid creation of sessions */
134 new_uuid(sessions.initok);
135 else if (strlen(initok) < sizeof sessions.initok)
136 strcpy(sessions.initok, initok);
138 ERROR("initial token '%s' too long (max length %d)", initok, ((int)(sizeof sessions.initok)) - 1);
143 const char *afb_session_initial_token()
145 return sessions.initok;
148 static struct afb_session *search (const char* uuid, int idx)
150 struct afb_session *session;
152 session = sessions.heads[idx];
153 while (session && strcmp(uuid, session->uuid))
154 session = session->next;
159 static void destroy (struct afb_session *session)
161 struct afb_session **prv;
163 assert (session != NULL);
165 remove_all_cookies(session);
166 pthread_mutex_lock(&sessions.mutex);
167 prv = &sessions.heads[(int)session->idx];
170 prv = &((*prv)->next);
172 *prv = session->next;
174 pthread_mutex_destroy(&session->mutex);
178 pthread_mutex_unlock(&sessions.mutex);
181 // Check if context timeout or not
182 static int is_expired (struct afb_session *ctx, time_t now)
184 assert (ctx != NULL);
185 return ctx->expiration < now;
188 // Check if context is active or not
189 static int is_active (struct afb_session *ctx, time_t now)
191 assert (ctx != NULL);
192 return ctx->uuid[0] != 0 && ctx->expiration >= now;
195 // Loop on every entry and remove old context sessions.hash
196 static time_t cleanup ()
198 struct afb_session *session, *next;
202 // Loop on Sessions Table and remove anything that is older than timeout
204 for (idx = 0 ; idx < HEADCOUNT; idx++) {
205 session = sessions.heads[idx];
207 next = session->next;
208 if (is_expired(session, now))
209 afb_session_close(session);
216 static struct afb_session *add_session (const char *uuid, int timeout, time_t now, int idx)
218 struct afb_session *session;
221 /* check arguments */
222 if (!AFB_SESSION_TIMEOUT_IS_VALID(timeout)
223 || (uuid && strlen(uuid) >= sizeof session->uuid)) {
228 /* check session count */
229 if (sessions.count >= sessions.max) {
234 /* compute expiration */
235 if (timeout == AFB_SESSION_TIMEOUT_DEFAULT)
236 timeout = sessions.timeout;
237 expiration = now + timeout;
238 if (timeout == AFB_SESSION_TIMEOUT_INFINITE || expiration < 0) {
239 expiration = (time_t)(~(time_t)0);
241 expiration = (time_t)(((unsigned long long)expiration) >> 1);
244 /* allocates a new one */
245 session = calloc(1, sizeof *session);
246 if (session == NULL) {
252 pthread_mutex_init(&session->mutex, NULL);
253 session->refcount = 1;
254 strcpy(session->uuid, uuid);
255 strcpy(session->token, sessions.initok);
256 session->timeout = timeout;
257 session->expiration = expiration;
258 session->idx = (char)idx;
259 session->next = sessions.heads[idx];
260 sessions.heads[idx] = session;
266 /* create a new session for the given timeout */
267 static struct afb_session *new_session (int timeout, time_t now)
274 idx = pearson4(uuid);
275 } while(search(uuid, idx));
276 return add_session(uuid, timeout, now, idx);
279 /* Creates a new session with 'timeout' */
280 struct afb_session *afb_session_create (int timeout)
283 struct afb_session *session;
286 pthread_mutex_lock(&sessions.mutex);
288 session = new_session(timeout, now);
289 pthread_mutex_unlock(&sessions.mutex);
294 /* Searchs the session of 'uuid' */
295 struct afb_session *afb_session_search (const char *uuid)
297 struct afb_session *session;
300 pthread_mutex_lock(&sessions.mutex);
302 session = search(uuid, pearson4(uuid));
304 __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
305 pthread_mutex_unlock(&sessions.mutex);
310 /* This function will return exiting session or newly created session */
311 struct afb_session *afb_session_get (const char *uuid, int timeout, int *created)
314 struct afb_session *session;
318 pthread_mutex_lock(&sessions.mutex);
321 /* search for an existing one not too old */
323 session = new_session(timeout, now);
325 idx = pearson4(uuid);
326 session = search(uuid, idx);
328 __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
329 pthread_mutex_unlock(&sessions.mutex);
334 session = add_session (uuid, timeout, now, idx);
336 pthread_mutex_unlock(&sessions.mutex);
339 *created = !!session;
344 /* increase the use count on the session */
345 struct afb_session *afb_session_addref(struct afb_session *session)
348 __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
352 /* decrease the use count of the session */
353 void afb_session_unref(struct afb_session *session)
355 if (session != NULL) {
356 assert(session->refcount != 0);
357 if (!__atomic_sub_fetch(&session->refcount, 1, __ATOMIC_RELAXED)) {
358 pthread_mutex_lock(&session->mutex);
359 if (session->uuid[0] == 0)
362 pthread_mutex_unlock(&session->mutex);
367 // Free Client Session Context
368 void afb_session_close (struct afb_session *session)
370 assert(session != NULL);
371 pthread_mutex_lock(&session->mutex);
372 if (session->uuid[0] != 0) {
373 session->uuid[0] = 0;
374 remove_all_cookies(session);
375 if (session->refcount == 0) {
380 pthread_mutex_unlock(&session->mutex);
383 // Sample Generic Ping Debug API
384 int afb_session_check_token (struct afb_session *session, const char *token)
386 assert(session != NULL);
387 assert(token != NULL);
389 // compare current token with previous one
390 if (!is_active (session, NOW))
393 if (session->token[0] && strcmp (token, session->token) != 0)
399 // generate a new token and update client context
400 void afb_session_new_token (struct afb_session *session)
402 assert(session != NULL);
404 // Old token was valid let's regenerate a new one
405 new_uuid(session->token);
407 // keep track of time for session timeout and further clean up
408 if (session->timeout != 0)
409 session->expiration = NOW + session->timeout;
412 /* Returns the uuid of 'session' */
413 const char *afb_session_uuid (struct afb_session *session)
415 assert(session != NULL);
416 return session->uuid;
419 /* Returns the token of 'session' */
420 const char *afb_session_token (struct afb_session *session)
422 assert(session != NULL);
423 return session->token;
427 * Get the index of the 'key' in the cookies array.
428 * @param key the key to scan
429 * @return the index of the list for key within cookies
431 static int cookeyidx(const void *key)
433 intptr_t x = (intptr_t)key;
434 unsigned r = (unsigned)((x >> 5) ^ (x >> 15));
435 return r & COOKEYMASK;
439 * Set, get, replace, remove a cookie of 'key' for the 'session'
441 * The behaviour of this function depends on its parameters:
443 * @param session the session
444 * @param key the key of the cookie
445 * @param makecb the creation function or NULL
446 * @param freecb the release function or NULL
447 * @param closure an argument for makecb or the value if makecb==NULL
448 * @param replace a boolean enforcing replecement of the previous value
450 * @return the value of the cookie
452 * The 'key' is a pointer and compared as pointers.
454 * For getting the current value of the cookie:
456 * afb_session_cookie(session, key, NULL, NULL, NULL, 0)
458 * For storing the value of the cookie
460 * afb_session_cookie(session, key, NULL, NULL, value, 1)
462 void *afb_session_cookie(struct afb_session *session, const void *key, void *(*makecb)(void *closure), void (*freecb)(void *item), void *closure, int replace)
466 struct cookie *cookie, **prv;
468 /* get key hashed index */
469 idx = cookeyidx(key);
471 /* lock session and search for the cookie of 'key' */
473 prv = &session->cookies[idx];
477 /* 'key' not found, create value using 'closure' and 'makecb' */
478 value = makecb ? makecb(closure) : closure;
479 /* store the the only if it has some meaning */
480 if (replace || makecb || freecb) {
481 cookie = malloc(sizeof *cookie);
484 /* calling freecb if there is no makecb may have issue */
485 if (makecb && freecb)
490 cookie->value = value;
491 cookie->freecb = freecb;
497 } else if (cookie->key == key) {
498 /* cookie of key found */
500 /* not replacing, get the value */
501 value = cookie->value;
503 /* create value using 'closure' and 'makecb' */
504 value = makecb ? makecb(closure) : closure;
506 /* free previous value is needed */
507 if (cookie->value != value && cookie->freecb)
508 cookie->freecb(cookie->value);
510 /* store the value and its releaser */
511 cookie->value = value;
512 cookie->freecb = freecb;
514 /* but if both are NULL drop the cookie */
515 if (!value && !freecb) {
522 prv = &(cookie->next);
526 /* unlock the session and return the value */
531 void *afb_session_get_cookie(struct afb_session *session, const void *key)
533 return afb_session_cookie(session, key, NULL, NULL, NULL, 0);
536 int afb_session_set_cookie(struct afb_session *session, const void *key, void *value, void (*freecb)(void*))
538 return -(value != afb_session_cookie(session, key, NULL, freecb, value, 1));