2 * Copyright (C) 2015-2018 "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.
27 #include <uuid/uuid.h>
31 #include "afb-session.h"
39 #define COOKIEMASK (COOKIECOUNT - 1)
41 #define _MAXEXP_ ((time_t)(~(time_t)0))
42 #define _MAXEXP2_ ((time_t)((((unsigned long long)_MAXEXP_) >> 1)))
43 #define MAX_EXPIRATION (_MAXEXP_ >= 0 ? _MAXEXP_ : _MAXEXP2_)
44 #define NOW (time_now())
47 * structure for a cookie added to sessions
51 struct cookie *next; /**< link to next cookie */
52 const void *key; /**< pointer key */
53 void *value; /**< value */
54 void (*freecb)(void*); /**< function to call when session is closed */
58 * structure for session
62 struct afb_session *next; /**< link to the next */
63 unsigned refcount; /**< count of reference to the session */
64 int timeout; /**< timeout of the session */
65 time_t expiration; /**< expiration time of the token */
66 pthread_mutex_t mutex; /**< mutex of the session */
67 struct cookie *cookies[COOKIECOUNT]; /**< cookies of the session */
68 uint8_t closed: 1; /**< is the session closed ? */
69 uint8_t autoclose: 1; /**< close the session when unreferenced */
70 uint8_t notinset: 1; /**< session removed from the set of sessions */
71 char uuid[SIZEUUID]; /**< long term authentication of remote client */
72 char token[SIZEUUID]; /**< short term authentication of remote client */
76 * structure for managing sessions
79 int count; /**< current number of sessions */
80 int max; /**< maximum count of sessions */
81 int timeout; /**< common initial timeout */
82 struct afb_session *heads[HEADCOUNT]; /**< sessions */
83 char initok[SIZEUUID]; /**< common initial token */
84 pthread_mutex_t mutex; /**< declare a mutex to protect hash table */
91 .mutex = PTHREAD_MUTEX_INITIALIZER
95 * Get the actual raw time
97 static inline time_t time_now()
100 clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
105 * generate a new fresh 'uuid'
107 static void new_uuid(char uuid[SIZEUUID])
111 #if defined(USE_UUID_GENERATE)
112 uuid_generate(newuuid);
116 static uint16_t counter;
117 static char state[32];
118 static struct random_data rdata;
121 clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
123 pid = (uint16_t)getpid();
124 counter = (uint16_t)(ts.tv_nsec >> 8);
126 initstate_r((((unsigned)pid) << 16) + ((unsigned)counter),
127 state, sizeof state, &rdata);
129 ts.tv_nsec ^= (long)ts.tv_sec;
133 newuuid[0] = (char)(ts.tv_nsec >> 24);
134 newuuid[1] = (char)(ts.tv_nsec >> 16);
135 newuuid[2] = (char)(ts.tv_nsec >> 8);
136 newuuid[3] = (char)(ts.tv_nsec);
138 newuuid[4] = (char)(pid >> 8);
139 newuuid[5] = (char)(pid);
141 random_r(&rdata, &x);
142 newuuid[6] = (char)(((x >> 16) & 0x0f) | 0x40); /* pseudo-random version */
143 newuuid[7] = (char)(x >> 8);
145 random_r(&rdata, &x);
146 newuuid[8] = (char)(((x >> 16) & 0x3f) | 0x80); /* variant RFC4122 */
147 newuuid[9] = (char)(x >> 8);
149 random_r(&rdata, &x);
150 newuuid[10] = (char)(x >> 16);
151 newuuid[11] = (char)(x >> 8);
153 random_r(&rdata, &x);
154 newuuid[12] = (char)(x >> 16);
155 newuuid[13] = (char)(x >> 8);
157 newuuid[14] = (char)(counter >> 8);
158 newuuid[15] = (char)(counter);
160 uuid_unparse_lower(newuuid, uuid);
163 /* lock the set of sessions for exclusive access */
164 static inline void sessionset_lock()
166 pthread_mutex_lock(&sessions.mutex);
169 /* unlock the set of sessions of exclusive access */
170 static inline void sessionset_unlock()
172 pthread_mutex_unlock(&sessions.mutex);
176 * search within the set of sessions the session of 'uuid'.
177 * 'hashidx' is the precomputed hash for 'uuid'
178 * return the session or NULL
180 static struct afb_session *sessionset_search(const char *uuid, uint8_t hashidx)
182 struct afb_session *session;
184 session = sessions.heads[hashidx];
185 while (session && strcmp(uuid, session->uuid))
186 session = session->next;
191 /* add 'session' to the set of sessions */
192 static int sessionset_add(struct afb_session *session, uint8_t hashidx)
194 /* check availability */
195 if (sessions.max && sessions.count >= sessions.max) {
200 /* add the session */
201 session->next = sessions.heads[hashidx];
202 sessions.heads[hashidx] = session;
207 /* make a new uuid not used in the set of sessions */
208 static uint8_t sessionset_make_uuid (char uuid[SIZEUUID])
214 hashidx = pearson4(uuid);
215 } while(sessionset_search(uuid, hashidx));
219 /* lock the 'session' for exclusive access */
220 static inline void session_lock(struct afb_session *session)
222 pthread_mutex_lock(&session->mutex);
225 /* unlock the 'session' of exclusive access */
226 static inline void session_unlock(struct afb_session *session)
228 pthread_mutex_unlock(&session->mutex);
231 /* close the 'session' */
232 static void session_close(struct afb_session *session)
235 struct cookie *cookie;
237 /* close only one time */
238 if (!session->closed) {
243 afb_hook_session_close(session);
245 /* release cookies */
246 for (idx = 0 ; idx < COOKIECOUNT ; idx++) {
247 while ((cookie = session->cookies[idx])) {
248 session->cookies[idx] = cookie->next;
249 if (cookie->freecb != NULL)
250 cookie->freecb(cookie->value);
257 /* destroy the 'session' */
258 static void session_destroy (struct afb_session *session)
260 afb_hook_session_destroy(session);
261 pthread_mutex_destroy(&session->mutex);
265 /* update expiration of 'session' according to 'now' */
266 static void session_update_expiration(struct afb_session *session, time_t now)
270 /* compute expiration */
271 expiration = now + afb_session_timeout(session);
273 expiration = MAX_EXPIRATION;
275 /* record the expiration */
276 session->expiration = expiration;
280 * Add a new session with the 'uuid' (of 'hashidx')
281 * and the 'timeout' starting from 'now'.
282 * Add it to the set of sessions
283 * Return the created session
285 static struct afb_session *session_add(const char *uuid, int timeout, time_t now, uint8_t hashidx)
287 struct afb_session *session;
289 /* check arguments */
290 if (!AFB_SESSION_TIMEOUT_IS_VALID(timeout)
291 || (uuid && strlen(uuid) >= sizeof session->uuid)) {
296 /* allocates a new one */
297 session = calloc(1, sizeof *session);
298 if (session == NULL) {
304 pthread_mutex_init(&session->mutex, NULL);
305 session->refcount = 1;
306 strcpy(session->uuid, uuid);
307 strcpy(session->token, sessions.initok);
308 session->timeout = timeout;
309 session_update_expiration(session, now);
312 if (sessionset_add(session, hashidx)) {
317 afb_hook_session_create(session);
322 /* Remove expired sessions and return current time (now) */
323 static time_t sessionset_cleanup (int force)
325 struct afb_session *session, **prv;
329 /* Loop on Sessions Table and remove anything that is older than timeout */
331 for (idx = 0 ; idx < HEADCOUNT; idx++) {
332 prv = &sessions.heads[idx];
333 while ((session = *prv)) {
334 session_lock(session);
335 if (force || session->expiration < now)
336 session_close(session);
337 if (!session->closed)
338 prv = &session->next;
340 *prv = session->next;
342 session->notinset = 1;
343 if ( !session->refcount) {
344 session_destroy(session);
348 session_unlock(session);
355 * Initialize the session manager with a 'max_session_count',
356 * an initial common 'timeout' and an initial common token 'initok'.
358 * @param max_session_count maximum allowed session count in the same time
359 * @param timeout the initial default timeout of sessions
360 * @param initok the initial default token of sessions
363 int afb_session_init (int max_session_count, int timeout, const char *initok)
365 /* check parameters */
366 if (initok && strlen(initok) >= sizeof sessions.initok) {
367 ERROR("initial token '%s' too long (max length %d)",
368 initok, ((int)(sizeof sessions.initok)) - 1);
373 /* init the sessionset (after cleanup) */
375 sessionset_cleanup(1);
376 sessions.max = max_session_count;
377 sessions.timeout = timeout;
379 new_uuid(sessions.initok);
381 strcpy(sessions.initok, initok);
387 * Iterate the sessions and call 'callback' with
388 * the 'closure' for each session.
390 void afb_session_foreach(void (*callback)(void *closure, struct afb_session *session), void *closure)
392 struct afb_session *session;
395 /* Loop on Sessions Table and remove anything that is older than timeout */
397 for (idx = 0 ; idx < HEADCOUNT; idx++) {
398 session = sessions.heads[idx];
400 if (!session->closed)
401 callback(closure, session);
402 session = session->next;
409 * Cleanup the sessionset of its closed or expired sessions
411 void afb_session_purge()
414 sessionset_cleanup(0);
419 * @return the initial token set at initialization
421 const char *afb_session_initial_token()
423 return sessions.initok;
426 /* Searchs the session of 'uuid' */
427 struct afb_session *afb_session_search (const char *uuid)
429 struct afb_session *session;
432 sessionset_cleanup(0);
433 session = sessionset_search(uuid, pearson4(uuid));
434 session = afb_session_addref(session);
441 * Creates a new session with 'timeout'
443 struct afb_session *afb_session_create (int timeout)
445 return afb_session_get(NULL, timeout, NULL);
449 * Returns the timeout of 'session' in seconds
451 int afb_session_timeout(struct afb_session *session)
455 /* compute timeout */
456 timeout = session->timeout;
457 if (timeout == AFB_SESSION_TIMEOUT_DEFAULT)
458 timeout = sessions.timeout;
465 * Returns the second remaining before expiration of 'session'
467 int afb_session_what_remains(struct afb_session *session)
469 return (int)(session->expiration - NOW);
472 /* This function will return exiting session or newly created session */
473 struct afb_session *afb_session_get (const char *uuid, int timeout, int *created)
475 char _uuid_[SIZEUUID];
477 struct afb_session *session;
483 now = sessionset_cleanup(0);
485 /* search for an existing one not too old */
487 hashidx = sessionset_make_uuid(_uuid_);
490 hashidx = pearson4(uuid);
491 session = sessionset_search(uuid, hashidx);
494 afb_session_addref(session);
499 /* create the session */
500 session = session_add(uuid, timeout, now, hashidx);
510 /* increase the use count on 'session' (can be NULL) */
511 struct afb_session *afb_session_addref(struct afb_session *session)
513 if (session != NULL) {
514 afb_hook_session_addref(session);
515 session_lock(session);
517 session_unlock(session);
522 /* decrease the use count of 'session' (can be NULL) */
523 void afb_session_unref(struct afb_session *session)
528 afb_hook_session_unref(session);
529 session_lock(session);
530 if (!--session->refcount) {
531 if (session->autoclose)
532 session_close(session);
533 if (session->notinset) {
534 session_destroy(session);
538 session_unlock(session);
541 /* close 'session' */
542 void afb_session_close (struct afb_session *session)
544 session_lock(session);
545 session_close(session);
546 session_unlock(session);
550 * Set the 'autoclose' flag of the 'session'
552 * A session whose autoclose flag is true will close as
553 * soon as it is no more referenced.
555 * @param session the session to set
556 * @param autoclose the value to set
558 void afb_session_set_autoclose(struct afb_session *session, int autoclose)
560 session->autoclose = !!autoclose;
563 /* is 'session' closed? */
564 int afb_session_is_closed (struct afb_session *session)
566 return session->closed;
570 * check whether the token of 'session' is 'token'
571 * return 1 if true or 0 otherwise
573 int afb_session_check_token (struct afb_session *session, const char *token)
577 session_lock(session);
579 && session->expiration >= NOW
580 && !(session->token[0] && strcmp (token, session->token));
581 session_unlock(session);
585 /* generate a new token and update client context */
586 void afb_session_new_token (struct afb_session *session)
588 session_lock(session);
589 new_uuid(session->token);
590 session_update_expiration(session, NOW);
591 afb_hook_session_renew(session);
592 session_unlock(session);
595 /* Returns the uuid of 'session' */
596 const char *afb_session_uuid (struct afb_session *session)
598 return session->uuid;
601 /* Returns the token of 'session' */
602 const char *afb_session_token (struct afb_session *session)
604 return session->token;
608 * Get the index of the 'key' in the cookies array.
609 * @param key the key to scan
610 * @return the index of the list for key within cookies
612 static int cookeyidx(const void *key)
614 intptr_t x = (intptr_t)key;
615 unsigned r = (unsigned)((x >> 5) ^ (x >> 15));
616 return r & COOKIEMASK;
620 * Set, get, replace, remove a cookie of 'key' for the 'session'
622 * The behaviour of this function depends on its parameters:
624 * @param session the session
625 * @param key the key of the cookie
626 * @param makecb the creation function or NULL
627 * @param freecb the release function or NULL
628 * @param closure an argument for makecb or the value if makecb==NULL
629 * @param replace a boolean enforcing replecement of the previous value
631 * @return the value of the cookie
633 * The 'key' is a pointer and compared as pointers.
635 * For getting the current value of the cookie:
637 * afb_session_cookie(session, key, NULL, NULL, NULL, 0)
639 * For storing the value of the cookie
641 * afb_session_cookie(session, key, NULL, NULL, value, 1)
643 void *afb_session_cookie(struct afb_session *session, const void *key, void *(*makecb)(void *closure), void (*freecb)(void *item), void *closure, int replace)
647 struct cookie *cookie, **prv;
649 /* get key hashed index */
650 idx = cookeyidx(key);
652 /* lock session and search for the cookie of 'key' */
653 session_lock(session);
654 prv = &session->cookies[idx];
658 /* 'key' not found, create value using 'closure' and 'makecb' */
659 value = makecb ? makecb(closure) : closure;
660 /* store the the only if it has some meaning */
661 if (replace || makecb || freecb) {
662 cookie = malloc(sizeof *cookie);
665 /* calling freecb if there is no makecb may have issue */
666 if (makecb && freecb)
671 cookie->value = value;
672 cookie->freecb = freecb;
678 } else if (cookie->key == key) {
679 /* cookie of key found */
681 /* not replacing, get the value */
682 value = cookie->value;
684 /* create value using 'closure' and 'makecb' */
685 value = makecb ? makecb(closure) : closure;
687 /* free previous value is needed */
688 if (cookie->value != value && cookie->freecb)
689 cookie->freecb(cookie->value);
691 /* if both value and freecb are NULL drop the cookie */
692 if (!value && !freecb) {
696 /* store the value and its releaser */
697 cookie->value = value;
698 cookie->freecb = freecb;
703 prv = &(cookie->next);
707 /* unlock the session and return the value */
708 session_unlock(session);
713 * Get the cookie of 'key' in the 'session'.
715 * @param session the session to search in
716 * @param key the key of the data to retrieve
718 * @return the data staored for the key or NULL if the key isn't found
720 void *afb_session_get_cookie(struct afb_session *session, const void *key)
722 return afb_session_cookie(session, key, NULL, NULL, NULL, 0);
726 * Set the cookie of 'key' in the 'session' to the 'value' that can be
727 * cleaned using 'freecb' (if not null).
729 * @param session the session to set
730 * @param key the key of the data to store
731 * @param value the value to store at key
732 * @param freecb a function to use when the cookie value is to remove (or null)
734 * @return 0 in case of success or -1 in case of error
736 int afb_session_set_cookie(struct afb_session *session, const void *key, void *value, void (*freecb)(void*))
738 return -(value != afb_session_cookie(session, key, NULL, freecb, value, 1));