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;
71 // Free context [XXXX Should be protected again memory abort XXXX]
72 static void ctxUuidFreeCB (struct AFB_clientCtx *client)
76 // If application add a handle let's free it now
77 assert (client->values != NULL);
79 // Free client handle with a standard Free function, with app callback or ignore it
80 for (idx=0; idx < sessions.apicount; idx ++)
81 ctxClientValueSet(client, idx, NULL, NULL);
84 // Create a new store in RAM, not that is too small it will be automatically extended
85 void ctxStoreInit (int max_session_count, int timeout, const char *initok, int context_count)
88 // let's create as store as hashtable does not have any
89 sessions.store = calloc (1 + (unsigned)max_session_count, sizeof(struct AFB_clientCtx));
90 sessions.max = max_session_count;
91 sessions.timeout = timeout;
92 sessions.apicount = context_count;
94 ERROR("\"--token=\" parameter is mandatory");
97 if (strlen(initok) >= sizeof(sessions.store[0]->token)) {
98 ERROR("initial token '%s' too long (max length 36)", initok);
101 sessions.initok = initok;
104 static struct AFB_clientCtx *ctxStoreSearch (const char* uuid)
107 struct AFB_clientCtx *client;
109 assert (uuid != NULL);
111 pthread_mutex_lock(&sessions.mutex);
113 for (idx=0; idx < sessions.max; idx++) {
114 client = sessions.store[idx];
115 if (client && (0 == strcmp (uuid, client->uuid)))
121 pthread_mutex_unlock(&sessions.mutex);
125 static int ctxStoreDel (struct AFB_clientCtx *client)
130 assert (client != NULL);
132 pthread_mutex_lock(&sessions.mutex);
134 for (idx=0; idx < sessions.max; idx++) {
135 if (sessions.store[idx] == client) {
136 sessions.store[idx] = NULL;
144 pthread_mutex_unlock(&sessions.mutex);
148 static int ctxStoreAdd (struct AFB_clientCtx *client)
153 assert (client != NULL);
155 pthread_mutex_lock(&sessions.mutex);
157 for (idx=0; idx < sessions.max; idx++) {
158 if (NULL == sessions.store[idx]) {
159 sessions.store[idx] = client;
167 pthread_mutex_unlock(&sessions.mutex);
171 // Check if context timeout or not
172 static int ctxStoreTooOld (struct AFB_clientCtx *ctx, time_t now)
174 assert (ctx != NULL);
175 return ctx->expiration < now;
178 // Check if context is active or not
179 static int ctxIsActive (struct AFB_clientCtx *ctx, time_t now)
181 assert (ctx != NULL);
182 return ctx->uuid[0] != 0 && ctx->expiration >= now;
185 // Loop on every entry and remove old context sessions.hash
186 static void ctxStoreCleanUp (time_t now)
188 struct AFB_clientCtx *ctx;
191 // Loop on Sessions Table and remove anything that is older than timeout
192 for (idx=0; idx < sessions.max; idx++) {
193 ctx = sessions.store[idx];
194 if (ctx != NULL && ctxStoreTooOld(ctx, now)) {
195 ctxClientClose (ctx);
200 // This function will return exiting client context or newly created client context
201 struct AFB_clientCtx *ctxClientGetSession (const char *uuid, int *created)
204 struct AFB_clientCtx *clientCtx;
209 ctxStoreCleanUp (now);
211 /* search for an existing one not too old */
213 if (strlen(uuid) >= sizeof clientCtx->uuid) {
217 clientCtx = ctxStoreSearch(uuid);
218 if (clientCtx != NULL) {
224 /* returns a new one */
225 clientCtx = calloc(1, sizeof(struct AFB_clientCtx) + ((unsigned)sessions.apicount * sizeof(*clientCtx->values)));
226 if (clientCtx == NULL) {
230 clientCtx->values = (void*)(clientCtx + 1);
232 /* generate the uuid */
234 uuid_generate(newuuid);
235 uuid_unparse_lower(newuuid, clientCtx->uuid);
237 strcpy(clientCtx->uuid, uuid);
241 strcpy(clientCtx->token, sessions.initok);
242 clientCtx->expiration = now + sessions.timeout;
243 if (!ctxStoreAdd (clientCtx)) {
250 clientCtx->access = now;
251 clientCtx->refcount++;
260 struct AFB_clientCtx *ctxClientAddRef(struct AFB_clientCtx *clientCtx)
262 if (clientCtx != NULL)
263 clientCtx->refcount++;
267 void ctxClientUnref(struct AFB_clientCtx *clientCtx)
269 if (clientCtx != NULL) {
270 assert(clientCtx->refcount != 0);
271 --clientCtx->refcount;
272 if (clientCtx->refcount == 0 && clientCtx->uuid[0] == 0) {
273 ctxStoreDel (clientCtx);
278 // Free Client Session Context
279 void ctxClientClose (struct AFB_clientCtx *clientCtx)
281 assert(clientCtx != NULL);
282 ctxUuidFreeCB (clientCtx);
283 clientCtx->uuid[0] = 0;
286 // Sample Generic Ping Debug API
287 int ctxTokenCheck (struct AFB_clientCtx *clientCtx, const char *token)
289 assert(clientCtx != NULL);
290 assert(token != NULL);
292 // compare current token with previous one
293 if (!ctxIsActive (clientCtx, NOW))
296 if (clientCtx->token[0] && strcmp (token, clientCtx->token) != 0)
302 // generate a new token and update client context
303 void ctxTokenNew (struct AFB_clientCtx *clientCtx)
307 assert(clientCtx != NULL);
309 // Old token was valid let's regenerate a new one
310 uuid_generate(newuuid); // create a new UUID
311 uuid_unparse_lower(newuuid, clientCtx->token);
313 // keep track of time for session timeout and further clean up
314 clientCtx->expiration = NOW + sessions.timeout;
317 static int add_listener(struct afb_event_listener_list **head, struct afb_event_listener listener)
319 struct afb_event_listener_list *iter, **prv;
325 iter = calloc(1, sizeof *iter);
330 iter->listener = listener;
335 if (iter->listener.itf == listener.itf && iter->listener.closure == listener.closure) {
343 int ctxClientEventListenerAdd(struct AFB_clientCtx *clientCtx, struct afb_event_listener listener)
345 return add_listener(clientCtx != NULL ? &clientCtx->listeners : &sessions.listeners, listener);
348 static void remove_listener(struct afb_event_listener_list **head, struct afb_event_listener listener)
350 struct afb_event_listener_list *iter, **prv;
357 if (iter->listener.itf == listener.itf && iter->listener.closure == listener.closure) {
358 if (!--iter->refcount) {
368 void ctxClientEventListenerRemove(struct AFB_clientCtx *clientCtx, struct afb_event_listener listener)
370 remove_listener(clientCtx != NULL ? &clientCtx->listeners : &sessions.listeners, listener);
373 static int send(struct afb_event_listener_list *head, const char *event, struct json_object *object)
375 struct afb_event_listener_list *iter;
380 while (iter != NULL) {
381 iter->listener.itf->send(iter->listener.closure, event, json_object_get(object));
389 int ctxClientEventSend(struct AFB_clientCtx *clientCtx, const char *event, struct json_object *object)
396 if (clientCtx != NULL) {
397 result = ctxIsActive(clientCtx, now) ? send(clientCtx->listeners, event, object) : 0;
399 result = send(sessions.listeners, event, object);
400 for (idx=0; idx < sessions.max; idx++) {
401 clientCtx = ctxClientAddRef(sessions.store[idx]);
402 if (clientCtx != NULL && ctxIsActive(clientCtx, now)) {
403 clientCtx = ctxClientAddRef(clientCtx);
404 result += send(clientCtx->listeners, event, object);
406 ctxClientUnref(clientCtx);
412 const char *ctxClientGetUuid (struct AFB_clientCtx *clientCtx)
414 assert(clientCtx != NULL);
415 return clientCtx->uuid;
418 const char *ctxClientGetToken (struct AFB_clientCtx *clientCtx)
420 assert(clientCtx != NULL);
421 return clientCtx->token;
424 void *ctxClientValueGet(struct AFB_clientCtx *clientCtx, int index)
426 assert(clientCtx != NULL);
428 assert(index < sessions.apicount);
429 return clientCtx->values[index].value;
432 void ctxClientValueSet(struct AFB_clientCtx *clientCtx, int index, void *value, void (*free_value)(void*))
434 struct client_value prev;
435 assert(clientCtx != NULL);
437 assert(index < sessions.apicount);
438 prev = clientCtx->values[index];
439 clientCtx->values[index] = (struct client_value){.value = value, .free_value = free_value};
440 if (prev.value != NULL && prev.free_value != NULL)
441 prev.free_value(prev.value);