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 = 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);
283 // Free Client Session Context
284 void ctxClientClose (struct AFB_clientCtx *clientCtx)
286 assert(clientCtx != NULL);
287 ctxUuidFreeCB (clientCtx);
288 clientCtx->uuid[0] = 0;
291 // Sample Generic Ping Debug API
292 int ctxTokenCheck (struct AFB_clientCtx *clientCtx, const char *token)
294 assert(clientCtx != NULL);
295 assert(token != NULL);
297 // compare current token with previous one
298 if (!ctxIsActive (clientCtx, NOW))
301 if (clientCtx->token[0] && strcmp (token, clientCtx->token) != 0)
307 // generate a new token and update client context
308 void ctxTokenNew (struct AFB_clientCtx *clientCtx)
310 assert(clientCtx != NULL);
312 // Old token was valid let's regenerate a new one
313 new_uuid(clientCtx->token);
315 // keep track of time for session timeout and further clean up
316 clientCtx->expiration = NOW + sessions.timeout;
319 static int add_listener(struct afb_event_listener_list **head, struct afb_event_listener listener)
321 struct afb_event_listener_list *iter, **prv;
327 iter = calloc(1, sizeof *iter);
332 iter->listener = listener;
337 if (iter->listener.itf == listener.itf && iter->listener.closure == listener.closure) {
345 int ctxClientEventListenerAdd(struct AFB_clientCtx *clientCtx, struct afb_event_listener listener)
347 return add_listener(clientCtx != NULL ? &clientCtx->listeners : &sessions.listeners, listener);
350 static void remove_listener(struct afb_event_listener_list **head, struct afb_event_listener listener)
352 struct afb_event_listener_list *iter, **prv;
359 if (iter->listener.itf == listener.itf && iter->listener.closure == listener.closure) {
360 if (!--iter->refcount) {
370 void ctxClientEventListenerRemove(struct AFB_clientCtx *clientCtx, struct afb_event_listener listener)
372 remove_listener(clientCtx != NULL ? &clientCtx->listeners : &sessions.listeners, listener);
375 static int send(struct afb_event_listener_list *head, const char *event, struct json_object *object)
377 struct afb_event_listener_list *iter;
382 while (iter != NULL) {
383 if (iter->listener.itf->expects == NULL || iter->listener.itf->expects(iter->listener.closure, event)) {
384 iter->listener.itf->send(iter->listener.closure, event, json_object_get(object));
393 int ctxClientEventSend(struct AFB_clientCtx *clientCtx, const char *event, struct json_object *object)
400 if (clientCtx != NULL) {
401 result = ctxIsActive(clientCtx, now) ? send(clientCtx->listeners, event, object) : 0;
403 result = send(sessions.listeners, event, object);
404 for (idx=0; idx < sessions.max; idx++) {
405 clientCtx = ctxClientAddRef(sessions.store[idx]);
406 if (clientCtx != NULL && ctxIsActive(clientCtx, now)) {
407 clientCtx = ctxClientAddRef(clientCtx);
408 result += send(clientCtx->listeners, event, object);
410 ctxClientUnref(clientCtx);
416 const char *ctxClientGetUuid (struct AFB_clientCtx *clientCtx)
418 assert(clientCtx != NULL);
419 return clientCtx->uuid;
422 const char *ctxClientGetToken (struct AFB_clientCtx *clientCtx)
424 assert(clientCtx != NULL);
425 return clientCtx->token;
428 void *ctxClientValueGet(struct AFB_clientCtx *clientCtx, int index)
430 assert(clientCtx != NULL);
432 assert(index < sessions.apicount);
433 return clientCtx->values[index].value;
436 void ctxClientValueSet(struct AFB_clientCtx *clientCtx, int index, void *value, void (*free_value)(void*))
438 struct client_value prev;
439 assert(clientCtx != NULL);
441 assert(index < sessions.apicount);
442 prev = clientCtx->values[index];
443 clientCtx->values[index] = (struct client_value){.value = value, .free_value = free_value};
444 if (prev.value != NULL && prev.free_value != NULL)
445 prev.free_value(prev.value);