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"
35 #define COOKEYMASK (COOKEYCOUNT - 1)
37 #define NOW (time(NULL))
44 void (*freecb)(void*);
51 time_t expiration; // expiration time of the token
52 pthread_mutex_t mutex;
53 char uuid[37]; // long term authentication of remote client
54 char token[37]; // short term authentication of remote client
55 struct cookie *cookies[COOKEYCOUNT];
58 // Session UUID are store in a simple array [for 10 sessions this should be enough]
60 pthread_mutex_t mutex; // declare a mutex to protect hash table
61 struct afb_session **store; // sessions store
62 int count; // current number of sessions
69 * Get the index of the 'key' in the cookies array.
70 * @param key the key to scan
71 * @return the index of the list for key within cookies
73 static int cookeyidx(const void *key)
75 intptr_t x = (intptr_t)key;
76 unsigned r = (unsigned)((x >> 5) ^ (x >> 15));
77 return r & COOKEYMASK;
81 static void new_uuid(char uuid[37])
84 uuid_generate(newuuid);
85 uuid_unparse_lower(newuuid, uuid);
88 static inline void lock(struct afb_session *session)
90 pthread_mutex_lock(&session->mutex);
93 static inline void unlock(struct afb_session *session)
95 pthread_mutex_unlock(&session->mutex);
98 // Free context [XXXX Should be protected again memory abort XXXX]
99 static void remove_all_cookies(struct afb_session *session)
102 struct cookie *cookie, *next;
105 for (idx = 0 ; idx < COOKEYCOUNT ; idx++) {
106 cookie = session->cookies[idx];
107 session->cookies[idx] = NULL;
108 while (cookie != NULL) {
110 if (cookie->freecb != NULL)
111 cookie->freecb(cookie->value);
118 // Create a new store in RAM, not that is too small it will be automatically extended
119 void afb_session_init (int max_session_count, int timeout, const char *initok)
121 // let's create as store as hashtable does not have any
122 sessions.store = calloc (1 + (unsigned)max_session_count, sizeof *sessions.store);
123 pthread_mutex_init(&sessions.mutex, NULL);
124 sessions.max = max_session_count;
125 sessions.timeout = timeout;
127 /* without token, a secret is made to forbid creation of sessions */
128 new_uuid(sessions.initok);
129 else if (strlen(initok) < sizeof(sessions.store[0]->token))
130 strcpy(sessions.initok, initok);
132 ERROR("initial token '%s' too long (max length 36)", initok);
137 const char *afb_session_initial_token()
139 return sessions.initok;
142 static struct afb_session *search (const char* uuid)
145 struct afb_session *session;
147 assert (uuid != NULL);
149 pthread_mutex_lock(&sessions.mutex);
151 for (idx=0; idx < sessions.max; idx++) {
152 session = sessions.store[idx];
153 if (session && (0 == strcmp (uuid, session->uuid)))
159 pthread_mutex_unlock(&sessions.mutex);
163 static int destroy (struct afb_session *session)
168 assert (session != NULL);
170 pthread_mutex_lock(&sessions.mutex);
172 for (idx=0; idx < sessions.max; idx++) {
173 if (sessions.store[idx] == session) {
174 sessions.store[idx] = NULL;
182 pthread_mutex_unlock(&sessions.mutex);
186 static int add (struct afb_session *session)
191 assert (session != NULL);
193 pthread_mutex_lock(&sessions.mutex);
195 for (idx=0; idx < sessions.max; idx++) {
196 if (NULL == sessions.store[idx]) {
197 sessions.store[idx] = session;
205 pthread_mutex_unlock(&sessions.mutex);
209 // Check if context timeout or not
210 static int is_expired (struct afb_session *ctx, time_t now)
212 assert (ctx != NULL);
213 return ctx->expiration < now;
216 // Check if context is active or not
217 static int is_active (struct afb_session *ctx, time_t now)
219 assert (ctx != NULL);
220 return ctx->uuid[0] != 0 && ctx->expiration >= now;
223 // Loop on every entry and remove old context sessions.hash
224 static void cleanup (time_t now)
226 struct afb_session *ctx;
229 // Loop on Sessions Table and remove anything that is older than timeout
230 for (idx=0; idx < sessions.max; idx++) {
231 ctx = sessions.store[idx];
232 if (ctx != NULL && is_expired(ctx, now)) {
233 afb_session_close (ctx);
238 static struct afb_session *make_session (const char *uuid, int timeout, time_t now)
240 struct afb_session *session;
242 if (!AFB_SESSION_TIMEOUT_IS_VALID(timeout)
243 || (uuid && strlen(uuid) >= sizeof session->uuid)) {
248 /* allocates a new one */
249 session = calloc(1, sizeof *session);
250 if (session == NULL) {
254 pthread_mutex_init(&session->mutex, NULL);
256 /* generate the uuid */
258 do { new_uuid(session->uuid); } while(search(session->uuid));
260 strcpy(session->uuid, uuid);
264 strcpy(session->token, sessions.initok);
267 if (timeout == AFB_SESSION_TIMEOUT_DEFAULT)
268 timeout = sessions.timeout;
269 session->timeout = timeout;
270 session->expiration = now + timeout;
271 if (timeout == AFB_SESSION_TIMEOUT_INFINITE || session->expiration < 0) {
272 session->expiration = (time_t)(~(time_t)0);
273 if (session->expiration < 0)
274 session->expiration = (time_t)(((unsigned long long)session->expiration) >> 1);
276 if (!add (session)) {
281 session->refcount = 1;
290 /* Creates a new session with 'timeout' */
291 struct afb_session *afb_session_create (int timeout)
299 return make_session(NULL, timeout, now);
302 /* Searchs the session of 'uuid' */
303 struct afb_session *afb_session_search (const char *uuid)
306 struct afb_session *session;
311 session = search(uuid);
316 /* This function will return exiting session or newly created session */
317 struct afb_session *afb_session_get (const char *uuid, int timeout, int *created)
319 struct afb_session *session;
326 /* search for an existing one not too old */
328 session = search(uuid);
329 if (session != NULL) {
337 /* no existing session found, create it */
338 session = make_session(uuid, timeout, now);
340 *created = !!session;
345 struct afb_session *afb_session_addref(struct afb_session *session)
348 __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
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 if (session->uuid[0] == 0) {
359 pthread_mutex_destroy(&session->mutex);
366 // Free Client Session Context
367 void afb_session_close (struct afb_session *session)
369 assert(session != NULL);
370 if (session->uuid[0] != 0) {
371 session->uuid[0] = 0;
372 remove_all_cookies(session);
373 if (session->refcount == 0) {
380 // Sample Generic Ping Debug API
381 int afb_session_check_token (struct afb_session *session, const char *token)
383 assert(session != NULL);
384 assert(token != NULL);
386 // compare current token with previous one
387 if (!is_active (session, NOW))
390 if (session->token[0] && strcmp (token, session->token) != 0)
396 // generate a new token and update client context
397 void afb_session_new_token (struct afb_session *session)
399 assert(session != NULL);
401 // Old token was valid let's regenerate a new one
402 new_uuid(session->token);
404 // keep track of time for session timeout and further clean up
405 if (session->timeout != 0)
406 session->expiration = NOW + session->timeout;
409 /* Returns the uuid of 'session' */
410 const char *afb_session_uuid (struct afb_session *session)
412 assert(session != NULL);
413 return session->uuid;
416 /* Returns the token of 'session' */
417 const char *afb_session_token (struct afb_session *session)
419 assert(session != NULL);
420 return session->token;
423 /* Set, get, replace, remove a cookie key */
424 void *afb_session_cookie(struct afb_session *session, const void *key, void *(*makecb)(void *closure), void (*freecb)(void *item), void *closure, int replace)
428 struct cookie *cookie;
430 idx = cookeyidx(key);
432 cookie = session->cookies[idx];
435 value = makecb ? makecb(closure) : closure;
436 if (replace || makecb || freecb) {
437 cookie = malloc(sizeof *cookie);
445 cookie->value = value;
446 cookie->freecb = freecb;
447 cookie->next = session->cookies[idx];
448 session->cookies[idx] = cookie;
452 } else if (cookie->key == key) {
454 value = cookie->value;
456 value = makecb ? makecb(closure) : closure;
457 if (cookie->value != value && cookie->freecb)
458 cookie->freecb(cookie->value);
459 cookie->value = value;
460 cookie->freecb = freecb;
464 cookie = cookie->next;
471 void *afb_session_get_cookie(struct afb_session *session, const void *key)
473 return afb_session_cookie(session, key, NULL, NULL, NULL, 0);
476 int afb_session_set_cookie(struct afb_session *session, const void *key, void *value, void (*freecb)(void*))
478 return -(value != afb_session_cookie(session, key, NULL, freecb, value, 1));