afb-session: Add function to enumerate sessions
[src/app-framework-binder.git] / src / afb-session.c
1 /*
2  * Copyright (C) 2015, 2016, 2017 "IoT.bzh"
3  * Author "Fulup Ar Foll"
4  * Author: José Bollo <jose.bollo@iot.bzh>
5  *
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
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  */
18
19 #define _GNU_SOURCE
20 #include <stdio.h>
21 #include <time.h>
22 #include <pthread.h>
23 #include <stdlib.h>
24 #include <stdint.h>
25 #include <string.h>
26 #include <uuid/uuid.h>
27 #include <errno.h>
28
29 #include <json-c/json.h>
30
31 #include "afb-session.h"
32 #include "afb-hook.h"
33 #include "verbose.h"
34
35 #define SIZEUUID        37
36 #define HEADCOUNT       16
37 #define COOKIECOUNT     8
38 #define COOKIEMASK      (COOKIECOUNT - 1)
39
40 #define _MAXEXP_        ((time_t)(~(time_t)0))
41 #define _MAXEXP2_       ((time_t)((((unsigned long long)_MAXEXP_) >> 1)))
42 #define MAX_EXPIRATION  (_MAXEXP_ >= 0 ? _MAXEXP_ : _MAXEXP2_)
43 #define NOW             (time(NULL))
44
45 /* structure for a cookie added to sessions */
46 struct cookie
47 {
48         struct cookie *next;    /* link to next cookie */
49         const void *key;        /* pointer key */
50         void *value;            /* value */
51         void (*freecb)(void*);  /* function to call when session is closed */
52 };
53
54 /*
55  * structure for session
56  */
57 struct afb_session
58 {
59         struct afb_session *next; /* link to the next */
60         unsigned refcount;      /* external reference count of the session */
61         int timeout;            /* timeout of the session */
62         time_t expiration;      /* expiration time of the token */
63         pthread_mutex_t mutex;  /* mutex of the session */
64         struct cookie *cookies[COOKIECOUNT]; /* cookies of the session */
65         uint8_t closed: 1;      /* is the session closed ? */
66         uint8_t autoclose: 1;   /* close the session when unreferenced */
67         uint8_t notinset: 1;    /* session removed from the set of sessions */
68         char uuid[SIZEUUID];    /* long term authentication of remote client */
69         char token[SIZEUUID];   /* short term authentication of remote client */
70 };
71
72 /* Session UUID are store in a simple array [for 10 sessions this should be enough] */
73 static struct {
74         int count;              /* current number of sessions */
75         int max;                /* maximum count of sessions */
76         int timeout;            /* common initial timeout */
77         struct afb_session *heads[HEADCOUNT]; /* sessions */
78         char initok[SIZEUUID];  /* common initial token */
79         pthread_mutex_t mutex;  /* declare a mutex to protect hash table */
80 } sessions = {
81         .count = 0,
82         .max = 10,
83         .timeout = 3600,
84         .heads = { 0 },
85         .initok = { 0 },
86         .mutex = PTHREAD_MUTEX_INITIALIZER
87 };
88
89 /* generate a new fresh 'uuid' */
90 static void new_uuid(char uuid[SIZEUUID])
91 {
92         uuid_t newuuid;
93         uuid_generate(newuuid);
94         uuid_unparse_lower(newuuid, uuid);
95 }
96
97 /*
98  * Returns a tiny hash value for the 'text'.
99  *
100  * Tiny hash function inspired from pearson
101  */
102 static uint8_t pearson4(const char *text)
103 {
104         static uint8_t T[16] = {
105                  4,  1,  6,  0,  9, 14, 11,  5,
106                  2,  3, 12, 15, 10,  7,  8, 13
107         };
108         uint8_t r, c;
109
110         for (r = 0; (c = (uint8_t)*text) ; text++) {
111                 r = T[r ^ (15 & c)];
112                 r = T[r ^ (c >> 4)];
113         }
114         return r; // % HEADCOUNT;
115 }
116
117 /* lock the set of sessions for exclusive access */
118 static inline void sessionset_lock()
119 {
120         pthread_mutex_lock(&sessions.mutex);
121 }
122
123 /* unlock the set of sessions of exclusive access */
124 static inline void sessionset_unlock()
125 {
126         pthread_mutex_unlock(&sessions.mutex);
127 }
128
129 /*
130  * search within the set of sessions the session of 'uuid'.
131  * 'hashidx' is the precomputed hash for 'uuid'
132  * return the session or NULL
133  */
134 static struct afb_session *sessionset_search(const char *uuid, uint8_t hashidx)
135 {
136         struct afb_session *session;
137
138         session = sessions.heads[hashidx];
139         while (session && strcmp(uuid, session->uuid))
140                 session = session->next;
141
142         return session;
143 }
144
145 /* add 'session' to the set of sessions */
146 static int sessionset_add(struct afb_session *session, uint8_t hashidx)
147 {
148         /* check availability */
149         if (sessions.count >= sessions.max) {
150                 errno = EBUSY;
151                 return -1;
152         }
153
154         /* add the session */
155         session->next = sessions.heads[hashidx];
156         sessions.heads[hashidx] = session;
157         sessions.count++;
158         return 0;
159 }
160
161 /* make a new uuid not used in the set of sessions */
162 static uint8_t sessionset_make_uuid (char uuid[SIZEUUID])
163 {
164         uint8_t hashidx;
165
166         do {
167                 new_uuid(uuid);
168                 hashidx = pearson4(uuid);
169         } while(sessionset_search(uuid, hashidx));
170         return hashidx;
171 }
172
173 /* lock the 'session' for exclusive access */
174 static inline void session_lock(struct afb_session *session)
175 {
176         pthread_mutex_lock(&session->mutex);
177 }
178
179 /* unlock the 'session' of exclusive access */
180 static inline void session_unlock(struct afb_session *session)
181 {
182         pthread_mutex_unlock(&session->mutex);
183 }
184
185 /* close the 'session' */
186 static void session_close(struct afb_session *session)
187 {
188         int idx;
189         struct cookie *cookie;
190
191         /* close only one time */
192         if (!session->closed) {
193                 /* close it now */
194                 session->closed = 1;
195
196                 /* emit the hook */
197                 afb_hook_session_close(session);
198
199                 /* release cookies */
200                 for (idx = 0 ; idx < COOKIECOUNT ; idx++) {
201                         while ((cookie = session->cookies[idx])) {
202                                 session->cookies[idx] = cookie->next;
203                                 if (cookie->freecb != NULL)
204                                         cookie->freecb(cookie->value);
205                                 free(cookie);
206                         }
207                 }
208         }
209 }
210
211 /* destroy the 'session' */
212 static void session_destroy (struct afb_session *session)
213 {
214         afb_hook_session_destroy(session);
215         pthread_mutex_destroy(&session->mutex);
216         free(session);
217 }
218
219 /* update expiration of 'session' according to 'now' */
220 static void session_update_expiration(struct afb_session *session, time_t now)
221 {
222         int timeout;
223         time_t expiration;
224
225         /* compute expiration */
226         timeout = session->timeout;
227         if (timeout == AFB_SESSION_TIMEOUT_INFINITE)
228                 expiration = MAX_EXPIRATION;
229         else {
230                 if (timeout == AFB_SESSION_TIMEOUT_DEFAULT)
231                         expiration = now + sessions.timeout;
232                 else
233                         expiration = now + timeout;
234                 if (expiration < 0)
235                         expiration = MAX_EXPIRATION;
236         }
237
238         /* record the expiration */
239         session->expiration = expiration;
240 }
241
242 /*
243  * Add a new session with the 'uuid' (of 'hashidx')
244  * and the 'timeout' starting from 'now'.
245  * Add it to the set of sessions
246  * Return the created session
247  */
248 static struct afb_session *session_add(const char *uuid, int timeout, time_t now, uint8_t hashidx)
249 {
250         struct afb_session *session;
251
252         /* check arguments */
253         if (!AFB_SESSION_TIMEOUT_IS_VALID(timeout)
254          || (uuid && strlen(uuid) >= sizeof session->uuid)) {
255                 errno = EINVAL;
256                 return NULL;
257         }
258
259         /* allocates a new one */
260         session = calloc(1, sizeof *session);
261         if (session == NULL) {
262                 errno = ENOMEM;
263                 return NULL;
264         }
265
266         /* initialize */
267         pthread_mutex_init(&session->mutex, NULL);
268         session->refcount = 1;
269         strcpy(session->uuid, uuid);
270         strcpy(session->token, sessions.initok);
271         session->timeout = timeout;
272         session_update_expiration(session, now);
273
274         /* add */
275         if (sessionset_add(session, hashidx)) {
276                 free(session);
277                 return NULL;
278         }
279
280         afb_hook_session_create(session);
281
282         return session;
283 }
284
285 /* Remove expired sessions and return current time (now) */
286 static time_t sessionset_cleanup (int force)
287 {
288         struct afb_session *session, **prv;
289         int idx;
290         time_t now;
291
292         /* Loop on Sessions Table and remove anything that is older than timeout */
293         now = NOW;
294         for (idx = 0 ; idx < HEADCOUNT; idx++) {
295                 prv = &sessions.heads[idx];
296                 while ((session = *prv)) {
297                         session_lock(session);
298                         if (force || session->expiration < now)
299                                 session_close(session);
300                         if (!session->closed)
301                                 prv = &session->next;
302                         else {
303                                 *prv = session->next;
304                                 sessions.count--;
305                                 session->notinset = 1;
306                                 if ( !session->refcount) {
307                                         session_destroy(session);
308                                         continue;
309                                 }
310                         }
311                         session_unlock(session);
312                 }
313         }
314         return now;
315 }
316
317 /**
318  * Initialize the session manager with a 'max_session_count',
319  * an initial common 'timeout' and an initial common token 'initok'.
320  *
321  * @param max_session_count  maximum allowed session count in the same time
322  * @param timeout            the initial default timeout of sessions
323  * @param initok             the initial default token of sessions
324  * 
325  */
326 int afb_session_init (int max_session_count, int timeout, const char *initok)
327 {
328         /* check parameters */
329         if (initok && strlen(initok) >= sizeof sessions.initok) {
330                 ERROR("initial token '%s' too long (max length %d)",
331                         initok, ((int)(sizeof sessions.initok)) - 1);
332                 errno = EINVAL;
333                 return -1;
334         }
335
336         /* init the sessionset (after cleanup) */
337         sessionset_lock();
338         sessionset_cleanup(1);
339         sessions.max = max_session_count;
340         sessions.timeout = timeout;
341         if (initok == NULL)
342                 new_uuid(sessions.initok);
343         else
344                 strcpy(sessions.initok, initok);
345         sessionset_unlock();
346         return 0;
347 }
348
349 /**
350  * Iterate the sessions and call 'callback' with
351  * the 'closure' for each session.
352  */
353 void afb_session_foreach(void (*callback)(void *closure, struct afb_session *session), void *closure)
354 {
355         struct afb_session *session;
356         int idx;
357
358         /* Loop on Sessions Table and remove anything that is older than timeout */
359         sessionset_lock();
360         for (idx = 0 ; idx < HEADCOUNT; idx++) {
361                 session = sessions.heads[idx];
362                 while (session) {
363                         if (!session->closed)
364                                 callback(closure, session);
365                         session = session->next;
366                 }
367         }
368         sessionset_unlock();
369 }
370
371 /**
372  * Cleanup the sessionset of its closed or expired sessions
373  */
374 void afb_session_purge()
375 {
376         sessionset_lock();
377         sessionset_cleanup(0);
378         sessionset_unlock();
379 }
380
381 /**
382  * @return the initial token set at initialization
383  */
384 const char *afb_session_initial_token()
385 {
386         return sessions.initok;
387 }
388
389 /* Searchs the session of 'uuid' */
390 struct afb_session *afb_session_search (const char *uuid)
391 {
392         struct afb_session *session;
393
394         sessionset_lock();
395         sessionset_cleanup(0);
396         session = sessionset_search(uuid, pearson4(uuid));
397         session = afb_session_addref(session);
398         sessionset_unlock();
399         return session;
400
401 }
402
403 /**
404  * Creates a new session with 'timeout'
405  */
406 struct afb_session *afb_session_create (int timeout)
407 {
408         return afb_session_get(NULL, timeout, NULL);
409 }
410
411 /* This function will return exiting session or newly created session */
412 struct afb_session *afb_session_get (const char *uuid, int timeout, int *created)
413 {
414         char _uuid_[SIZEUUID];
415         uint8_t hashidx;
416         struct afb_session *session;
417         time_t now;
418         int c;
419
420         /* cleaning */
421         sessionset_lock();
422         now = sessionset_cleanup(0);
423
424         /* search for an existing one not too old */
425         if (!uuid) {
426                 hashidx = sessionset_make_uuid(_uuid_);
427                 uuid = _uuid_;
428         } else {
429                 hashidx = pearson4(uuid);
430                 session = sessionset_search(uuid, hashidx);
431                 if (session) {
432                         /* session found */
433                         afb_session_addref(session);
434                         c = 0;
435                         goto end;
436                 }
437         }
438         /* create the session */
439         session = session_add(uuid, timeout, now, hashidx);
440         c = 1;
441 end:
442         sessionset_unlock();
443         if (created)
444                 *created = c;
445
446         return session;
447 }
448
449 /* increase the use count on 'session' (can be NULL) */
450 struct afb_session *afb_session_addref(struct afb_session *session)
451 {
452         if (session != NULL) {
453                 afb_hook_session_addref(session);
454                 session->refcount++;
455                 session_unlock(session);
456         }
457         return session;
458 }
459
460 /* decrease the use count of 'session' (can be NULL) */
461 void afb_session_unref(struct afb_session *session)
462 {
463         if (session == NULL)
464                 return;
465
466         session_lock(session);
467         afb_hook_session_unref(session);
468         if (--session->refcount) {
469                 if (session->autoclose)
470                         session_close(session);
471                 if (session->notinset) {
472                         session_destroy(session);
473                         return;
474                 }
475         }
476         session_unlock(session);
477 }
478
479 /* close 'session' */
480 void afb_session_close (struct afb_session *session)
481 {
482         session_lock(session);
483         session_close(session);
484         session_unlock(session);
485 }
486
487 /**
488  * Set the 'autoclose' flag of the 'session'
489  *
490  * A session whose autoclose flag is true will close as
491  * soon as it is no more referenced. 
492  *
493  * @param session    the session to set
494  * @param autoclose  the value to set
495  */
496 void afb_session_set_autoclose(struct afb_session *session, int autoclose)
497 {
498         session->autoclose = !!autoclose;
499 }
500
501 /* is 'session' closed? */
502 int afb_session_is_closed (struct afb_session *session)
503 {
504         return session->closed;
505 }
506
507 /*
508  * check whether the token of 'session' is 'token'
509  * return 1 if true or 0 otherwise
510  */
511 int afb_session_check_token (struct afb_session *session, const char *token)
512 {
513         int r;
514
515         session_unlock(session);
516         r = !session->closed
517           && session->expiration >= NOW
518           && !(session->token[0] && strcmp (token, session->token));
519         session_unlock(session);
520         return r;
521 }
522
523 /* generate a new token and update client context */
524 void afb_session_new_token (struct afb_session *session)
525 {
526         session_unlock(session);
527         new_uuid(session->token);
528         session_update_expiration(session, NOW);
529         afb_hook_session_renew(session);
530         session_unlock(session);
531 }
532
533 /* Returns the uuid of 'session' */
534 const char *afb_session_uuid (struct afb_session *session)
535 {
536         return session->uuid;
537 }
538
539 /* Returns the token of 'session' */
540 const char *afb_session_token (struct afb_session *session)
541 {
542         return session->token;
543 }
544
545 /**
546  * Get the index of the 'key' in the cookies array.
547  * @param key the key to scan
548  * @return the index of the list for key within cookies
549  */
550 static int cookeyidx(const void *key)
551 {
552         intptr_t x = (intptr_t)key;
553         unsigned r = (unsigned)((x >> 5) ^ (x >> 15));
554         return r & COOKIEMASK;
555 }
556
557 /**
558  * Set, get, replace, remove a cookie of 'key' for the 'session'
559  *
560  * The behaviour of this function depends on its parameters:
561  *
562  * @param session       the session
563  * @param key           the key of the cookie
564  * @param makecb        the creation function or NULL
565  * @param freecb        the release function or NULL
566  * @param closure       an argument for makecb or the value if makecb==NULL
567  * @param replace       a boolean enforcing replecement of the previous value
568  *
569  * @return the value of the cookie
570  *
571  * The 'key' is a pointer and compared as pointers.
572  *
573  * For getting the current value of the cookie:
574  *
575  *   afb_session_cookie(session, key, NULL, NULL, NULL, 0)
576  *
577  * For storing the value of the cookie
578  *
579  *   afb_session_cookie(session, key, NULL, NULL, value, 1)
580  */
581 void *afb_session_cookie(struct afb_session *session, const void *key, void *(*makecb)(void *closure), void (*freecb)(void *item), void *closure, int replace)
582 {
583         int idx;
584         void *value;
585         struct cookie *cookie, **prv;
586
587         /* get key hashed index */
588         idx = cookeyidx(key);
589
590         /* lock session and search for the cookie of 'key' */
591         session_lock(session);
592         prv = &session->cookies[idx];
593         for (;;) {
594                 cookie = *prv;
595                 if (!cookie) {
596                         /* 'key' not found, create value using 'closure' and 'makecb' */
597                         value = makecb ? makecb(closure) : closure;
598                         /* store the the only if it has some meaning */
599                         if (replace || makecb || freecb) {
600                                 cookie = malloc(sizeof *cookie);
601                                 if (!cookie) {
602                                         errno = ENOMEM;
603                                         /* calling freecb if there is no makecb may have issue */
604                                         if (makecb && freecb)
605                                                 freecb(value);
606                                         value = NULL;
607                                 } else {
608                                         cookie->key = key;
609                                         cookie->value = value;
610                                         cookie->freecb = freecb;
611                                         cookie->next = NULL;
612                                         *prv = cookie;
613                                 }
614                         }
615                         break;
616                 } else if (cookie->key == key) {
617                         /* cookie of key found */
618                         if (!replace)
619                                 /* not replacing, get the value */
620                                 value = cookie->value;
621                         else {
622                                 /* create value using 'closure' and 'makecb' */
623                                 value = makecb ? makecb(closure) : closure;
624
625                                 /* free previous value is needed */
626                                 if (cookie->value != value && cookie->freecb)
627                                         cookie->freecb(cookie->value);
628
629                                 /* if both value and freecb are NULL drop the cookie */
630                                 if (!value && !freecb) {
631                                         *prv = cookie->next;
632                                         free(cookie);
633                                 } else {
634                                         /* store the value and its releaser */
635                                         cookie->value = value;
636                                         cookie->freecb = freecb;
637                                 }
638                         }
639                         break;
640                 } else {
641                         prv = &(cookie->next);
642                 }
643         }
644
645         /* unlock the session and return the value */
646         session_unlock(session);
647         return value;
648 }
649
650 /**
651  * Get the cookie of 'key' in the 'session'.
652  *
653  * @param session  the session to search in
654  * @param key      the key of the data to retrieve
655  *
656  * @return the data staored for the key or NULL if the key isn't found
657  */
658 void *afb_session_get_cookie(struct afb_session *session, const void *key)
659 {
660         return afb_session_cookie(session, key, NULL, NULL, NULL, 0);
661 }
662
663 /**
664  * Set the cookie of 'key' in the 'session' to the 'value' that can be
665  * cleaned using 'freecb' (if not null).
666  *
667  * @param session  the session to set
668  * @param key      the key of the data to store
669  * @param value    the value to store at key
670  * @param freecb   a function to use when the cookie value is to remove (or null)
671  *
672  * @return the data staored for the key or NULL if the key isn't found
673  * 
674  */
675 int afb_session_set_cookie(struct afb_session *session, const void *key, void *value, void (*freecb)(void*))
676 {
677         return -(value != afb_session_cookie(session, key, NULL, freecb, value, 1));
678 }
679