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
53 pthread_mutex_t mutex;
54 char uuid[37]; // long term authentication of remote client
55 char token[37]; // short term authentication of remote client
56 struct cookie *cookies[COOKEYCOUNT];
59 // Session UUID are store in a simple array [for 10 sessions this should be enough]
61 pthread_mutex_t mutex; // declare a mutex to protect hash table
62 struct afb_session **store; // sessions store
63 int count; // current number of sessions
70 * Get the index of the 'key' in the cookies array.
71 * @param key the key to scan
72 * @return the index of the list for key within cookies
74 static int cookeyidx(const void *key)
76 intptr_t x = (intptr_t)key;
77 unsigned r = (unsigned)((x >> 5) ^ (x >> 15));
78 return r & COOKEYMASK;
82 static void new_uuid(char uuid[37])
85 uuid_generate(newuuid);
86 uuid_unparse_lower(newuuid, uuid);
89 static inline void lock(struct afb_session *session)
91 pthread_mutex_lock(&session->mutex);
94 static inline void unlock(struct afb_session *session)
96 pthread_mutex_unlock(&session->mutex);
99 // Free context [XXXX Should be protected again memory abort XXXX]
100 static void remove_all_cookies(struct afb_session *session)
103 struct cookie *cookie, *next;
106 for (idx = 0 ; idx < COOKEYCOUNT ; idx++) {
107 cookie = session->cookies[idx];
108 session->cookies[idx] = NULL;
109 while (cookie != NULL) {
111 if (cookie->freecb != NULL)
112 cookie->freecb(cookie->value);
119 // Create a new store in RAM, not that is too small it will be automatically extended
120 void afb_session_init (int max_session_count, int timeout, const char *initok)
122 // let's create as store as hashtable does not have any
123 sessions.store = calloc (1 + (unsigned)max_session_count, sizeof *sessions.store);
124 pthread_mutex_init(&sessions.mutex, NULL);
125 sessions.max = max_session_count;
126 sessions.timeout = timeout;
128 /* without token, a secret is made to forbid creation of sessions */
129 new_uuid(sessions.initok);
130 else if (strlen(initok) < sizeof(sessions.store[0]->token))
131 strcpy(sessions.initok, initok);
133 ERROR("initial token '%s' too long (max length 36)", initok);
138 const char *afb_session_initial_token()
140 return sessions.initok;
143 static struct afb_session *search (const char* uuid)
146 struct afb_session *session;
148 assert (uuid != NULL);
150 pthread_mutex_lock(&sessions.mutex);
152 for (idx=0; idx < sessions.max; idx++) {
153 session = sessions.store[idx];
154 if (session && (0 == strcmp (uuid, session->uuid)))
160 pthread_mutex_unlock(&sessions.mutex);
164 static int destroy (struct afb_session *session)
169 assert (session != NULL);
171 pthread_mutex_lock(&sessions.mutex);
173 for (idx=0; idx < sessions.max; idx++) {
174 if (sessions.store[idx] == session) {
175 sessions.store[idx] = NULL;
183 pthread_mutex_unlock(&sessions.mutex);
187 static int add (struct afb_session *session)
192 assert (session != NULL);
194 pthread_mutex_lock(&sessions.mutex);
196 for (idx=0; idx < sessions.max; idx++) {
197 if (NULL == sessions.store[idx]) {
198 sessions.store[idx] = session;
206 pthread_mutex_unlock(&sessions.mutex);
210 // Check if context timeout or not
211 static int is_expired (struct afb_session *ctx, time_t now)
213 assert (ctx != NULL);
214 return ctx->expiration < now;
217 // Check if context is active or not
218 static int is_active (struct afb_session *ctx, time_t now)
220 assert (ctx != NULL);
221 return ctx->uuid[0] != 0 && ctx->expiration >= now;
224 // Loop on every entry and remove old context sessions.hash
225 static void cleanup (time_t now)
227 struct afb_session *ctx;
230 // Loop on Sessions Table and remove anything that is older than timeout
231 for (idx=0; idx < sessions.max; idx++) {
232 ctx = sessions.store[idx];
233 if (ctx != NULL && is_expired(ctx, now)) {
234 afb_session_close (ctx);
239 static struct afb_session *make_session (const char *uuid, int timeout, time_t now)
241 struct afb_session *session;
243 /* allocates a new one */
244 session = calloc(1, sizeof *session);
245 if (session == NULL) {
249 pthread_mutex_init(&session->mutex, NULL);
251 /* generate the uuid */
253 do { new_uuid(session->uuid); } while(search(session->uuid));
255 if (strlen(uuid) >= sizeof session->uuid) {
259 strcpy(session->uuid, uuid);
263 strcpy(session->token, sessions.initok);
264 session->timeout = timeout;
266 session->expiration = now + timeout;
268 session->expiration = (time_t)(~(time_t)0);
269 if (session->expiration < 0)
270 session->expiration = (time_t)(((unsigned long long)session->expiration) >> 1);
272 if (!add (session)) {
277 session->access = now;
278 session->refcount = 1;
287 /* Creates a new session with 'timeout' */
288 struct afb_session *afb_session_create (int timeout)
296 return make_session(NULL, timeout, now);
299 /* Searchs the session of 'uuid' */
300 struct afb_session *afb_session_search (const char *uuid)
311 /* This function will return exiting session or newly created session */
312 struct afb_session *afb_session_get (const char *uuid, int *created)
314 struct afb_session *session;
321 /* search for an existing one not too old */
323 session = search(uuid);
324 if (session != NULL) {
327 session->access = now;
333 /* no existing session found, create it */
334 session = make_session(uuid, sessions.timeout, now);
336 *created = !!session;
341 struct afb_session *afb_session_addref(struct afb_session *session)
344 __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
348 void afb_session_unref(struct afb_session *session)
350 if (session != NULL) {
351 assert(session->refcount != 0);
352 if (!__atomic_sub_fetch(&session->refcount, 1, __ATOMIC_RELAXED)) {
353 if (session->uuid[0] == 0) {
355 pthread_mutex_destroy(&session->mutex);
362 // Free Client Session Context
363 void afb_session_close (struct afb_session *session)
365 assert(session != NULL);
366 if (session->uuid[0] != 0) {
367 session->uuid[0] = 0;
368 remove_all_cookies(session);
369 if (session->refcount == 0) {
376 // Sample Generic Ping Debug API
377 int afb_session_check_token (struct afb_session *session, const char *token)
379 assert(session != NULL);
380 assert(token != NULL);
382 // compare current token with previous one
383 if (!is_active (session, NOW))
386 if (session->token[0] && strcmp (token, session->token) != 0)
392 // generate a new token and update client context
393 void afb_session_new_token (struct afb_session *session)
395 assert(session != NULL);
397 // Old token was valid let's regenerate a new one
398 new_uuid(session->token);
400 // keep track of time for session timeout and further clean up
401 if (session->timeout != 0)
402 session->expiration = NOW + session->timeout;
405 /* Returns the uuid of 'session' */
406 const char *afb_session_uuid (struct afb_session *session)
408 assert(session != NULL);
409 return session->uuid;
412 /* Returns the token of 'session' */
413 const char *afb_session_token (struct afb_session *session)
415 assert(session != NULL);
416 return session->token;
419 /* Set, get, replace, remove a cookie key */
420 void *afb_session_cookie(struct afb_session *session, const void *key, void *(*makecb)(void *closure), void (*freecb)(void *item), void *closure, int replace)
424 struct cookie *cookie;
426 idx = cookeyidx(key);
428 cookie = session->cookies[idx];
431 value = makecb ? makecb(closure) : closure;
432 if (replace || makecb || freecb) {
433 cookie = malloc(sizeof *cookie);
441 cookie->value = value;
442 cookie->freecb = freecb;
443 cookie->next = session->cookies[idx];
444 session->cookies[idx] = cookie;
448 } else if (cookie->key == key) {
450 value = cookie->value;
452 value = makecb ? makecb(closure) : closure;
453 if (cookie->value != value && cookie->freecb)
454 cookie->freecb(cookie->value);
455 cookie->value = value;
456 cookie->freecb = freecb;
460 cookie = cookie->next;
467 void *afb_session_get_cookie(struct afb_session *session, const void *key)
469 return afb_session_cookie(session, key, NULL, NULL, NULL, 0);
472 int afb_session_set_cookie(struct afb_session *session, const void *key, void *value, void (*freecb)(void*))
474 return -(value != afb_session_cookie(session, key, NULL, freecb, value, 1));