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"
36 #define COOKEYMASK (COOKEYCOUNT - 1)
38 #define NOW (time(NULL))
45 void (*freecb)(void*);
50 struct afb_session *next; /* link to the next */
53 time_t expiration; // expiration time of the token
54 pthread_mutex_t mutex;
56 char uuid[37]; // long term authentication of remote client
57 char token[37]; // short term authentication of remote client
58 struct cookie *cookies[COOKEYCOUNT];
61 // Session UUID are store in a simple array [for 10 sessions this should be enough]
63 pthread_mutex_t mutex; // declare a mutex to protect hash table
64 struct afb_session *heads[HEADCOUNT]; // sessions
65 int count; // current number of sessions
72 static void new_uuid(char uuid[37])
75 uuid_generate(newuuid);
76 uuid_unparse_lower(newuuid, uuid);
79 static inline void lock(struct afb_session *session)
81 pthread_mutex_lock(&session->mutex);
84 static inline void unlock(struct afb_session *session)
86 pthread_mutex_unlock(&session->mutex);
89 // Free context [XXXX Should be protected again memory abort XXXX]
90 static void remove_all_cookies(struct afb_session *session)
93 struct cookie *cookie, *next;
96 for (idx = 0 ; idx < COOKEYCOUNT ; idx++) {
97 cookie = session->cookies[idx];
98 session->cookies[idx] = NULL;
99 while (cookie != NULL) {
101 if (cookie->freecb != NULL)
102 cookie->freecb(cookie->value);
109 /* tiny hash function inspired from pearson */
110 static int 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 // Create a new store in RAM, not that is too small it will be automatically extended
126 void afb_session_init (int max_session_count, int timeout, const char *initok)
128 pthread_mutex_init(&sessions.mutex, NULL);
129 sessions.max = max_session_count;
130 sessions.timeout = timeout;
132 /* without token, a secret is made to forbid creation of sessions */
133 new_uuid(sessions.initok);
134 else if (strlen(initok) < sizeof sessions.initok)
135 strcpy(sessions.initok, initok);
137 ERROR("initial token '%s' too long (max length %d)", initok, ((int)(sizeof sessions.initok)) - 1);
142 const char *afb_session_initial_token()
144 return sessions.initok;
147 static struct afb_session *search (const char* uuid, int idx)
149 struct afb_session *session;
151 session = sessions.heads[idx];
152 while (session && strcmp(uuid, session->uuid))
153 session = session->next;
158 static void destroy (struct afb_session *session)
160 struct afb_session **prv;
162 assert (session != NULL);
164 pthread_mutex_lock(&sessions.mutex);
165 prv = &sessions.heads[(int)session->idx];
168 prv = &((*prv)->next);
170 *prv = session->next;
172 pthread_mutex_destroy(&session->mutex);
176 pthread_mutex_unlock(&sessions.mutex);
179 // Check if context timeout or not
180 static int is_expired (struct afb_session *ctx, time_t now)
182 assert (ctx != NULL);
183 return ctx->expiration < now;
186 // Check if context is active or not
187 static int is_active (struct afb_session *ctx, time_t now)
189 assert (ctx != NULL);
190 return ctx->uuid[0] != 0 && ctx->expiration >= now;
193 // Loop on every entry and remove old context sessions.hash
194 static time_t cleanup ()
196 struct afb_session *session, *next;
200 // Loop on Sessions Table and remove anything that is older than timeout
202 for (idx = 0 ; idx < HEADCOUNT; idx++) {
203 session = sessions.heads[idx];
205 next = session->next;
206 if (is_expired(session, now))
207 afb_session_close(session);
214 static struct afb_session *add_session (const char *uuid, int timeout, time_t now, int idx)
216 struct afb_session *session;
218 if (!AFB_SESSION_TIMEOUT_IS_VALID(timeout)
219 || (uuid && strlen(uuid) >= sizeof session->uuid)) {
224 if (sessions.count >= sessions.max) {
229 /* allocates a new one */
230 session = calloc(1, sizeof *session);
231 if (session == NULL) {
236 pthread_mutex_init(&session->mutex, NULL);
237 session->refcount = 1;
238 strcpy(session->uuid, uuid);
239 strcpy(session->token, sessions.initok);
242 if (timeout == AFB_SESSION_TIMEOUT_DEFAULT)
243 timeout = sessions.timeout;
244 session->timeout = timeout;
245 session->expiration = now + timeout;
246 if (timeout == AFB_SESSION_TIMEOUT_INFINITE || session->expiration < 0) {
247 session->expiration = (time_t)(~(time_t)0);
248 if (session->expiration < 0)
249 session->expiration = (time_t)(((unsigned long long)session->expiration) >> 1);
252 session->idx = (char)idx;
253 session->next = sessions.heads[idx];
254 sessions.heads[idx] = session;
260 static struct afb_session *new_session (int timeout, time_t now)
267 idx = pearson4(uuid);
268 } while(search(uuid, idx));
269 return add_session(uuid, timeout, now, idx);
272 /* Creates a new session with 'timeout' */
273 struct afb_session *afb_session_create (int timeout)
276 struct afb_session *session;
279 pthread_mutex_lock(&sessions.mutex);
281 session = new_session(timeout, now);
282 pthread_mutex_unlock(&sessions.mutex);
287 /* Searchs the session of 'uuid' */
288 struct afb_session *afb_session_search (const char *uuid)
290 struct afb_session *session;
293 pthread_mutex_lock(&sessions.mutex);
295 session = search(uuid, pearson4(uuid));
296 pthread_mutex_unlock(&sessions.mutex);
301 /* This function will return exiting session or newly created session */
302 struct afb_session *afb_session_get (const char *uuid, int timeout, int *created)
305 struct afb_session *session;
309 pthread_mutex_lock(&sessions.mutex);
312 /* search for an existing one not too old */
314 session = new_session(timeout, now);
316 idx = pearson4(uuid);
317 session = search(uuid, idx);
318 if (session != NULL) {
319 __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
320 pthread_mutex_unlock(&sessions.mutex);
325 session = add_session (uuid, timeout, now, idx);
327 pthread_mutex_unlock(&sessions.mutex);
330 *created = !!session;
335 /* increase the use count on the session */
336 struct afb_session *afb_session_addref(struct afb_session *session)
339 __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
343 /* decrease the use count of the session */
344 void afb_session_unref(struct afb_session *session)
346 if (session != NULL) {
347 assert(session->refcount != 0);
348 if (!__atomic_sub_fetch(&session->refcount, 1, __ATOMIC_RELAXED)) {
349 if (session->uuid[0] == 0)
355 // Free Client Session Context
356 void afb_session_close (struct afb_session *session)
358 assert(session != NULL);
359 if (session->uuid[0] != 0) {
360 session->uuid[0] = 0;
361 remove_all_cookies(session);
362 if (session->refcount == 0)
367 // Sample Generic Ping Debug API
368 int afb_session_check_token (struct afb_session *session, const char *token)
370 assert(session != NULL);
371 assert(token != NULL);
373 // compare current token with previous one
374 if (!is_active (session, NOW))
377 if (session->token[0] && strcmp (token, session->token) != 0)
383 // generate a new token and update client context
384 void afb_session_new_token (struct afb_session *session)
386 assert(session != NULL);
388 // Old token was valid let's regenerate a new one
389 new_uuid(session->token);
391 // keep track of time for session timeout and further clean up
392 if (session->timeout != 0)
393 session->expiration = NOW + session->timeout;
396 /* Returns the uuid of 'session' */
397 const char *afb_session_uuid (struct afb_session *session)
399 assert(session != NULL);
400 return session->uuid;
403 /* Returns the token of 'session' */
404 const char *afb_session_token (struct afb_session *session)
406 assert(session != NULL);
407 return session->token;
411 * Get the index of the 'key' in the cookies array.
412 * @param key the key to scan
413 * @return the index of the list for key within cookies
415 static int cookeyidx(const void *key)
417 intptr_t x = (intptr_t)key;
418 unsigned r = (unsigned)((x >> 5) ^ (x >> 15));
419 return r & COOKEYMASK;
423 * Set, get, replace, remove a cookie of 'key' for the 'session'
425 * The behaviour of this function depends on its parameters:
427 * @param session the session
428 * @param key the key of the cookie
429 * @param makecb the creation function
430 * @param freecb the release function
431 * @param closure an argument
432 * @param replace a boolean enforcing replecement of the previous value
434 * @return the value of the cookie
436 * The 'key' is a pointer and compared as pointers.
438 * For getting the current value of the cookie:
440 * afb_session_cookie(session, key, NULL, NULL, NULL, 0)
442 * For storing the value of the cookie
444 * afb_session_cookie(session, key, NULL, NULL, value, 1)
446 void *afb_session_cookie(struct afb_session *session, const void *key, void *(*makecb)(void *closure), void (*freecb)(void *item), void *closure, int replace)
450 struct cookie *cookie, **prv;
452 /* get key hashed index */
453 idx = cookeyidx(key);
455 /* lock session and search for the cookie of 'key' */
457 prv = &session->cookies[idx];
461 /* 'key' not found, create value using 'closure' and 'makecb' */
462 value = makecb ? makecb(closure) : closure;
463 /* store the the only if it has some meaning */
464 if (replace || makecb || freecb) {
465 cookie = malloc(sizeof *cookie);
468 /* calling freecb if there is no makecb may have issue */
469 if (makecb && freecb)
474 cookie->value = value;
475 cookie->freecb = freecb;
481 } else if (cookie->key == key) {
482 /* cookie of key found */
484 /* not replacing, get the value */
485 value = cookie->value;
487 /* create value using 'closure' and 'makecb' */
488 value = makecb ? makecb(closure) : closure;
490 /* free previous value is needed */
491 if (cookie->value != value && cookie->freecb)
492 cookie->freecb(cookie->value);
494 /* store the value and its releaser */
495 cookie->value = value;
496 cookie->freecb = freecb;
498 /* but if both are NULL drop the cookie */
499 if (!value && !freecb) {
506 prv = &(cookie->next);
510 /* unlock the session and return the value */
515 void *afb_session_get_cookie(struct afb_session *session, const void *key)
517 return afb_session_cookie(session, key, NULL, NULL, NULL, 0);
520 int afb_session_set_cookie(struct afb_session *session, const void *key, void *value, void (*freecb)(void*))
522 return -(value != afb_session_cookie(session, key, NULL, freecb, value, 1));