2 * Copyright (C) 2015 "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 = ctxClientAddRef(sessions.store[idx]);
201 if (ctx != NULL && ctxStoreTooOld(ctx, now)) {
202 ctxClientClose (ctx);
208 // This function will return exiting client context or newly created client context
209 struct AFB_clientCtx *ctxClientGetSession (const char *uuid, int *created)
211 struct AFB_clientCtx *clientCtx;
216 ctxStoreCleanUp (now);
218 /* search for an existing one not too old */
220 if (strlen(uuid) >= sizeof clientCtx->uuid) {
224 clientCtx = ctxStoreSearch(uuid);
225 if (clientCtx != NULL) {
231 /* returns a new one */
232 clientCtx = calloc(1, sizeof(struct AFB_clientCtx) + ((unsigned)sessions.apicount * sizeof(*clientCtx->values)));
233 if (clientCtx == NULL) {
237 clientCtx->values = (void*)(clientCtx + 1);
239 /* generate the uuid */
241 new_uuid(clientCtx->uuid);
243 strcpy(clientCtx->uuid, uuid);
247 strcpy(clientCtx->token, sessions.initok);
248 clientCtx->expiration = now + sessions.timeout;
249 if (!ctxStoreAdd (clientCtx)) {
256 clientCtx->access = now;
257 clientCtx->refcount++;
266 struct AFB_clientCtx *ctxClientAddRef(struct AFB_clientCtx *clientCtx)
268 if (clientCtx != NULL)
269 clientCtx->refcount++;
273 void ctxClientUnref(struct AFB_clientCtx *clientCtx)
275 if (clientCtx != NULL) {
276 assert(clientCtx->refcount != 0);
277 --clientCtx->refcount;
278 if (clientCtx->refcount == 0 && clientCtx->uuid[0] == 0) {
279 ctxStoreDel (clientCtx);
285 // Free Client Session Context
286 void ctxClientClose (struct AFB_clientCtx *clientCtx)
288 assert(clientCtx != NULL);
289 if (clientCtx->uuid[0] != 0) {
290 clientCtx->uuid[0] = 0;
291 ctxUuidFreeCB (clientCtx);
292 while(clientCtx->listeners != NULL)
293 ctxClientEventListenerRemove(clientCtx, clientCtx->listeners->listener);
297 // Sample Generic Ping Debug API
298 int ctxTokenCheck (struct AFB_clientCtx *clientCtx, const char *token)
300 assert(clientCtx != NULL);
301 assert(token != NULL);
303 // compare current token with previous one
304 if (!ctxIsActive (clientCtx, NOW))
307 if (clientCtx->token[0] && strcmp (token, clientCtx->token) != 0)
313 // generate a new token and update client context
314 void ctxTokenNew (struct AFB_clientCtx *clientCtx)
316 assert(clientCtx != NULL);
318 // Old token was valid let's regenerate a new one
319 new_uuid(clientCtx->token);
321 // keep track of time for session timeout and further clean up
322 clientCtx->expiration = NOW + sessions.timeout;
325 static int add_listener(struct afb_event_listener_list **head, struct afb_event_listener listener)
327 struct afb_event_listener_list *iter, **prv;
333 iter = calloc(1, sizeof *iter);
338 iter->listener = listener;
343 if (iter->listener.itf == listener.itf && iter->listener.closure == listener.closure) {
351 int ctxClientEventListenerAdd(struct AFB_clientCtx *clientCtx, struct afb_event_listener listener)
353 return add_listener(clientCtx != NULL ? &clientCtx->listeners : &sessions.listeners, listener);
356 static void remove_listener(struct afb_event_listener_list **head, struct afb_event_listener listener)
358 struct afb_event_listener_list *iter, **prv;
365 if (iter->listener.itf == listener.itf && iter->listener.closure == listener.closure) {
366 if (!--iter->refcount) {
376 void ctxClientEventListenerRemove(struct AFB_clientCtx *clientCtx, struct afb_event_listener listener)
378 remove_listener(clientCtx != NULL ? &clientCtx->listeners : &sessions.listeners, listener);
381 static int send(struct afb_event_listener_list *head, const char *event, struct json_object *object)
383 struct afb_event_listener_list *iter;
388 while (iter != NULL) {
389 if (iter->listener.itf->expects == NULL || iter->listener.itf->expects(iter->listener.closure, event)) {
390 iter->listener.itf->send(iter->listener.closure, event, json_object_get(object));
399 int ctxClientEventSend(struct AFB_clientCtx *clientCtx, const char *event, struct json_object *object)
406 if (clientCtx != NULL) {
407 result = ctxIsActive(clientCtx, now) ? send(clientCtx->listeners, event, object) : 0;
409 result = send(sessions.listeners, event, object);
410 for (idx=0; idx < sessions.max; idx++) {
411 clientCtx = ctxClientAddRef(sessions.store[idx]);
412 if (clientCtx != NULL && ctxIsActive(clientCtx, now)) {
413 clientCtx = ctxClientAddRef(clientCtx);
414 result += send(clientCtx->listeners, event, object);
416 ctxClientUnref(clientCtx);
422 const char *ctxClientGetUuid (struct AFB_clientCtx *clientCtx)
424 assert(clientCtx != NULL);
425 return clientCtx->uuid;
428 const char *ctxClientGetToken (struct AFB_clientCtx *clientCtx)
430 assert(clientCtx != NULL);
431 return clientCtx->token;
434 void *ctxClientValueGet(struct AFB_clientCtx *clientCtx, int index)
436 assert(clientCtx != NULL);
438 assert(index < sessions.apicount);
439 return clientCtx->values[index].value;
442 void ctxClientValueSet(struct AFB_clientCtx *clientCtx, int index, void *value, void (*free_value)(void*))
444 struct client_value prev;
445 assert(clientCtx != NULL);
447 assert(index < sessions.apicount);
448 prev = clientCtx->values[index];
449 clientCtx->values[index] = (struct client_value){.value = value, .free_value = free_value};
450 if (prev.value != NULL && prev.free_value != NULL)
451 prev.free_value(prev.value);