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 _MAXEXP_ ((time_t)(~(time_t)0))
40 #define _MAXEXP2_ ((time_t)((((unsigned long long)_MAXEXP_) >> 1)))
41 #define MAX_EXPIRATION (_MAXEXP_ >= 0 ? _MAXEXP_ : _MAXEXP2_)
42 #define NOW (time(NULL))
49 void (*freecb)(void*);
54 struct afb_session *next; /* link to the next */
57 time_t expiration; // expiration time of the token
58 pthread_mutex_t mutex;
59 struct cookie *cookies[COOKEYCOUNT];
61 char uuid[SIZEUUID]; // long term authentication of remote client
62 char token[SIZEUUID]; // short term authentication of remote client
65 // Session UUID are store in a simple array [for 10 sessions this should be enough]
67 pthread_mutex_t mutex; // declare a mutex to protect hash table
68 struct afb_session *heads[HEADCOUNT]; // sessions
69 int count; // current number of sessions
72 char initok[SIZEUUID];
76 static void new_uuid(char uuid[SIZEUUID])
79 uuid_generate(newuuid);
80 uuid_unparse_lower(newuuid, uuid);
83 static inline void lock(struct afb_session *session)
85 pthread_mutex_lock(&session->mutex);
88 static inline void unlock(struct afb_session *session)
90 pthread_mutex_unlock(&session->mutex);
93 // Free context [XXXX Should be protected again memory abort XXXX]
94 static void close_session(struct afb_session *session)
97 struct cookie *cookie;
100 for (idx = 0 ; idx < COOKEYCOUNT ; idx++) {
101 while ((cookie = session->cookies[idx])) {
102 session->cookies[idx] = cookie->next;
103 if (cookie->freecb != NULL)
104 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 close_session(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 // Loop on every entry and remove old context sessions.hash
182 static time_t cleanup ()
184 struct afb_session *session, *next;
188 // Loop on Sessions Table and remove anything that is older than timeout
190 for (idx = 0 ; idx < HEADCOUNT; idx++) {
191 session = sessions.heads[idx];
193 next = session->next;
194 if (session->expiration < now)
195 afb_session_close(session);
202 static void update_timeout(struct afb_session *session, time_t now, int timeout)
206 /* compute expiration */
207 if (timeout == AFB_SESSION_TIMEOUT_INFINITE)
208 expiration = MAX_EXPIRATION;
210 if (timeout == AFB_SESSION_TIMEOUT_DEFAULT)
211 expiration = now + sessions.timeout;
213 expiration = now + timeout;
215 expiration = MAX_EXPIRATION;
218 /* record the values */
219 session->timeout = timeout;
220 session->expiration = expiration;
223 static void update_expiration(struct afb_session *session, time_t now)
225 update_timeout(session, now, session->timeout);
228 static struct afb_session *add_session (const char *uuid, int timeout, time_t now, int idx)
230 struct afb_session *session;
232 /* check arguments */
233 if (!AFB_SESSION_TIMEOUT_IS_VALID(timeout)
234 || (uuid && strlen(uuid) >= sizeof session->uuid)) {
239 /* check session count */
240 if (sessions.count >= sessions.max) {
245 /* allocates a new one */
246 session = calloc(1, sizeof *session);
247 if (session == NULL) {
253 pthread_mutex_init(&session->mutex, NULL);
254 session->refcount = 1;
255 strcpy(session->uuid, uuid);
256 strcpy(session->token, sessions.initok);
257 update_timeout(session, now, timeout);
260 session->idx = (char)idx;
261 session->next = sessions.heads[idx];
262 sessions.heads[idx] = session;
268 /* create a new session for the given timeout */
269 static struct afb_session *new_session (int timeout, time_t now)
276 idx = pearson4(uuid);
277 } while(search(uuid, idx));
278 return add_session(uuid, timeout, now, idx);
281 /* Creates a new session with 'timeout' */
282 struct afb_session *afb_session_create (int timeout)
285 struct afb_session *session;
288 pthread_mutex_lock(&sessions.mutex);
290 session = new_session(timeout, now);
291 pthread_mutex_unlock(&sessions.mutex);
296 /* Searchs the session of 'uuid' */
297 struct afb_session *afb_session_search (const char *uuid)
299 struct afb_session *session;
302 pthread_mutex_lock(&sessions.mutex);
304 session = search(uuid, pearson4(uuid));
306 __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
307 pthread_mutex_unlock(&sessions.mutex);
312 /* This function will return exiting session or newly created session */
313 struct afb_session *afb_session_get (const char *uuid, int timeout, int *created)
316 struct afb_session *session;
320 pthread_mutex_lock(&sessions.mutex);
323 /* search for an existing one not too old */
325 session = new_session(timeout, now);
327 idx = pearson4(uuid);
328 session = search(uuid, idx);
330 __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
331 pthread_mutex_unlock(&sessions.mutex);
336 session = add_session (uuid, timeout, now, idx);
338 pthread_mutex_unlock(&sessions.mutex);
341 *created = !!session;
346 /* increase the use count on the session */
347 struct afb_session *afb_session_addref(struct afb_session *session)
350 __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
354 /* decrease the use count of the session */
355 void afb_session_unref(struct afb_session *session)
357 if (session != NULL) {
358 assert(session->refcount != 0);
359 if (!__atomic_sub_fetch(&session->refcount, 1, __ATOMIC_RELAXED)) {
360 pthread_mutex_lock(&session->mutex);
361 if (session->uuid[0] == 0)
364 pthread_mutex_unlock(&session->mutex);
369 // close Client Session Context
370 void afb_session_close (struct afb_session *session)
372 assert(session != NULL);
373 pthread_mutex_lock(&session->mutex);
374 if (session->uuid[0] != 0) {
375 session->uuid[0] = 0;
376 if (session->refcount)
377 close_session(session);
383 pthread_mutex_unlock(&session->mutex);
386 // is the session active?
387 int afb_session_is_active (struct afb_session *session)
389 assert(session != NULL);
390 return !!session->uuid[0];
393 // is the session closed?
394 int afb_session_is_closed (struct afb_session *session)
396 assert(session != NULL);
397 return !session->uuid[0];
400 // Sample Generic Ping Debug API
401 int afb_session_check_token (struct afb_session *session, const char *token)
403 assert(session != NULL);
404 assert(token != NULL);
406 if (!session->uuid[0])
409 if (session->expiration < NOW)
412 if (session->token[0] && strcmp (token, session->token) != 0)
418 // generate a new token and update client context
419 void afb_session_new_token (struct afb_session *session)
421 assert(session != NULL);
423 // Old token was valid let's regenerate a new one
424 new_uuid(session->token);
426 // keep track of time for session timeout and further clean up
427 update_expiration(session, NOW);
430 /* Returns the uuid of 'session' */
431 const char *afb_session_uuid (struct afb_session *session)
433 assert(session != NULL);
434 return session->uuid;
437 /* Returns the token of 'session' */
438 const char *afb_session_token (struct afb_session *session)
440 assert(session != NULL);
441 return session->token;
445 * Get the index of the 'key' in the cookies array.
446 * @param key the key to scan
447 * @return the index of the list for key within cookies
449 static int cookeyidx(const void *key)
451 intptr_t x = (intptr_t)key;
452 unsigned r = (unsigned)((x >> 5) ^ (x >> 15));
453 return r & COOKEYMASK;
457 * Set, get, replace, remove a cookie of 'key' for the 'session'
459 * The behaviour of this function depends on its parameters:
461 * @param session the session
462 * @param key the key of the cookie
463 * @param makecb the creation function or NULL
464 * @param freecb the release function or NULL
465 * @param closure an argument for makecb or the value if makecb==NULL
466 * @param replace a boolean enforcing replecement of the previous value
468 * @return the value of the cookie
470 * The 'key' is a pointer and compared as pointers.
472 * For getting the current value of the cookie:
474 * afb_session_cookie(session, key, NULL, NULL, NULL, 0)
476 * For storing the value of the cookie
478 * afb_session_cookie(session, key, NULL, NULL, value, 1)
480 void *afb_session_cookie(struct afb_session *session, const void *key, void *(*makecb)(void *closure), void (*freecb)(void *item), void *closure, int replace)
484 struct cookie *cookie, **prv;
486 /* get key hashed index */
487 idx = cookeyidx(key);
489 /* lock session and search for the cookie of 'key' */
491 prv = &session->cookies[idx];
495 /* 'key' not found, create value using 'closure' and 'makecb' */
496 value = makecb ? makecb(closure) : closure;
497 /* store the the only if it has some meaning */
498 if (replace || makecb || freecb) {
499 cookie = malloc(sizeof *cookie);
502 /* calling freecb if there is no makecb may have issue */
503 if (makecb && freecb)
508 cookie->value = value;
509 cookie->freecb = freecb;
515 } else if (cookie->key == key) {
516 /* cookie of key found */
518 /* not replacing, get the value */
519 value = cookie->value;
521 /* create value using 'closure' and 'makecb' */
522 value = makecb ? makecb(closure) : closure;
524 /* free previous value is needed */
525 if (cookie->value != value && cookie->freecb)
526 cookie->freecb(cookie->value);
528 /* store the value and its releaser */
529 cookie->value = value;
530 cookie->freecb = freecb;
532 /* but if both are NULL drop the cookie */
533 if (!value && !freecb) {
540 prv = &(cookie->next);
544 /* unlock the session and return the value */
549 void *afb_session_get_cookie(struct afb_session *session, const void *key)
551 return afb_session_cookie(session, key, NULL, NULL, NULL, 0);
554 int afb_session_set_cookie(struct afb_session *session, const void *key, void *value, void (*freecb)(void*))
556 return -(value != afb_session_cookie(session, key, NULL, freecb, value, 1));