2 * Copyright (C) 2015, 2016 "IoT.bzh"
3 * Author "Fulup Ar Foll"
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
24 #include <uuid/uuid.h>
28 #include <json-c/json.h>
33 #define NOW (time(NULL))
38 void (*free_value)(void*);
41 struct afb_event_listener_list
43 struct afb_event_listener_list *next;
44 struct afb_event_listener listener;
51 time_t expiration; // expiration time of the token
53 char uuid[37]; // long term authentication of remote client
54 char token[37]; // short term authentication of remote client
55 struct client_value *values;
56 struct afb_event_listener_list *listeners;
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_clientCtx **store; // sessions store
63 int count; // current number of sessions
68 struct afb_event_listener_list *listeners;
72 static void new_uuid(char uuid[37])
75 uuid_generate(newuuid);
76 uuid_unparse_lower(newuuid, uuid);
79 // Free context [XXXX Should be protected again memory abort XXXX]
80 static void ctxUuidFreeCB (struct AFB_clientCtx *client)
84 // If application add a handle let's free it now
85 assert (client->values != NULL);
87 // Free client handle with a standard Free function, with app callback or ignore it
88 for (idx=0; idx < sessions.apicount; idx ++)
89 ctxClientValueSet(client, idx, NULL, NULL);
92 // Create a new store in RAM, not that is too small it will be automatically extended
93 void ctxStoreInit (int max_session_count, int timeout, const char *initok, int context_count)
95 // let's create as store as hashtable does not have any
96 sessions.store = calloc (1 + (unsigned)max_session_count, sizeof(struct AFB_clientCtx));
97 sessions.max = max_session_count;
98 sessions.timeout = timeout;
99 sessions.apicount = context_count;
101 /* without token, a secret is made to forbid creation of sessions */
102 new_uuid(sessions.initok);
103 else if (strlen(initok) < sizeof(sessions.store[0]->token))
104 strcpy(sessions.initok, initok);
106 ERROR("initial token '%s' too long (max length 36)", initok);
111 static struct AFB_clientCtx *ctxStoreSearch (const char* uuid)
114 struct AFB_clientCtx *client;
116 assert (uuid != NULL);
118 pthread_mutex_lock(&sessions.mutex);
120 for (idx=0; idx < sessions.max; idx++) {
121 client = sessions.store[idx];
122 if (client && (0 == strcmp (uuid, client->uuid)))
128 pthread_mutex_unlock(&sessions.mutex);
132 static int ctxStoreDel (struct AFB_clientCtx *client)
137 assert (client != NULL);
139 pthread_mutex_lock(&sessions.mutex);
141 for (idx=0; idx < sessions.max; idx++) {
142 if (sessions.store[idx] == client) {
143 sessions.store[idx] = NULL;
151 pthread_mutex_unlock(&sessions.mutex);
155 static int ctxStoreAdd (struct AFB_clientCtx *client)
160 assert (client != NULL);
162 pthread_mutex_lock(&sessions.mutex);
164 for (idx=0; idx < sessions.max; idx++) {
165 if (NULL == sessions.store[idx]) {
166 sessions.store[idx] = client;
174 pthread_mutex_unlock(&sessions.mutex);
178 // Check if context timeout or not
179 static int ctxStoreTooOld (struct AFB_clientCtx *ctx, time_t now)
181 assert (ctx != NULL);
182 return ctx->expiration < now;
185 // Check if context is active or not
186 static int ctxIsActive (struct AFB_clientCtx *ctx, time_t now)
188 assert (ctx != NULL);
189 return ctx->uuid[0] != 0 && ctx->expiration >= now;
192 // Loop on every entry and remove old context sessions.hash
193 static void ctxStoreCleanUp (time_t now)
195 struct AFB_clientCtx *ctx;
198 // Loop on Sessions Table and remove anything that is older than timeout
199 for (idx=0; idx < sessions.max; idx++) {
200 ctx = sessions.store[idx];
201 if (ctx != NULL && ctxStoreTooOld(ctx, now)) {
202 ctxClientClose (ctx);
207 // This function will return exiting client context or newly created client context
208 struct AFB_clientCtx *ctxClientGetSession (const char *uuid, int *created)
210 struct AFB_clientCtx *clientCtx;
215 ctxStoreCleanUp (now);
217 /* search for an existing one not too old */
219 if (strlen(uuid) >= sizeof clientCtx->uuid) {
223 clientCtx = ctxStoreSearch(uuid);
224 if (clientCtx != NULL) {
230 /* returns a new one */
231 clientCtx = calloc(1, sizeof(struct AFB_clientCtx) + ((unsigned)sessions.apicount * sizeof(*clientCtx->values)));
232 if (clientCtx == NULL) {
236 clientCtx->values = (void*)(clientCtx + 1);
238 /* generate the uuid */
240 new_uuid(clientCtx->uuid);
242 strcpy(clientCtx->uuid, uuid);
246 strcpy(clientCtx->token, sessions.initok);
247 clientCtx->expiration = now + sessions.timeout;
248 if (!ctxStoreAdd (clientCtx)) {
255 clientCtx->access = now;
256 clientCtx->refcount++;
265 struct AFB_clientCtx *ctxClientAddRef(struct AFB_clientCtx *clientCtx)
267 if (clientCtx != NULL)
268 clientCtx->refcount++;
272 void ctxClientUnref(struct AFB_clientCtx *clientCtx)
274 if (clientCtx != NULL) {
275 assert(clientCtx->refcount != 0);
276 --clientCtx->refcount;
277 if (clientCtx->refcount == 0 && clientCtx->uuid[0] == 0) {
278 ctxStoreDel (clientCtx);
284 // Free Client Session Context
285 void ctxClientClose (struct AFB_clientCtx *clientCtx)
287 assert(clientCtx != NULL);
288 if (clientCtx->uuid[0] != 0) {
289 clientCtx->uuid[0] = 0;
290 ctxUuidFreeCB (clientCtx);
291 while(clientCtx->listeners != NULL)
292 ctxClientEventListenerRemove(clientCtx, clientCtx->listeners->listener);
293 if (clientCtx->refcount == 0) {
294 ctxStoreDel (clientCtx);
300 // Sample Generic Ping Debug API
301 int ctxTokenCheck (struct AFB_clientCtx *clientCtx, const char *token)
303 assert(clientCtx != NULL);
304 assert(token != NULL);
306 // compare current token with previous one
307 if (!ctxIsActive (clientCtx, NOW))
310 if (clientCtx->token[0] && strcmp (token, clientCtx->token) != 0)
316 // generate a new token and update client context
317 void ctxTokenNew (struct AFB_clientCtx *clientCtx)
319 assert(clientCtx != NULL);
321 // Old token was valid let's regenerate a new one
322 new_uuid(clientCtx->token);
324 // keep track of time for session timeout and further clean up
325 clientCtx->expiration = NOW + sessions.timeout;
328 static int add_listener(struct afb_event_listener_list **head, struct afb_event_listener listener)
330 struct afb_event_listener_list *iter, **prv;
336 iter = calloc(1, sizeof *iter);
341 iter->listener = listener;
346 if (iter->listener.itf == listener.itf && iter->listener.closure == listener.closure) {
354 int ctxClientEventListenerAdd(struct AFB_clientCtx *clientCtx, struct afb_event_listener listener)
356 return add_listener(clientCtx != NULL ? &clientCtx->listeners : &sessions.listeners, listener);
359 static void remove_listener(struct afb_event_listener_list **head, struct afb_event_listener listener)
361 struct afb_event_listener_list *iter, **prv;
368 if (iter->listener.itf == listener.itf && iter->listener.closure == listener.closure) {
369 if (!--iter->refcount) {
379 void ctxClientEventListenerRemove(struct AFB_clientCtx *clientCtx, struct afb_event_listener listener)
381 remove_listener(clientCtx != NULL ? &clientCtx->listeners : &sessions.listeners, listener);
384 static int send(struct afb_event_listener_list *head, const char *event, struct json_object *object)
386 struct afb_event_listener_list *iter;
391 while (iter != NULL) {
392 if (iter->listener.itf->expects == NULL || iter->listener.itf->expects(iter->listener.closure, event)) {
393 iter->listener.itf->send(iter->listener.closure, event, json_object_get(object));
402 int ctxClientEventSend(struct AFB_clientCtx *clientCtx, const char *event, struct json_object *object)
409 if (clientCtx != NULL) {
410 result = ctxIsActive(clientCtx, now) ? send(clientCtx->listeners, event, object) : 0;
412 result = send(sessions.listeners, event, object);
413 for (idx=0; idx < sessions.max; idx++) {
414 clientCtx = ctxClientAddRef(sessions.store[idx]);
415 if (clientCtx != NULL && ctxIsActive(clientCtx, now)) {
416 clientCtx = ctxClientAddRef(clientCtx);
417 result += send(clientCtx->listeners, event, object);
419 ctxClientUnref(clientCtx);
425 const char *ctxClientGetUuid (struct AFB_clientCtx *clientCtx)
427 assert(clientCtx != NULL);
428 return clientCtx->uuid;
431 const char *ctxClientGetToken (struct AFB_clientCtx *clientCtx)
433 assert(clientCtx != NULL);
434 return clientCtx->token;
437 void *ctxClientValueGet(struct AFB_clientCtx *clientCtx, int index)
439 assert(clientCtx != NULL);
441 assert(index < sessions.apicount);
442 return clientCtx->values[index].value;
445 void ctxClientValueSet(struct AFB_clientCtx *clientCtx, int index, void *value, void (*free_value)(void*))
447 struct client_value prev;
448 assert(clientCtx != NULL);
450 assert(index < sessions.apicount);
451 prev = clientCtx->values[index];
452 clientCtx->values[index] = (struct client_value){.value = value, .free_value = free_value};
453 if (prev.value != NULL && prev.free_value != NULL)
454 prev.free_value(prev.value);