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;
56 struct cookie *cookies[COOKEYCOUNT];
58 char uuid[SIZEUUID]; // long term authentication of remote client
59 char token[SIZEUUID]; // short term authentication of remote client
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 close_session(struct afb_session *session)
94 struct cookie *cookie;
97 for (idx = 0 ; idx < COOKEYCOUNT ; idx++) {
98 while ((cookie = session->cookies[idx])) {
99 session->cookies[idx] = cookie->next;
100 if (cookie->freecb != NULL)
101 cookie->freecb(cookie->value);
107 /* tiny hash function inspired from pearson */
108 static int pearson4(const char *text)
110 static uint8_t T[16] = {
111 4, 1, 6, 0, 9, 14, 11, 5,
112 2, 3, 12, 15, 10, 7, 8, 13
116 for (r = 0; (c = (uint8_t)*text) ; text++) {
120 return r; // % HEADCOUNT;
123 // Create a new store in RAM, not that is too small it will be automatically extended
124 void afb_session_init (int max_session_count, int timeout, const char *initok)
126 pthread_mutex_init(&sessions.mutex, NULL);
127 sessions.max = max_session_count;
128 sessions.timeout = timeout;
130 /* without token, a secret is made to forbid creation of sessions */
131 new_uuid(sessions.initok);
132 else if (strlen(initok) < sizeof sessions.initok)
133 strcpy(sessions.initok, initok);
135 ERROR("initial token '%s' too long (max length %d)", initok, ((int)(sizeof sessions.initok)) - 1);
140 const char *afb_session_initial_token()
142 return sessions.initok;
145 static struct afb_session *search (const char* uuid, int idx)
147 struct afb_session *session;
149 session = sessions.heads[idx];
150 while (session && strcmp(uuid, session->uuid))
151 session = session->next;
156 static void destroy (struct afb_session *session)
158 struct afb_session **prv;
160 assert (session != NULL);
162 close_session(session);
163 pthread_mutex_lock(&sessions.mutex);
164 prv = &sessions.heads[(int)session->idx];
167 prv = &((*prv)->next);
169 *prv = session->next;
171 pthread_mutex_destroy(&session->mutex);
175 pthread_mutex_unlock(&sessions.mutex);
178 // Check if context timeout or not
179 static int is_expired (struct afb_session *ctx, time_t now)
181 assert (ctx != NULL);
182 return ctx->expiration < now;
185 // Check if context is active or not
186 static int is_active (struct afb_session *ctx, time_t now)
188 assert (ctx != NULL);
189 return ctx->uuid[0] != 0 && ctx->expiration >= now;
192 // Loop on every entry and remove old context sessions.hash
193 static time_t cleanup ()
195 struct afb_session *session, *next;
199 // Loop on Sessions Table and remove anything that is older than timeout
201 for (idx = 0 ; idx < HEADCOUNT; idx++) {
202 session = sessions.heads[idx];
204 next = session->next;
205 if (is_expired(session, now))
206 afb_session_close(session);
213 static struct afb_session *add_session (const char *uuid, int timeout, time_t now, int idx)
215 struct afb_session *session;
218 /* check arguments */
219 if (!AFB_SESSION_TIMEOUT_IS_VALID(timeout)
220 || (uuid && strlen(uuid) >= sizeof session->uuid)) {
225 /* check session count */
226 if (sessions.count >= sessions.max) {
231 /* compute expiration */
232 if (timeout == AFB_SESSION_TIMEOUT_DEFAULT)
233 timeout = sessions.timeout;
234 expiration = now + timeout;
235 if (timeout == AFB_SESSION_TIMEOUT_INFINITE || expiration < 0) {
236 expiration = (time_t)(~(time_t)0);
238 expiration = (time_t)(((unsigned long long)expiration) >> 1);
241 /* allocates a new one */
242 session = calloc(1, sizeof *session);
243 if (session == NULL) {
249 pthread_mutex_init(&session->mutex, NULL);
250 session->refcount = 1;
251 strcpy(session->uuid, uuid);
252 strcpy(session->token, sessions.initok);
253 session->timeout = timeout;
254 session->expiration = expiration;
257 session->idx = (char)idx;
258 session->next = sessions.heads[idx];
259 sessions.heads[idx] = session;
265 /* create a new session for the given timeout */
266 static struct afb_session *new_session (int timeout, time_t now)
273 idx = pearson4(uuid);
274 } while(search(uuid, idx));
275 return add_session(uuid, timeout, now, idx);
278 /* Creates a new session with 'timeout' */
279 struct afb_session *afb_session_create (int timeout)
282 struct afb_session *session;
285 pthread_mutex_lock(&sessions.mutex);
287 session = new_session(timeout, now);
288 pthread_mutex_unlock(&sessions.mutex);
293 /* Searchs the session of 'uuid' */
294 struct afb_session *afb_session_search (const char *uuid)
296 struct afb_session *session;
299 pthread_mutex_lock(&sessions.mutex);
301 session = search(uuid, pearson4(uuid));
303 __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
304 pthread_mutex_unlock(&sessions.mutex);
309 /* This function will return exiting session or newly created session */
310 struct afb_session *afb_session_get (const char *uuid, int timeout, int *created)
313 struct afb_session *session;
317 pthread_mutex_lock(&sessions.mutex);
320 /* search for an existing one not too old */
322 session = new_session(timeout, now);
324 idx = pearson4(uuid);
325 session = search(uuid, idx);
327 __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
328 pthread_mutex_unlock(&sessions.mutex);
333 session = add_session (uuid, timeout, now, idx);
335 pthread_mutex_unlock(&sessions.mutex);
338 *created = !!session;
343 /* increase the use count on the session */
344 struct afb_session *afb_session_addref(struct afb_session *session)
347 __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
351 /* decrease the use count of the session */
352 void afb_session_unref(struct afb_session *session)
354 if (session != NULL) {
355 assert(session->refcount != 0);
356 if (!__atomic_sub_fetch(&session->refcount, 1, __ATOMIC_RELAXED)) {
357 pthread_mutex_lock(&session->mutex);
358 if (session->uuid[0] == 0)
361 pthread_mutex_unlock(&session->mutex);
366 // Free Client Session Context
367 void afb_session_close (struct afb_session *session)
369 assert(session != NULL);
370 pthread_mutex_lock(&session->mutex);
371 if (session->uuid[0] != 0) {
372 session->uuid[0] = 0;
373 if (session->refcount)
374 close_session(session);
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));