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.
26 #include <uuid/uuid.h>
29 #include <json-c/json.h>
31 #include "afb-session.h"
38 #define COOKIEMASK (COOKIECOUNT - 1)
40 #define _MAXEXP_ ((time_t)(~(time_t)0))
41 #define _MAXEXP2_ ((time_t)((((unsigned long long)_MAXEXP_) >> 1)))
42 #define MAX_EXPIRATION (_MAXEXP_ >= 0 ? _MAXEXP_ : _MAXEXP2_)
43 #define NOW (time_now())
45 /* structure for a cookie added to sessions */
48 struct cookie *next; /* link to next cookie */
49 const void *key; /* pointer key */
50 void *value; /* value */
51 void (*freecb)(void*); /* function to call when session is closed */
55 * structure for session
59 struct afb_session *next; /* link to the next */
60 unsigned refcount; /* external reference count of the session */
61 int timeout; /* timeout of the session */
62 time_t expiration; /* expiration time of the token */
63 pthread_mutex_t mutex; /* mutex of the session */
64 struct cookie *cookies[COOKIECOUNT]; /* cookies of the session */
65 uint8_t closed: 1; /* is the session closed ? */
66 uint8_t autoclose: 1; /* close the session when unreferenced */
67 uint8_t notinset: 1; /* session removed from the set of sessions */
68 char uuid[SIZEUUID]; /* long term authentication of remote client */
69 char token[SIZEUUID]; /* short term authentication of remote client */
72 /* Session UUID are store in a simple array [for 10 sessions this should be enough] */
74 int count; /* current number of sessions */
75 int max; /* maximum count of sessions */
76 int timeout; /* common initial timeout */
77 struct afb_session *heads[HEADCOUNT]; /* sessions */
78 char initok[SIZEUUID]; /* common initial token */
79 pthread_mutex_t mutex; /* declare a mutex to protect hash table */
86 .mutex = PTHREAD_MUTEX_INITIALIZER
89 /* Get the actual raw time */
90 static inline time_t time_now()
93 clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
97 /* generate a new fresh 'uuid' */
98 static void new_uuid(char uuid[SIZEUUID])
101 uuid_generate(newuuid);
102 uuid_unparse_lower(newuuid, uuid);
106 * Returns a tiny hash value for the 'text'.
108 * Tiny hash function inspired from pearson
110 static uint8_t pearson4(const char *text)
112 static uint8_t T[16] = {
113 4, 1, 6, 0, 9, 14, 11, 5,
114 2, 3, 12, 15, 10, 7, 8, 13
118 for (r = 0; (c = (uint8_t)*text) ; text++) {
122 return r; // % HEADCOUNT;
125 /* lock the set of sessions for exclusive access */
126 static inline void sessionset_lock()
128 pthread_mutex_lock(&sessions.mutex);
131 /* unlock the set of sessions of exclusive access */
132 static inline void sessionset_unlock()
134 pthread_mutex_unlock(&sessions.mutex);
138 * search within the set of sessions the session of 'uuid'.
139 * 'hashidx' is the precomputed hash for 'uuid'
140 * return the session or NULL
142 static struct afb_session *sessionset_search(const char *uuid, uint8_t hashidx)
144 struct afb_session *session;
146 session = sessions.heads[hashidx];
147 while (session && strcmp(uuid, session->uuid))
148 session = session->next;
153 /* add 'session' to the set of sessions */
154 static int sessionset_add(struct afb_session *session, uint8_t hashidx)
156 /* check availability */
157 if (sessions.count >= sessions.max) {
162 /* add the session */
163 session->next = sessions.heads[hashidx];
164 sessions.heads[hashidx] = session;
169 /* make a new uuid not used in the set of sessions */
170 static uint8_t sessionset_make_uuid (char uuid[SIZEUUID])
176 hashidx = pearson4(uuid);
177 } while(sessionset_search(uuid, hashidx));
181 /* lock the 'session' for exclusive access */
182 static inline void session_lock(struct afb_session *session)
184 pthread_mutex_lock(&session->mutex);
187 /* unlock the 'session' of exclusive access */
188 static inline void session_unlock(struct afb_session *session)
190 pthread_mutex_unlock(&session->mutex);
193 /* close the 'session' */
194 static void session_close(struct afb_session *session)
197 struct cookie *cookie;
199 /* close only one time */
200 if (!session->closed) {
205 afb_hook_session_close(session);
207 /* release cookies */
208 for (idx = 0 ; idx < COOKIECOUNT ; idx++) {
209 while ((cookie = session->cookies[idx])) {
210 session->cookies[idx] = cookie->next;
211 if (cookie->freecb != NULL)
212 cookie->freecb(cookie->value);
219 /* destroy the 'session' */
220 static void session_destroy (struct afb_session *session)
222 afb_hook_session_destroy(session);
223 pthread_mutex_destroy(&session->mutex);
227 /* update expiration of 'session' according to 'now' */
228 static void session_update_expiration(struct afb_session *session, time_t now)
233 /* compute expiration */
234 timeout = session->timeout;
235 if (timeout == AFB_SESSION_TIMEOUT_INFINITE)
236 expiration = MAX_EXPIRATION;
238 if (timeout == AFB_SESSION_TIMEOUT_DEFAULT)
239 expiration = now + sessions.timeout;
241 expiration = now + timeout;
243 expiration = MAX_EXPIRATION;
246 /* record the expiration */
247 session->expiration = expiration;
251 * Add a new session with the 'uuid' (of 'hashidx')
252 * and the 'timeout' starting from 'now'.
253 * Add it to the set of sessions
254 * Return the created session
256 static struct afb_session *session_add(const char *uuid, int timeout, time_t now, uint8_t hashidx)
258 struct afb_session *session;
260 /* check arguments */
261 if (!AFB_SESSION_TIMEOUT_IS_VALID(timeout)
262 || (uuid && strlen(uuid) >= sizeof session->uuid)) {
267 /* allocates a new one */
268 session = calloc(1, sizeof *session);
269 if (session == NULL) {
275 pthread_mutex_init(&session->mutex, NULL);
276 session->refcount = 1;
277 strcpy(session->uuid, uuid);
278 strcpy(session->token, sessions.initok);
279 session->timeout = timeout;
280 session_update_expiration(session, now);
283 if (sessionset_add(session, hashidx)) {
288 afb_hook_session_create(session);
293 /* Remove expired sessions and return current time (now) */
294 static time_t sessionset_cleanup (int force)
296 struct afb_session *session, **prv;
300 /* Loop on Sessions Table and remove anything that is older than timeout */
302 for (idx = 0 ; idx < HEADCOUNT; idx++) {
303 prv = &sessions.heads[idx];
304 while ((session = *prv)) {
305 session_lock(session);
306 if (force || session->expiration < now)
307 session_close(session);
308 if (!session->closed)
309 prv = &session->next;
311 *prv = session->next;
313 session->notinset = 1;
314 if ( !session->refcount) {
315 session_destroy(session);
319 session_unlock(session);
326 * Initialize the session manager with a 'max_session_count',
327 * an initial common 'timeout' and an initial common token 'initok'.
329 * @param max_session_count maximum allowed session count in the same time
330 * @param timeout the initial default timeout of sessions
331 * @param initok the initial default token of sessions
334 int afb_session_init (int max_session_count, int timeout, const char *initok)
336 /* check parameters */
337 if (initok && strlen(initok) >= sizeof sessions.initok) {
338 ERROR("initial token '%s' too long (max length %d)",
339 initok, ((int)(sizeof sessions.initok)) - 1);
344 /* init the sessionset (after cleanup) */
346 sessionset_cleanup(1);
347 sessions.max = max_session_count;
348 sessions.timeout = timeout;
350 new_uuid(sessions.initok);
352 strcpy(sessions.initok, initok);
358 * Iterate the sessions and call 'callback' with
359 * the 'closure' for each session.
361 void afb_session_foreach(void (*callback)(void *closure, struct afb_session *session), void *closure)
363 struct afb_session *session;
366 /* Loop on Sessions Table and remove anything that is older than timeout */
368 for (idx = 0 ; idx < HEADCOUNT; idx++) {
369 session = sessions.heads[idx];
371 if (!session->closed)
372 callback(closure, session);
373 session = session->next;
380 * Cleanup the sessionset of its closed or expired sessions
382 void afb_session_purge()
385 sessionset_cleanup(0);
390 * @return the initial token set at initialization
392 const char *afb_session_initial_token()
394 return sessions.initok;
397 /* Searchs the session of 'uuid' */
398 struct afb_session *afb_session_search (const char *uuid)
400 struct afb_session *session;
403 sessionset_cleanup(0);
404 session = sessionset_search(uuid, pearson4(uuid));
405 session = afb_session_addref(session);
412 * Creates a new session with 'timeout'
414 struct afb_session *afb_session_create (int timeout)
416 return afb_session_get(NULL, timeout, NULL);
419 /* This function will return exiting session or newly created session */
420 struct afb_session *afb_session_get (const char *uuid, int timeout, int *created)
422 char _uuid_[SIZEUUID];
424 struct afb_session *session;
430 now = sessionset_cleanup(0);
432 /* search for an existing one not too old */
434 hashidx = sessionset_make_uuid(_uuid_);
437 hashidx = pearson4(uuid);
438 session = sessionset_search(uuid, hashidx);
441 afb_session_addref(session);
446 /* create the session */
447 session = session_add(uuid, timeout, now, hashidx);
457 /* increase the use count on 'session' (can be NULL) */
458 struct afb_session *afb_session_addref(struct afb_session *session)
460 if (session != NULL) {
461 afb_hook_session_addref(session);
463 session_unlock(session);
468 /* decrease the use count of 'session' (can be NULL) */
469 void afb_session_unref(struct afb_session *session)
474 session_lock(session);
475 afb_hook_session_unref(session);
476 if (--session->refcount) {
477 if (session->autoclose)
478 session_close(session);
479 if (session->notinset) {
480 session_destroy(session);
484 session_unlock(session);
487 /* close 'session' */
488 void afb_session_close (struct afb_session *session)
490 session_lock(session);
491 session_close(session);
492 session_unlock(session);
496 * Set the 'autoclose' flag of the 'session'
498 * A session whose autoclose flag is true will close as
499 * soon as it is no more referenced.
501 * @param session the session to set
502 * @param autoclose the value to set
504 void afb_session_set_autoclose(struct afb_session *session, int autoclose)
506 session->autoclose = !!autoclose;
509 /* is 'session' closed? */
510 int afb_session_is_closed (struct afb_session *session)
512 return session->closed;
516 * check whether the token of 'session' is 'token'
517 * return 1 if true or 0 otherwise
519 int afb_session_check_token (struct afb_session *session, const char *token)
523 session_unlock(session);
525 && session->expiration >= NOW
526 && !(session->token[0] && strcmp (token, session->token));
527 session_unlock(session);
531 /* generate a new token and update client context */
532 void afb_session_new_token (struct afb_session *session)
534 session_unlock(session);
535 new_uuid(session->token);
536 session_update_expiration(session, NOW);
537 afb_hook_session_renew(session);
538 session_unlock(session);
541 /* Returns the uuid of 'session' */
542 const char *afb_session_uuid (struct afb_session *session)
544 return session->uuid;
547 /* Returns the token of 'session' */
548 const char *afb_session_token (struct afb_session *session)
550 return session->token;
554 * Get the index of the 'key' in the cookies array.
555 * @param key the key to scan
556 * @return the index of the list for key within cookies
558 static int cookeyidx(const void *key)
560 intptr_t x = (intptr_t)key;
561 unsigned r = (unsigned)((x >> 5) ^ (x >> 15));
562 return r & COOKIEMASK;
566 * Set, get, replace, remove a cookie of 'key' for the 'session'
568 * The behaviour of this function depends on its parameters:
570 * @param session the session
571 * @param key the key of the cookie
572 * @param makecb the creation function or NULL
573 * @param freecb the release function or NULL
574 * @param closure an argument for makecb or the value if makecb==NULL
575 * @param replace a boolean enforcing replecement of the previous value
577 * @return the value of the cookie
579 * The 'key' is a pointer and compared as pointers.
581 * For getting the current value of the cookie:
583 * afb_session_cookie(session, key, NULL, NULL, NULL, 0)
585 * For storing the value of the cookie
587 * afb_session_cookie(session, key, NULL, NULL, value, 1)
589 void *afb_session_cookie(struct afb_session *session, const void *key, void *(*makecb)(void *closure), void (*freecb)(void *item), void *closure, int replace)
593 struct cookie *cookie, **prv;
595 /* get key hashed index */
596 idx = cookeyidx(key);
598 /* lock session and search for the cookie of 'key' */
599 session_lock(session);
600 prv = &session->cookies[idx];
604 /* 'key' not found, create value using 'closure' and 'makecb' */
605 value = makecb ? makecb(closure) : closure;
606 /* store the the only if it has some meaning */
607 if (replace || makecb || freecb) {
608 cookie = malloc(sizeof *cookie);
611 /* calling freecb if there is no makecb may have issue */
612 if (makecb && freecb)
617 cookie->value = value;
618 cookie->freecb = freecb;
624 } else if (cookie->key == key) {
625 /* cookie of key found */
627 /* not replacing, get the value */
628 value = cookie->value;
630 /* create value using 'closure' and 'makecb' */
631 value = makecb ? makecb(closure) : closure;
633 /* free previous value is needed */
634 if (cookie->value != value && cookie->freecb)
635 cookie->freecb(cookie->value);
637 /* if both value and freecb are NULL drop the cookie */
638 if (!value && !freecb) {
642 /* store the value and its releaser */
643 cookie->value = value;
644 cookie->freecb = freecb;
649 prv = &(cookie->next);
653 /* unlock the session and return the value */
654 session_unlock(session);
659 * Get the cookie of 'key' in the 'session'.
661 * @param session the session to search in
662 * @param key the key of the data to retrieve
664 * @return the data staored for the key or NULL if the key isn't found
666 void *afb_session_get_cookie(struct afb_session *session, const void *key)
668 return afb_session_cookie(session, key, NULL, NULL, NULL, 0);
672 * Set the cookie of 'key' in the 'session' to the 'value' that can be
673 * cleaned using 'freecb' (if not null).
675 * @param session the session to set
676 * @param key the key of the data to store
677 * @param value the value to store at key
678 * @param freecb a function to use when the cookie value is to remove (or null)
680 * @return the data staored for the key or NULL if the key isn't found
683 int afb_session_set_cookie(struct afb_session *session, const void *key, void *value, void (*freecb)(void*))
685 return -(value != afb_session_cookie(session, key, NULL, freecb, value, 1));