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(NULL))
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 /* generate a new fresh 'uuid' */
90 static void new_uuid(char uuid[SIZEUUID])
93 uuid_generate(newuuid);
94 uuid_unparse_lower(newuuid, uuid);
98 * Returns a tiny hash value for the 'text'.
100 * Tiny hash function inspired from pearson
102 static uint8_t pearson4(const char *text)
104 static uint8_t T[16] = {
105 4, 1, 6, 0, 9, 14, 11, 5,
106 2, 3, 12, 15, 10, 7, 8, 13
110 for (r = 0; (c = (uint8_t)*text) ; text++) {
114 return r; // % HEADCOUNT;
117 /* lock the set of sessions for exclusive access */
118 static inline void sessionset_lock()
120 pthread_mutex_lock(&sessions.mutex);
123 /* unlock the set of sessions of exclusive access */
124 static inline void sessionset_unlock()
126 pthread_mutex_unlock(&sessions.mutex);
130 * search within the set of sessions the session of 'uuid'.
131 * 'hashidx' is the precomputed hash for 'uuid'
132 * return the session or NULL
134 static struct afb_session *sessionset_search(const char *uuid, uint8_t hashidx)
136 struct afb_session *session;
138 session = sessions.heads[hashidx];
139 while (session && strcmp(uuid, session->uuid))
140 session = session->next;
145 /* add 'session' to the set of sessions */
146 static int sessionset_add(struct afb_session *session, uint8_t hashidx)
148 /* check availability */
149 if (sessions.count >= sessions.max) {
154 /* add the session */
155 session->next = sessions.heads[hashidx];
156 sessions.heads[hashidx] = session;
161 /* make a new uuid not used in the set of sessions */
162 static uint8_t sessionset_make_uuid (char uuid[SIZEUUID])
168 hashidx = pearson4(uuid);
169 } while(sessionset_search(uuid, hashidx));
173 /* lock the 'session' for exclusive access */
174 static inline void session_lock(struct afb_session *session)
176 pthread_mutex_lock(&session->mutex);
179 /* unlock the 'session' of exclusive access */
180 static inline void session_unlock(struct afb_session *session)
182 pthread_mutex_unlock(&session->mutex);
185 /* close the 'session' */
186 static void session_close(struct afb_session *session)
189 struct cookie *cookie;
191 /* close only one time */
192 if (!session->closed) {
197 afb_hook_session_close(session);
199 /* release cookies */
200 for (idx = 0 ; idx < COOKIECOUNT ; idx++) {
201 while ((cookie = session->cookies[idx])) {
202 session->cookies[idx] = cookie->next;
203 if (cookie->freecb != NULL)
204 cookie->freecb(cookie->value);
211 /* destroy the 'session' */
212 static void session_destroy (struct afb_session *session)
214 afb_hook_session_destroy(session);
215 pthread_mutex_destroy(&session->mutex);
219 /* update expiration of 'session' according to 'now' */
220 static void session_update_expiration(struct afb_session *session, time_t now)
225 /* compute expiration */
226 timeout = session->timeout;
227 if (timeout == AFB_SESSION_TIMEOUT_INFINITE)
228 expiration = MAX_EXPIRATION;
230 if (timeout == AFB_SESSION_TIMEOUT_DEFAULT)
231 expiration = now + sessions.timeout;
233 expiration = now + timeout;
235 expiration = MAX_EXPIRATION;
238 /* record the expiration */
239 session->expiration = expiration;
243 * Add a new session with the 'uuid' (of 'hashidx')
244 * and the 'timeout' starting from 'now'.
245 * Add it to the set of sessions
246 * Return the created session
248 static struct afb_session *session_add(const char *uuid, int timeout, time_t now, uint8_t hashidx)
250 struct afb_session *session;
252 /* check arguments */
253 if (!AFB_SESSION_TIMEOUT_IS_VALID(timeout)
254 || (uuid && strlen(uuid) >= sizeof session->uuid)) {
259 /* allocates a new one */
260 session = calloc(1, sizeof *session);
261 if (session == NULL) {
267 pthread_mutex_init(&session->mutex, NULL);
268 session->refcount = 1;
269 strcpy(session->uuid, uuid);
270 strcpy(session->token, sessions.initok);
271 session->timeout = timeout;
272 session_update_expiration(session, now);
275 if (sessionset_add(session, hashidx)) {
280 afb_hook_session_create(session);
285 /* Remove expired sessions and return current time (now) */
286 static time_t sessionset_cleanup (int force)
288 struct afb_session *session, **prv;
292 /* Loop on Sessions Table and remove anything that is older than timeout */
294 for (idx = 0 ; idx < HEADCOUNT; idx++) {
295 prv = &sessions.heads[idx];
296 while ((session = *prv)) {
297 session_lock(session);
298 if (force || session->expiration < now)
299 session_close(session);
300 if (!session->closed)
301 prv = &session->next;
303 *prv = session->next;
305 session->notinset = 1;
306 if ( !session->refcount) {
307 session_destroy(session);
311 session_unlock(session);
318 * Initialize the session manager with a 'max_session_count',
319 * an initial common 'timeout' and an initial common token 'initok'.
321 * @param max_session_count maximum allowed session count in the same time
322 * @param timeout the initial default timeout of sessions
323 * @param initok the initial default token of sessions
326 int afb_session_init (int max_session_count, int timeout, const char *initok)
328 /* check parameters */
329 if (initok && strlen(initok) >= sizeof sessions.initok) {
330 ERROR("initial token '%s' too long (max length %d)",
331 initok, ((int)(sizeof sessions.initok)) - 1);
336 /* init the sessionset (after cleanup) */
338 sessionset_cleanup(1);
339 sessions.max = max_session_count;
340 sessions.timeout = timeout;
342 new_uuid(sessions.initok);
344 strcpy(sessions.initok, initok);
350 * Cleanup the sessionset of its closed or expired sessions
352 void afb_session_purge()
355 sessionset_cleanup(0);
360 * @return the initial token set at initialization
362 const char *afb_session_initial_token()
364 return sessions.initok;
367 /* Searchs the session of 'uuid' */
368 struct afb_session *afb_session_search (const char *uuid)
370 struct afb_session *session;
373 sessionset_cleanup(0);
374 session = sessionset_search(uuid, pearson4(uuid));
375 session = afb_session_addref(session);
382 * Creates a new session with 'timeout'
384 struct afb_session *afb_session_create (int timeout)
386 return afb_session_get(NULL, timeout, NULL);
389 /* This function will return exiting session or newly created session */
390 struct afb_session *afb_session_get (const char *uuid, int timeout, int *created)
392 char _uuid_[SIZEUUID];
394 struct afb_session *session;
400 now = sessionset_cleanup(0);
402 /* search for an existing one not too old */
404 hashidx = sessionset_make_uuid(_uuid_);
407 hashidx = pearson4(uuid);
408 session = sessionset_search(uuid, hashidx);
411 afb_session_addref(session);
416 /* create the session */
417 session = session_add(uuid, timeout, now, hashidx);
427 /* increase the use count on 'session' (can be NULL) */
428 struct afb_session *afb_session_addref(struct afb_session *session)
430 if (session != NULL) {
431 afb_hook_session_addref(session);
433 session_unlock(session);
438 /* decrease the use count of 'session' (can be NULL) */
439 void afb_session_unref(struct afb_session *session)
444 session_lock(session);
445 afb_hook_session_unref(session);
446 if (--session->refcount) {
447 if (session->autoclose)
448 session_close(session);
449 if (session->notinset) {
450 session_destroy(session);
454 session_unlock(session);
457 /* close 'session' */
458 void afb_session_close (struct afb_session *session)
460 session_lock(session);
461 session_close(session);
462 session_unlock(session);
466 * Set the 'autoclose' flag of the 'session'
468 * A session whose autoclose flag is true will close as
469 * soon as it is no more referenced.
471 * @param session the session to set
472 * @param autoclose the value to set
474 void afb_session_set_autoclose(struct afb_session *session, int autoclose)
476 session->autoclose = !!autoclose;
479 /* is 'session' closed? */
480 int afb_session_is_closed (struct afb_session *session)
482 return session->closed;
486 * check whether the token of 'session' is 'token'
487 * return 1 if true or 0 otherwise
489 int afb_session_check_token (struct afb_session *session, const char *token)
493 session_unlock(session);
495 && session->expiration >= NOW
496 && !(session->token[0] && strcmp (token, session->token));
497 session_unlock(session);
501 /* generate a new token and update client context */
502 void afb_session_new_token (struct afb_session *session)
504 session_unlock(session);
505 new_uuid(session->token);
506 session_update_expiration(session, NOW);
507 afb_hook_session_renew(session);
508 session_unlock(session);
511 /* Returns the uuid of 'session' */
512 const char *afb_session_uuid (struct afb_session *session)
514 return session->uuid;
517 /* Returns the token of 'session' */
518 const char *afb_session_token (struct afb_session *session)
520 return session->token;
524 * Get the index of the 'key' in the cookies array.
525 * @param key the key to scan
526 * @return the index of the list for key within cookies
528 static int cookeyidx(const void *key)
530 intptr_t x = (intptr_t)key;
531 unsigned r = (unsigned)((x >> 5) ^ (x >> 15));
532 return r & COOKIEMASK;
536 * Set, get, replace, remove a cookie of 'key' for the 'session'
538 * The behaviour of this function depends on its parameters:
540 * @param session the session
541 * @param key the key of the cookie
542 * @param makecb the creation function or NULL
543 * @param freecb the release function or NULL
544 * @param closure an argument for makecb or the value if makecb==NULL
545 * @param replace a boolean enforcing replecement of the previous value
547 * @return the value of the cookie
549 * The 'key' is a pointer and compared as pointers.
551 * For getting the current value of the cookie:
553 * afb_session_cookie(session, key, NULL, NULL, NULL, 0)
555 * For storing the value of the cookie
557 * afb_session_cookie(session, key, NULL, NULL, value, 1)
559 void *afb_session_cookie(struct afb_session *session, const void *key, void *(*makecb)(void *closure), void (*freecb)(void *item), void *closure, int replace)
563 struct cookie *cookie, **prv;
565 /* get key hashed index */
566 idx = cookeyidx(key);
568 /* lock session and search for the cookie of 'key' */
569 session_lock(session);
570 prv = &session->cookies[idx];
574 /* 'key' not found, create value using 'closure' and 'makecb' */
575 value = makecb ? makecb(closure) : closure;
576 /* store the the only if it has some meaning */
577 if (replace || makecb || freecb) {
578 cookie = malloc(sizeof *cookie);
581 /* calling freecb if there is no makecb may have issue */
582 if (makecb && freecb)
587 cookie->value = value;
588 cookie->freecb = freecb;
594 } else if (cookie->key == key) {
595 /* cookie of key found */
597 /* not replacing, get the value */
598 value = cookie->value;
600 /* create value using 'closure' and 'makecb' */
601 value = makecb ? makecb(closure) : closure;
603 /* free previous value is needed */
604 if (cookie->value != value && cookie->freecb)
605 cookie->freecb(cookie->value);
607 /* if both value and freecb are NULL drop the cookie */
608 if (!value && !freecb) {
612 /* store the value and its releaser */
613 cookie->value = value;
614 cookie->freecb = freecb;
619 prv = &(cookie->next);
623 /* unlock the session and return the value */
624 session_unlock(session);
629 * Get the cookie of 'key' in the 'session'.
631 * @param session the session to search in
632 * @param key the key of the data to retrieve
634 * @return the data staored for the key or NULL if the key isn't found
636 void *afb_session_get_cookie(struct afb_session *session, const void *key)
638 return afb_session_cookie(session, key, NULL, NULL, NULL, 0);
642 * Set the cookie of 'key' in the 'session' to the 'value' that can be
643 * cleaned using 'freecb' (if not null).
645 * @param session the session to set
646 * @param key the key of the data to store
647 * @param value the value to store at key
648 * @param freecb a function to use when the cookie value is to remove (or null)
650 * @return the data staored for the key or NULL if the key isn't found
653 int afb_session_set_cookie(struct afb_session *session, const void *key, void *value, void (*freecb)(void*))
655 return -(value != afb_session_cookie(session, key, NULL, freecb, value, 1));