afb-session: improve naming
[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 <string.h>
25 #include <uuid/uuid.h>
26 #include <assert.h>
27 #include <errno.h>
28
29 #include <json-c/json.h>
30
31 #include "afb-session.h"
32 #include "verbose.h"
33
34 #define SIZEUUID        37
35 #define HEADCOUNT       16
36 #define COOKEYCOUNT     8
37 #define COOKEYMASK      (COOKEYCOUNT - 1)
38
39 #define NOW (time(NULL))
40
41 struct cookie
42 {
43         struct cookie *next;
44         const void *key;
45         void *value;
46         void (*freecb)(void*);
47 };
48
49 struct afb_session
50 {
51         struct afb_session *next; /* link to the next */
52         unsigned refcount;
53         int timeout;
54         time_t expiration;      // expiration time of the token
55         pthread_mutex_t mutex;
56         struct cookie *cookies[COOKEYCOUNT];
57         char idx;
58         char uuid[SIZEUUID];    // long term authentication of remote client
59         char token[SIZEUUID];   // short term authentication of remote client
60 };
61
62 // Session UUID are store in a simple array [for 10 sessions this should be enough]
63 static struct {
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
67         int max;
68         int timeout;
69         char initok[SIZEUUID];
70 } sessions;
71
72 /* generate a uuid */
73 static void new_uuid(char uuid[SIZEUUID])
74 {
75         uuid_t newuuid;
76         uuid_generate(newuuid);
77         uuid_unparse_lower(newuuid, uuid);
78 }
79
80 static inline void lock(struct afb_session *session)
81 {
82         pthread_mutex_lock(&session->mutex);
83 }
84
85 static inline void unlock(struct afb_session *session)
86 {
87         pthread_mutex_unlock(&session->mutex);
88 }
89
90 // Free context [XXXX Should be protected again memory abort XXXX]
91 static void close_session(struct afb_session *session)
92 {
93         int idx;
94         struct cookie *cookie;
95
96         /* free cookies */
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);
102                         free(cookie);
103                 }
104         }
105 }
106
107 /* tiny hash function inspired from pearson */
108 static int pearson4(const char *text)
109 {
110         static uint8_t T[16] = {
111                  4,  1,  6,  0,  9, 14, 11,  5,
112                  2,  3, 12, 15, 10,  7,  8, 13
113         };
114         uint8_t r, c;
115
116         for (r = 0; (c = (uint8_t)*text) ; text++) {
117                 r = T[r ^ (15 & c)];
118                 r = T[r ^ (c >> 4)];
119         }
120         return r; // % HEADCOUNT;
121 }
122
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)
125 {
126         pthread_mutex_init(&sessions.mutex, NULL);
127         sessions.max = max_session_count;
128         sessions.timeout = timeout;
129         if (initok == NULL)
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);
134         else {
135                 ERROR("initial token '%s' too long (max length %d)", initok, ((int)(sizeof sessions.initok)) - 1);
136                 exit(1);
137         }
138 }
139
140 const char *afb_session_initial_token()
141 {
142         return sessions.initok;
143 }
144
145 static struct afb_session *search (const char* uuid, int idx)
146 {
147         struct afb_session *session;
148
149         session = sessions.heads[idx];
150         while (session && strcmp(uuid, session->uuid))
151                 session = session->next;
152
153         return session;
154 }
155
156 static void destroy (struct afb_session *session)
157 {
158         struct afb_session **prv;
159
160         assert (session != NULL);
161
162         close_session(session);
163         pthread_mutex_lock(&sessions.mutex);
164         prv = &sessions.heads[(int)session->idx];
165         while (*prv)
166                 if (*prv != session)
167                         prv = &((*prv)->next);
168                 else {
169                         *prv = session->next;
170                         sessions.count--;
171                         pthread_mutex_destroy(&session->mutex);
172                         free(session);
173                         break;
174                 }
175         pthread_mutex_unlock(&sessions.mutex);
176 }
177
178 // Check if context timeout or not
179 static int is_expired (struct afb_session *ctx, time_t now)
180 {
181         assert (ctx != NULL);
182         return ctx->expiration < now;
183 }
184
185 // Check if context is active or not
186 static int is_active (struct afb_session *ctx, time_t now)
187 {
188         assert (ctx != NULL);
189         return ctx->uuid[0] != 0 && ctx->expiration >= now;
190 }
191
192 // Loop on every entry and remove old context sessions.hash
193 static time_t cleanup ()
194 {
195         struct afb_session *session, *next;
196         int idx;
197         time_t now;
198
199         // Loop on Sessions Table and remove anything that is older than timeout
200         now = NOW;
201         for (idx = 0 ; idx < HEADCOUNT; idx++) {
202                 session = sessions.heads[idx];
203                 while (session) {
204                         next = session->next;
205                         if (is_expired(session, now))
206                                 afb_session_close(session);
207                         session = next;
208                 }
209         }
210         return now;
211 }
212
213 static struct afb_session *add_session (const char *uuid, int timeout, time_t now, int idx)
214 {
215         struct afb_session *session;
216         time_t expiration;
217
218         /* check arguments */
219         if (!AFB_SESSION_TIMEOUT_IS_VALID(timeout)
220          || (uuid && strlen(uuid) >= sizeof session->uuid)) {
221                 errno = EINVAL;
222                 return NULL;
223         }
224
225         /* check session count */
226         if (sessions.count >= sessions.max) {
227                 errno = EBUSY;
228                 return NULL;
229         }
230
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);
237                 if (expiration < 0)
238                         expiration = (time_t)(((unsigned long long)expiration) >> 1);
239         }
240
241         /* allocates a new one */
242         session = calloc(1, sizeof *session);
243         if (session == NULL) {
244                 errno = ENOMEM;
245                 return NULL;
246         }
247
248         /* initialize */
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;
255
256         /* link */
257         session->idx = (char)idx;
258         session->next = sessions.heads[idx];
259         sessions.heads[idx] = session;
260         sessions.count++;
261
262         return session;
263 }
264
265 /* create a new session for the given timeout */
266 static struct afb_session *new_session (int timeout, time_t now)
267 {
268         int idx;
269         char uuid[SIZEUUID];
270
271         do {
272                 new_uuid(uuid);
273                 idx = pearson4(uuid);
274         } while(search(uuid, idx));
275         return add_session(uuid, timeout, now, idx);
276 }
277
278 /* Creates a new session with 'timeout' */
279 struct afb_session *afb_session_create (int timeout)
280 {
281         time_t now;
282         struct afb_session *session;
283
284         /* cleaning */
285         pthread_mutex_lock(&sessions.mutex);
286         now = cleanup();
287         session = new_session(timeout, now);
288         pthread_mutex_unlock(&sessions.mutex);
289
290         return session;
291 }
292
293 /* Searchs the session of 'uuid' */
294 struct afb_session *afb_session_search (const char *uuid)
295 {
296         struct afb_session *session;
297
298         /* cleaning */
299         pthread_mutex_lock(&sessions.mutex);
300         cleanup();
301         session = search(uuid, pearson4(uuid));
302         if (session)
303                 __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
304         pthread_mutex_unlock(&sessions.mutex);
305         return session;
306
307 }
308
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)
311 {
312         int idx;
313         struct afb_session *session;
314         time_t now;
315
316         /* cleaning */
317         pthread_mutex_lock(&sessions.mutex);
318         now = cleanup();
319
320         /* search for an existing one not too old */
321         if (!uuid)
322                 session = new_session(timeout, now);
323         else {
324                 idx = pearson4(uuid);
325                 session = search(uuid, idx);
326                 if (session) {
327                         __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
328                         pthread_mutex_unlock(&sessions.mutex);
329                         if (created)
330                                 *created = 0;
331                         return session;
332                 }
333                 session = add_session (uuid, timeout, now, idx);
334         }
335         pthread_mutex_unlock(&sessions.mutex);
336
337         if (created)
338                 *created = !!session;
339
340         return session;
341 }
342
343 /* increase the use count on the session */
344 struct afb_session *afb_session_addref(struct afb_session *session)
345 {
346         if (session != NULL)
347                 __atomic_add_fetch(&session->refcount, 1, __ATOMIC_RELAXED);
348         return session;
349 }
350
351 /* decrease the use count of the session */
352 void afb_session_unref(struct afb_session *session)
353 {
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)
359                                 destroy (session);
360                         else
361                                 pthread_mutex_unlock(&session->mutex);
362                 }
363         }
364 }
365
366 // Free Client Session Context
367 void afb_session_close (struct afb_session *session)
368 {
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);
375                 else {
376                         destroy (session);
377                         return;
378                 }
379         }
380         pthread_mutex_unlock(&session->mutex);
381 }
382
383 // Sample Generic Ping Debug API
384 int afb_session_check_token (struct afb_session *session, const char *token)
385 {
386         assert(session != NULL);
387         assert(token != NULL);
388
389         // compare current token with previous one
390         if (!is_active (session, NOW))
391                 return 0;
392
393         if (session->token[0] && strcmp (token, session->token) != 0)
394                 return 0;
395
396         return 1;
397 }
398
399 // generate a new token and update client context
400 void afb_session_new_token (struct afb_session *session)
401 {
402         assert(session != NULL);
403
404         // Old token was valid let's regenerate a new one
405         new_uuid(session->token);
406
407         // keep track of time for session timeout and further clean up
408         if (session->timeout != 0)
409                 session->expiration = NOW + session->timeout;
410 }
411
412 /* Returns the uuid of 'session' */
413 const char *afb_session_uuid (struct afb_session *session)
414 {
415         assert(session != NULL);
416         return session->uuid;
417 }
418
419 /* Returns the token of 'session' */
420 const char *afb_session_token (struct afb_session *session)
421 {
422         assert(session != NULL);
423         return session->token;
424 }
425
426 /**
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
430  */
431 static int cookeyidx(const void *key)
432 {
433         intptr_t x = (intptr_t)key;
434         unsigned r = (unsigned)((x >> 5) ^ (x >> 15));
435         return r & COOKEYMASK;
436 }
437
438 /**
439  * Set, get, replace, remove a cookie of 'key' for the 'session'
440  *
441  * The behaviour of this function depends on its parameters:
442  *
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
449  *
450  * @return the value of the cookie
451  *
452  * The 'key' is a pointer and compared as pointers.
453  *
454  * For getting the current value of the cookie:
455  *
456  *   afb_session_cookie(session, key, NULL, NULL, NULL, 0)
457  *
458  * For storing the value of the cookie
459  *
460  *   afb_session_cookie(session, key, NULL, NULL, value, 1)
461  */
462 void *afb_session_cookie(struct afb_session *session, const void *key, void *(*makecb)(void *closure), void (*freecb)(void *item), void *closure, int replace)
463 {
464         int idx;
465         void *value;
466         struct cookie *cookie, **prv;
467
468         /* get key hashed index */
469         idx = cookeyidx(key);
470
471         /* lock session and search for the cookie of 'key' */
472         lock(session);
473         prv = &session->cookies[idx];
474         for (;;) {
475                 cookie = *prv;
476                 if (!cookie) {
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);
482                                 if (!cookie) {
483                                         errno = ENOMEM;
484                                         /* calling freecb if there is no makecb may have issue */
485                                         if (makecb && freecb)
486                                                 freecb(value);
487                                         value = NULL;
488                                 } else {
489                                         cookie->key = key;
490                                         cookie->value = value;
491                                         cookie->freecb = freecb;
492                                         cookie->next = NULL;
493                                         *prv = cookie;
494                                 }
495                         }
496                         break;
497                 } else if (cookie->key == key) {
498                         /* cookie of key found */
499                         if (!replace)
500                                 /* not replacing, get the value */
501                                 value = cookie->value;
502                         else {
503                                 /* create value using 'closure' and 'makecb' */
504                                 value = makecb ? makecb(closure) : closure;
505
506                                 /* free previous value is needed */
507                                 if (cookie->value != value && cookie->freecb)
508                                         cookie->freecb(cookie->value);
509
510                                 /* store the value and its releaser */
511                                 cookie->value = value;
512                                 cookie->freecb = freecb;
513
514                                 /* but if both are NULL drop the cookie */
515                                 if (!value && !freecb) {
516                                         *prv = cookie->next;
517                                         free(cookie);
518                                 }
519                         }
520                         break;
521                 } else {
522                         prv = &(cookie->next);
523                 }
524         }
525
526         /* unlock the session and return the value */
527         unlock(session);
528         return value;
529 }
530
531 void *afb_session_get_cookie(struct afb_session *session, const void *key)
532 {
533         return afb_session_cookie(session, key, NULL, NULL, NULL, 0);
534 }
535
536 int afb_session_set_cookie(struct afb_session *session, const void *key, void *value, void (*freecb)(void*))
537 {
538         return -(value != afb_session_cookie(session, key, NULL, freecb, value, 1));
539 }
540