Make LOA local to the binding
[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 COOKEYCOUNT  8
35 #define COOKEYMASK   (COOKEYCOUNT - 1)
36
37 #define NOW (time(NULL))
38
39 struct cookie
40 {
41         struct cookie *next;
42         const void *key;
43         void *value;
44         void (*freecb)(void*);
45 };
46
47 struct afb_session
48 {
49         unsigned refcount;
50         int timeout;
51         time_t expiration;    // expiration time of the token
52         time_t access;
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];
56 };
57
58 // Session UUID are store in a simple array [for 10 sessions this should be enough]
59 static struct {
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
63         int max;
64         int timeout;
65         char initok[37];
66 } sessions;
67
68 /**
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
72  */
73 static int cookeyidx(const void *key)
74 {
75         intptr_t x = (intptr_t)key;
76         unsigned r = (unsigned)((x >> 5) ^ (x >> 15));
77         return r & COOKEYMASK;
78 }
79
80 /* generate a uuid */
81 static void new_uuid(char uuid[37])
82 {
83         uuid_t newuuid;
84         uuid_generate(newuuid);
85         uuid_unparse_lower(newuuid, uuid);
86 }
87
88 // Free context [XXXX Should be protected again memory abort XXXX]
89 static void free_data (struct afb_session *session)
90 {
91         int idx;
92         struct cookie *cookie, *next;
93
94         // free cookies
95         for (idx = 0 ; idx < COOKEYCOUNT ; idx++) {
96                 cookie = session->cookies[idx];
97                 session->cookies[idx] = NULL;
98                 while (cookie != NULL) {
99                         next = cookie->next;
100                         if (cookie->freecb != NULL)
101                                 cookie->freecb(cookie->value);
102                         free(cookie);
103                         cookie = next;
104                 }
105         }
106 }
107
108 // Create a new store in RAM, not that is too small it will be automatically extended
109 void afb_session_init (int max_session_count, int timeout, const char *initok)
110 {
111         // let's create as store as hashtable does not have any
112         sessions.store = calloc (1 + (unsigned)max_session_count, sizeof(struct afb_session));
113         sessions.max = max_session_count;
114         sessions.timeout = timeout;
115         if (initok == NULL)
116                 /* without token, a secret is made to forbid creation of sessions */
117                 new_uuid(sessions.initok);
118         else if (strlen(initok) < sizeof(sessions.store[0]->token))
119                 strcpy(sessions.initok, initok);
120         else {
121                 ERROR("initial token '%s' too long (max length 36)", initok);
122                 exit(1);
123         }
124 }
125
126 static struct afb_session *search (const char* uuid)
127 {
128         int  idx;
129         struct afb_session *session;
130
131         assert (uuid != NULL);
132
133         pthread_mutex_lock(&sessions.mutex);
134
135         for (idx=0; idx < sessions.max; idx++) {
136                 session = sessions.store[idx];
137                 if (session && (0 == strcmp (uuid, session->uuid)))
138                         goto found;
139         }
140         session = NULL;
141
142 found:
143         pthread_mutex_unlock(&sessions.mutex);
144         return session;
145 }
146
147 static int destroy (struct afb_session *session)
148 {
149         int idx;
150         int status;
151
152         assert (session != NULL);
153
154         pthread_mutex_lock(&sessions.mutex);
155
156         for (idx=0; idx < sessions.max; idx++) {
157                 if (sessions.store[idx] == session) {
158                         sessions.store[idx] = NULL;
159                         sessions.count--;
160                         status = 1;
161                         goto deleted;
162                 }
163         }
164         status = 0;
165 deleted:
166         pthread_mutex_unlock(&sessions.mutex);
167         return status;
168 }
169
170 static int add (struct afb_session *session)
171 {
172         int idx;
173         int status;
174
175         assert (session != NULL);
176
177         pthread_mutex_lock(&sessions.mutex);
178
179         for (idx=0; idx < sessions.max; idx++) {
180                 if (NULL == sessions.store[idx]) {
181                         sessions.store[idx] = session;
182                         sessions.count++;
183                         status = 1;
184                         goto added;
185                 }
186         }
187         status = 0;
188 added:
189         pthread_mutex_unlock(&sessions.mutex);
190         return status;
191 }
192
193 // Check if context timeout or not
194 static int is_expired (struct afb_session *ctx, time_t now)
195 {
196         assert (ctx != NULL);
197         return ctx->expiration < now;
198 }
199
200 // Check if context is active or not
201 static int is_active (struct afb_session *ctx, time_t now)
202 {
203         assert (ctx != NULL);
204         return ctx->uuid[0] != 0 && ctx->expiration >= now;
205 }
206
207 // Loop on every entry and remove old context sessions.hash
208 static void cleanup (time_t now)
209 {
210         struct afb_session *ctx;
211         long idx;
212
213         // Loop on Sessions Table and remove anything that is older than timeout
214         for (idx=0; idx < sessions.max; idx++) {
215                 ctx = sessions.store[idx];
216                 if (ctx != NULL && is_expired(ctx, now)) {
217                         afb_session_close (ctx);
218                 }
219         }
220 }
221
222 static struct afb_session *make_session (const char *uuid, int timeout, time_t now)
223 {
224         struct afb_session *session;
225
226         /* allocates a new one */
227         session = calloc(1, sizeof(struct afb_session));
228         if (session == NULL) {
229                 errno = ENOMEM;
230                 goto error;
231         }
232
233         /* generate the uuid */
234         if (uuid == NULL) {
235                 new_uuid(session->uuid);
236         } else {
237                 if (strlen(uuid) >= sizeof session->uuid) {
238                         errno = EINVAL;
239                         goto error2;
240                 }
241                 strcpy(session->uuid, uuid);
242         }
243
244         /* init the token */
245         strcpy(session->token, sessions.initok);
246         session->timeout = timeout;
247         if (timeout != 0)
248                 session->expiration = now + timeout;
249         else {
250                 session->expiration = (time_t)(~(time_t)0);
251                 if (session->expiration < 0)
252                         session->expiration = (time_t)(((unsigned long long)session->expiration) >> 1);
253         }
254         if (!add (session)) {
255                 errno = ENOMEM;
256                 goto error2;
257         }
258
259         session->access = now;
260         session->refcount = 1;
261         return session;
262
263 error2:
264         free(session);
265 error:
266         return NULL;
267 }
268
269 struct afb_session *afb_session_create (const char *uuid, int timeout)
270 {
271         time_t now;
272
273         /* cleaning */
274         now = NOW;
275         cleanup (now);
276
277         /* search for an existing one not too old */
278         if (uuid != NULL && search(uuid) != NULL) {
279                 errno = EEXIST;
280                 return NULL;
281         }
282
283         return make_session(uuid, timeout, now);
284 }
285
286 // This function will return exiting session or newly created session
287 struct afb_session *afb_session_get (const char *uuid, int *created)
288 {
289         struct afb_session *session;
290         time_t now;
291
292         /* cleaning */
293         now = NOW;
294         cleanup (now);
295
296         /* search for an existing one not too old */
297         if (uuid != NULL) {
298                 session = search(uuid);
299                 if (session != NULL) {
300                         *created = 0;
301                         session->access = now;
302                         session->refcount++;
303                         return session;
304                 }
305         }
306
307         *created = 1;
308         return make_session(uuid, sessions.timeout, now);
309 }
310
311 struct afb_session *afb_session_addref(struct afb_session *session)
312 {
313         if (session != NULL)
314                 session->refcount++;
315         return session;
316 }
317
318 void afb_session_unref(struct afb_session *session)
319 {
320         if (session != NULL) {
321                 assert(session->refcount != 0);
322                 --session->refcount;
323                 if (session->refcount == 0 && session->uuid[0] == 0) {
324                         destroy (session);
325                         free(session);
326                 }
327         }
328 }
329
330 // Free Client Session Context
331 void afb_session_close (struct afb_session *session)
332 {
333         assert(session != NULL);
334         if (session->uuid[0] != 0) {
335                 session->uuid[0] = 0;
336                 free_data (session);
337                 if (session->refcount == 0) {
338                         destroy (session);
339                         free(session);
340                 }
341         }
342 }
343
344 // Sample Generic Ping Debug API
345 int afb_session_check_token (struct afb_session *session, const char *token)
346 {
347         assert(session != NULL);
348         assert(token != NULL);
349
350         // compare current token with previous one
351         if (!is_active (session, NOW))
352                 return 0;
353
354         if (session->token[0] && strcmp (token, session->token) != 0)
355                 return 0;
356
357         return 1;
358 }
359
360 // generate a new token and update client context
361 void afb_session_new_token (struct afb_session *session)
362 {
363         assert(session != NULL);
364
365         // Old token was valid let's regenerate a new one
366         new_uuid(session->token);
367
368         // keep track of time for session timeout and further clean up
369         if (session->timeout != 0)
370                 session->expiration = NOW + session->timeout;
371 }
372
373 const char *afb_session_uuid (struct afb_session *session)
374 {
375         assert(session != NULL);
376         return session->uuid;
377 }
378
379 const char *afb_session_token (struct afb_session *session)
380 {
381         assert(session != NULL);
382         return session->token;
383 }
384
385 void *afb_session_get_cookie(struct afb_session *session, const void *key)
386 {
387         struct cookie *cookie;
388         int idx;
389
390         idx = cookeyidx(key);
391         cookie = session->cookies[idx];
392         while(cookie != NULL) {
393                 if (cookie->key == key)
394                         return cookie->value;
395                 cookie = cookie->next;
396         }
397         return NULL;
398 }
399
400 int afb_session_set_cookie(struct afb_session *session, const void *key, void *value, void (*freecb)(void*))
401 {
402         struct cookie *cookie;
403         int idx;
404
405         /* search for a replacement */
406         idx = cookeyidx(key);
407         cookie = session->cookies[idx];
408         while(cookie != NULL) {
409                 if (cookie->key == key) {
410                         if (cookie->value != value && cookie->freecb)
411                                 cookie->freecb(cookie->value);
412                         cookie->value = value;
413                         cookie->freecb = freecb;
414                         return 0;
415                 }
416                 cookie = cookie->next;
417         }
418
419         /* allocates */
420         cookie = malloc(sizeof *cookie);
421         if (cookie == NULL) {
422                 errno = ENOMEM;
423                 return -1;
424         }
425
426         cookie->key = key;
427         cookie->value = value;
428         cookie->freecb = freecb;
429         cookie->next = session->cookies[idx];
430         session->cookies[idx] = cookie;
431         return 0;
432 }
433