Merge origin/master
[src/app-framework-binder.git] / src / rest-api.c
1 /*
2  * Copyright (C) 2015 "IoT.bzh"
3  * Author "Fulup Ar Foll"
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  * 
18  * Contain all generic part to handle REST/API
19  * 
20  *  https://www.gnu.org/software/libmicrohttpd/tutorial.html [search 'largepost.c']
21  */
22
23 #include "../include/local-def.h"
24
25 #include <dirent.h>
26 #include <dlfcn.h>
27 #include <setjmp.h>
28 #include <signal.h>
29
30 #define AFB_MSG_JTYPE "AJB_reply"
31
32
33
34 static json_object     *afbJsonType;
35
36
37 // Because of POST call multiple time requestApi we need to free POST handle here
38 // Note this method is called from http-svc just before closing session
39 PUBLIC void endPostRequest(AFB_PostHandle *postHandle) {
40
41     if (postHandle->type == AFB_POST_JSON) {
42         // if (verbose) fprintf(stderr, "End PostJson Request UID=%d\n", postHandle->uid);
43     }
44
45     if (postHandle->type == AFB_POST_FORM) {
46          if (verbose) fprintf(stderr, "End PostForm Request UID=%d\n", postHandle->uid);
47     }
48     free(postHandle->private);
49     free(postHandle);
50 }
51
52 // Check of apiurl is declare in this plugin and call it
53 STATIC AFB_error callPluginApi(AFB_plugin *plugin, AFB_request *request, void *context) {
54     json_object *jresp, *jcall;
55     int idx, status, sig;
56     int signals[]= {SIGALRM, SIGSEGV, SIGFPE, 0};
57     
58     /*---------------------------------------------------------------
59     | Signal handler defined inside CallPluginApi to access Request
60     +---------------------------------------------------------------- */
61     void pluginError (int signum) {
62       sigset_t sigset;
63       AFB_clientCtx *context;
64               
65       // unlock signal to allow a new signal to come
66       sigemptyset (&sigset);
67       sigaddset   (&sigset, signum);
68       sigprocmask (SIG_UNBLOCK, &sigset, 0);
69
70       fprintf (stderr, "Oops:%s Plugin Api Timeout timeout\n", configTime());
71       longjmp (request->checkPluginCall, signum);
72     }
73
74     
75     // If a plugin hold this urlpath call its callback
76     for (idx = 0; plugin->apis[idx].callback != NULL; idx++) {
77         if (!strcmp(plugin->apis[idx].name, request->api)) {
78             
79             // Request was found and at least partially executed
80             request->jresp  = json_object_new_object();
81             json_object_get (afbJsonType);  // increate jsontype reference count
82             json_object_object_add (request->jresp, "jtype", afbJsonType);
83             
84             // prepare an object to store calling values
85             jcall=json_object_new_object();
86             json_object_object_add(jcall, "prefix", json_object_new_string (plugin->prefix));
87             json_object_object_add(jcall, "api"   , json_object_new_string (plugin->apis[idx].name));
88             
89             // save context before calling the API
90             status = setjmp (request->checkPluginCall);
91             if (status != 0) {    
92                 
93                 // Plugin aborted somewhere during its execution
94                 json_object_object_add(jcall, "status", json_object_new_string ("abort"));
95                 json_object_object_add(jcall, "info" ,  json_object_new_string ("Plugin broke during execution"));
96                 json_object_object_add(request->jresp, "request", jcall);
97                 
98             } else {
99                 
100                 // If timeout protection==0 we are in debug and we do not apply signal protection
101                 if (request->config->apiTimeout > 0) {
102                     for (sig=0; signals[sig] != 0; sig++) {
103                        if (signal (signals[sig], pluginError) == SIG_ERR) {
104                             request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
105                             json_object_object_add(jcall, "status", json_object_new_string ("fail"));
106                             json_object_object_add(jcall, "info", json_object_new_string ("Setting Timeout Handler Failed"));
107                             json_object_object_add(request->jresp, "request", jcall);
108                             return AFB_DONE;
109                        }
110                     }
111                     // Trigger a timer to protect from unacceptable long time execution
112                     alarm (request->config->apiTimeout);
113                 }
114
115                 // Out of SessionNone every call get a client context session
116                 if (AFB_SESSION_NONE != plugin->apis[idx].session) {
117                     
118                     // add client context to request
119                     if (ctxClientGet(request, plugin) != AFB_SUCCESS) {
120                         request->errcode=MHD_HTTP_INSUFFICIENT_STORAGE;
121                         json_object_object_add(jcall, "status", json_object_new_string ("fail"));
122                         json_object_object_add(jcall, "info", json_object_new_string ("Client Session Context Full !!!"));
123                         json_object_object_add(request->jresp, "request", jcall);
124                         return (AFB_DONE);                              
125                     };
126                     
127                     if (verbose) fprintf(stderr, "Plugin=[%s] Api=[%s] Middleware=[%d] Client=[0x%x] Uuid=[%s] Token=[%s]\n"
128                            , request->plugin, request->api, plugin->apis[idx].session, request->client, request->client->uuid, request->client->token);                        
129                     
130                     switch(plugin->apis[idx].session) {
131
132                         case AFB_SESSION_CREATE:
133                             if (request->client->token[0] != '\0') {
134                                 request->errcode=MHD_HTTP_UNAUTHORIZED;
135                                 json_object_object_add(jcall, "status", json_object_new_string ("exist"));
136                                 json_object_object_add(jcall, "info", json_object_new_string ("AFB_SESSION_CREATE Session already exist"));
137                                 json_object_object_add(request->jresp, "request", jcall);
138                                 return (AFB_DONE);                              
139                             }
140                         
141                             if (AFB_SUCCESS != ctxTokenCreate (request)) {
142                                 request->errcode=MHD_HTTP_UNAUTHORIZED;
143                                 json_object_object_add(jcall, "status", json_object_new_string ("fail"));
144                                 json_object_object_add(jcall, "info", json_object_new_string ("AFB_SESSION_CREATE Invalid Initial Token"));
145                                 json_object_object_add(request->jresp, "request", jcall);
146                                 return (AFB_DONE);
147                             } else {
148                                 json_object_object_add(jcall, "uuid", json_object_new_string (request->client->uuid));                                
149                                 json_object_object_add(jcall, "token", json_object_new_string (request->client->token));                                
150                                 json_object_object_add(jcall, "timeout", json_object_new_int (request->config->cntxTimeout));                                
151                             }
152                             break;
153
154
155                         case AFB_SESSION_RENEW:
156                             if (AFB_SUCCESS != ctxTokenRefresh (request)) {
157                                 request->errcode=MHD_HTTP_UNAUTHORIZED;
158                                 json_object_object_add(jcall, "status", json_object_new_string ("fail"));
159                                 json_object_object_add(jcall, "info", json_object_new_string ("AFB_SESSION_REFRESH Broken Exchange Token Chain"));
160                                 json_object_object_add(request->jresp, "request", jcall);
161                                 return (AFB_DONE);
162                             } else {
163                                 json_object_object_add(jcall, "uuid", json_object_new_string (request->client->uuid));                                
164                                 json_object_object_add(jcall, "token", json_object_new_string (request->client->token));                                
165                                 json_object_object_add(jcall, "timeout", json_object_new_int (request->config->cntxTimeout));                                
166                             }
167                             break;
168
169                         case AFB_SESSION_CLOSE:
170                             if (AFB_SUCCESS != ctxTokenCheck (request)) {
171                                 request->errcode=MHD_HTTP_UNAUTHORIZED;
172                                 json_object_object_add(jcall, "status", json_object_new_string ("empty"));
173                                 json_object_object_add(jcall, "info", json_object_new_string ("AFB_SESSION_CLOSE Not a Valid Access Token"));
174                                 json_object_object_add(request->jresp, "request", jcall);
175                                 return (AFB_DONE);
176                             } else {
177                                 json_object_object_add(jcall, "uuid", json_object_new_string (request->client->uuid));                                
178                             }
179                             break;
180                         
181                         case AFB_SESSION_CHECK:
182                         default: 
183                             // default action is check
184                             if (AFB_SUCCESS != ctxTokenCheck (request)) {
185                                 request->errcode=MHD_HTTP_UNAUTHORIZED;
186                                 json_object_object_add(jcall, "status", json_object_new_string ("fail"));
187                                 json_object_object_add(jcall, "info", json_object_new_string ("AFB_SESSION_CHECK Invalid Active Token"));
188                                 json_object_object_add(request->jresp, "request", jcall);
189                                 return (AFB_DONE);
190                             }
191                             break;
192                     }
193                 }
194                 
195                 // Effectively call the API with a subset of the context
196                 jresp = plugin->apis[idx].callback(request, context);
197                 
198                 // handle intemediatry Post Iterates out of band
199                 if ((jresp == NULL) && (request->errcode == MHD_HTTP_OK)) return (AFB_SUCCESS);
200
201                 // Session close is done after the API call so API can still use session in closing API
202                 if (AFB_SESSION_CLOSE == plugin->apis[idx].session) ctxTokenReset (request);                    
203                 
204                 // API should return NULL of a valid Json Object
205                 if (jresp == NULL) {
206                     json_object_object_add(jcall, "status", json_object_new_string ("null"));
207                     json_object_object_add(request->jresp, "request", jcall);
208                     request->errcode = MHD_HTTP_NO_RESPONSE;
209                     
210                 } else {
211                     json_object_object_add(jcall, "status", json_object_new_string ("processed"));
212                     json_object_object_add(request->jresp, "request", jcall);
213                     json_object_object_add(request->jresp, "response", jresp);
214                 }
215                 // cancel timeout and plugin signal handle before next call
216                 if (request->config->apiTimeout > 0) {
217                     alarm (0);
218                     for (sig=0; signals[sig] != 0; sig++) {
219                        signal (signals[sig], SIG_DFL);
220                     }
221                 }              
222             }       
223             return (AFB_DONE);
224         }
225     }   
226     return (AFB_FAIL);
227 }
228
229 STATIC AFB_error findAndCallApi (AFB_request *request, void *context) {
230     int idx;
231     AFB_error status;
232     
233     if (!request->api || !request->plugin) return (AFB_FAIL);
234    
235     // Search for a plugin with this urlpath
236     for (idx = 0; request->plugins[idx] != NULL; idx++) {
237         if (!strcmp(request->plugins[idx]->prefix, request->plugin)) {
238             status =callPluginApi(request->plugins[idx], request, context);
239             break;
240         }
241     }
242     // No plugin was found
243     if (request->plugins[idx] == NULL) {
244         request->jresp = jsonNewMessage(AFB_FATAL, "No Plugin=[%s] Url=%s", request->plugin, request->url);
245         goto ExitOnError;
246     }  
247     
248     // plugin callback did not return a valid Json Object
249     if (status == AFB_FAIL) {
250         request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->api, request->plugin, request->url);
251         goto ExitOnError;
252     }
253     
254     // Everything look OK
255     return (status);
256     
257 ExitOnError:
258     request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
259     return (AFB_FAIL);
260 }
261
262 // This CB is call for every item with a form post it reformat iterator values
263 // and callback Plugin API for each Item within PostForm.
264 doPostIterate (void *cls, enum MHD_ValueKind kind, const char *key,
265               const char *filename, const char *mimetype,
266               const char *encoding, const char *data, uint64_t offset,
267               size_t size) {
268   
269   AFB_error    status;
270   AFB_PostItem item;
271     
272   // retrieve API request from Post iterator handle  
273   AFB_PostHandle *postHandle  = (AFB_PostHandle*)cls;
274   AFB_request *request = (AFB_request*)postHandle->private;
275   AFB_PostRequest postRequest;
276   
277   fprintf (stderr, "postHandle key=%s filename=%s len=%d mime=%s\n", key, filename, size, mimetype);
278    
279   // Create and Item value for Plugin API
280   item.kind     = kind;
281   item.key      = key;
282   item.filename = filename;
283   item.mimetype = mimetype;
284   item.encoding = encoding;
285   item.len      = size;
286   item.data     = data;
287   item.offset   = offset;
288   
289   // Reformat Request to make it somehow similar to GET/PostJson case
290   postRequest.data= (char*) postHandle;
291   postRequest.len = size;
292   postRequest.type= AFB_POST_FORM;;
293   request->post = &postRequest;
294   
295   // effectively call plugin API                 
296   status = findAndCallApi (request, &item);
297   // when returning no processing of postform stop
298   if (status != AFB_SUCCESS) return MHD_NO;
299   
300   // let's allow iterator to move to next item
301   return (MHD_YES);
302 }
303
304 STATIC void freeRequest (AFB_request *request) {
305
306  free (request->plugin);    
307  free (request->api);    
308  free (request);    
309 }
310
311 STATIC AFB_request *createRequest (struct MHD_Connection *connection, AFB_session *session, const char* url) {
312     
313     AFB_request *request;
314     
315     // Start with a clean request
316     request = calloc (1, sizeof (AFB_request));
317     char *urlcpy1, *urlcpy2;
318     char *baseapi, *baseurl;  
319       
320     // Extract plugin urlpath from request and make two copy because strsep overload copy
321     urlcpy1 = urlcpy2 = strdup(url);
322     baseurl = strsep(&urlcpy2, "/");
323     if (baseurl == NULL) {
324         request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call url=[%s]", url);
325         request->errcode = MHD_HTTP_BAD_REQUEST;
326         goto Done;
327     }
328
329     // let's compute URL and call API
330     baseapi = strsep(&urlcpy2, "/");
331     if (baseapi == NULL) {
332         request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call plugin=[%s] url=[%s]", baseurl, url);
333         request->errcode = MHD_HTTP_BAD_REQUEST;
334         goto Done;
335     }
336     
337     // build request structure
338     request->connection = connection;
339     request->config = session->config;
340     request->url    = url;
341     request->plugin = strdup (baseurl);
342     request->api    = strdup (baseapi);
343     request->plugins= session->plugins;
344
345 Done:    
346     free(urlcpy1);
347     return (request);
348 }
349
350 // process rest API query
351 PUBLIC int doRestApi(struct MHD_Connection *connection, AFB_session *session, const char* url, const char *method
352     , const char *upload_data, size_t *upload_data_size, void **con_cls) {
353     
354     static int postcount = 0; // static counter to debug POST protocol
355     json_object *errMessage;
356     AFB_error status;
357     struct MHD_Response *webResponse;
358     const char *serialized;
359     AFB_request *request;
360     AFB_PostHandle *postHandle;
361     AFB_PostRequest postRequest;
362     int ret;
363   
364     // if post data may come in multiple calls
365     if (0 == strcmp(method, MHD_HTTP_METHOD_POST)) {
366         const char *encoding, *param;
367         int contentlen = -1;
368         postHandle = *con_cls;
369
370         // This is the initial post event let's create form post structure POST datas come in multiple events
371         if (postHandle == NULL) {
372
373             // allocate application POST processor handle to zero
374             postHandle = calloc(1, sizeof (AFB_PostHandle));
375             postHandle->uid = postcount++; // build a UID for DEBUG
376             *con_cls = postHandle;  // update context with posthandle
377             
378             // Let make sure we have the right encoding and a valid length
379             encoding = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE);
380             
381             // We are facing an empty post let's process it as a get
382             if (encoding == NULL) {
383                 request= createRequest (connection, session, url);
384                 goto ProcessApiCall;
385             }
386         
387             // Form post is handle through a PostProcessor and call API once per form key
388             if (strcasestr(encoding, FORM_CONTENT) != NULL) {
389                 if (verbose) fprintf(stderr, "Create PostForm[uid=%d]\n", postHandle->uid);
390
391                 request = createRequest (connection, session, url);
392                 if (request->jresp != NULL) goto ProcessApiCall;
393
394                 postHandle = malloc(sizeof (AFB_PostHandle)); // allocate application POST processor handle
395                 postHandle->type   = AFB_POST_FORM;
396                 postHandle->pp     = MHD_create_post_processor (connection, MAX_POST_SIZE, doPostIterate, postHandle);
397                 postHandle->private= (void*)request;
398                 
399                 if (NULL == postHandle->pp) {
400                     fprintf(stderr,"OOPS: Internal error fail to allocate MHD_create_post_processor\n");
401                     free (postHandle);
402                     return MHD_NO;
403                 }
404                 return MHD_YES;
405             }           
406         
407             // POST json is store into a buffer and present in one piece to API
408             if (strcasestr(encoding, JSON_CONTENT) != NULL) {
409
410                 param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
411                 if (param) sscanf(param, "%i", &contentlen);
412
413                 // Because PostJson are build in RAM size is constrained
414                 if (contentlen > MAX_POST_SIZE) {
415                     errMessage = jsonNewMessage(AFB_FATAL, "Post Date to big %d > %d", contentlen, MAX_POST_SIZE);
416                     goto ExitOnError;
417                 }
418
419                 // Size is OK, let's allocate a buffer to hold post data
420                 postHandle->type = AFB_POST_JSON;
421                 postHandle->private = malloc(contentlen + 1); // allocate memory for full POST data + 1 for '\0' enf of string
422
423                 // if (verbose) fprintf(stderr, "Create PostJson[uid=%d] Size=%d\n", postHandle->uid, contentlen);
424                 return MHD_YES;
425
426             } else {
427                 // We only support Json and Form Post format
428                 errMessage = jsonNewMessage(AFB_FATAL, "Post Date wrong type encoding=%s != %s", encoding, JSON_CONTENT);
429                 goto ExitOnError;                
430             }   
431         }
432
433         // This time we receive partial/all Post data. Note that even if we get all POST data. We should nevertheless
434         // return MHD_YES and not process the request directly. Otherwise Libmicrohttpd is unhappy and fails with
435         // 'Internal application error, closing connection'.            
436         if (*upload_data_size) {
437     
438             if (postHandle->type == AFB_POST_FORM) {
439                 // if (verbose) fprintf(stderr, "Processing PostForm[uid=%d]\n", postHandle->uid);
440                 MHD_post_process (postHandle->pp, upload_data, *upload_data_size);
441             }
442             
443             // Process JsonPost request when buffer is completed let's call API    
444             if (postHandle->type == AFB_POST_JSON) {
445                 // if (verbose) fprintf(stderr, "Updating PostJson[uid=%d]\n", postHandle->uid);
446                 memcpy(&postHandle->private[postHandle->len], upload_data, *upload_data_size);
447                 postHandle->len = postHandle->len + *upload_data_size;
448             }
449             
450             *upload_data_size = 0;
451             return MHD_YES;
452             
453         } else {  // we have finish with Post reception let's finish the work
454             
455             // Create a request structure to finalise the request
456             request= createRequest (connection, session, url);
457             if (request->jresp != NULL) {
458                 errMessage = request->jresp;
459                 goto ExitOnError;
460             }
461             
462             // Postform add application context handle to request
463             if (postHandle->type == AFB_POST_FORM) {
464                postRequest.data = (char*) postHandle;
465                postRequest.type = postHandle->type;
466                request->post = &postRequest;
467             }
468             
469             if (postHandle->type == AFB_POST_JSON) {
470                 // if (verbose) fprintf(stderr, "Processing PostJson[uid=%d]\n", postHandle->uid);
471
472                 param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
473                 if (param) sscanf(param, "%i", &contentlen);
474
475                 // At this level we're may verify that we got everything and process DATA
476                 if (postHandle->len != contentlen) {
477                     errMessage = jsonNewMessage(AFB_FATAL, "Post Data Incomplete UID=%d Len %d != %d", postHandle->uid, contentlen, postHandle->len);
478                     goto ExitOnError;
479                 }
480
481                 // Before processing data, make sure buffer string is properly ended
482                 postHandle->private[postHandle->len] = '\0';
483                 postRequest.data = postHandle->private;
484                 postRequest.type = postHandle->type;
485                 request->post = &postRequest;
486
487                 // if (verbose) fprintf(stderr, "Close Post[%d] Buffer=%s\n", postHandle->uid, request->post->data);
488             }
489         }
490     } else {
491         // this is a get we only need a request
492         request= createRequest (connection, session, url);
493     };
494
495 ProcessApiCall:    
496     // Request is ready let's call API without any extra handle
497     status = findAndCallApi (request, NULL);
498
499     serialized = json_object_to_json_string(request->jresp);
500     webResponse = MHD_create_response_from_buffer(strlen(serialized), (void*) serialized, MHD_RESPMEM_MUST_COPY);
501     
502     // client did not pass token on URI let's use cookies 
503     if ((!request->restfull) && (request->client != NULL)) {
504        char cookie[64]; 
505        snprintf (cookie, sizeof (cookie), "%s=%s", COOKIE_NAME,  request->client->uuid); 
506        MHD_add_response_header (webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
507     }
508     
509     // if requested add an error status
510     if (request->errcode != 0)  ret=MHD_queue_response (connection, request->errcode, webResponse);
511     else MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
512     
513     MHD_destroy_response(webResponse);
514     json_object_put(request->jresp); // decrease reference rqtcount to free the json object
515     freeRequest (request);
516     return MHD_YES;
517
518 ExitOnError:
519     freeRequest (request);
520     serialized = json_object_to_json_string(errMessage);
521     webResponse = MHD_create_response_from_buffer(strlen(serialized), (void*) serialized, MHD_RESPMEM_MUST_COPY);
522     MHD_queue_response(connection, MHD_HTTP_BAD_REQUEST, webResponse);
523     MHD_destroy_response(webResponse);
524     json_object_put(errMessage); // decrease reference rqtcount to free the json object
525     return MHD_YES;
526 }
527
528
529 // Loop on plugins. Check that they have the right type, prepare a JSON object with prefix
530 STATIC AFB_plugin ** RegisterJsonPlugins(AFB_plugin **plugins) {
531     int idx, jdx;
532
533     for (idx = 0; plugins[idx] != NULL; idx++) {
534         if (plugins[idx]->type != AFB_PLUGIN_JSON) {
535             fprintf(stderr, "ERROR: AFSV plugin[%d] invalid type=%d != %d\n", idx, AFB_PLUGIN_JSON, plugins[idx]->type);
536         } else {
537             // some sanity controls
538             if ((plugins[idx]->prefix == NULL) || (plugins[idx]->info == NULL) || (plugins[idx]->apis == NULL)) {
539                 if (plugins[idx]->prefix == NULL) plugins[idx]->prefix = "No URL prefix for APIs";
540                 if (plugins[idx]->info == NULL) plugins[idx]->info = "No Info describing plugin APIs";
541                 fprintf(stderr, "ERROR: plugin[%d] invalid prefix=%s info=%s", idx, plugins[idx]->prefix, plugins[idx]->info);
542                 return NULL;
543             }
544
545             if (verbose) fprintf(stderr, "Loading plugin[%d] prefix=[%s] info=%s\n", idx, plugins[idx]->prefix, plugins[idx]->info);
546             
547             // Prebuild plugin jtype to boost API response
548             plugins[idx]->jtype = json_object_new_string(plugins[idx]->prefix);
549             json_object_get(plugins[idx]->jtype); // increase reference count to make it permanent
550             plugins[idx]->prefixlen = strlen(plugins[idx]->prefix);
551             
552               
553             // Prebuild each API jtype to boost API json response
554             for (jdx = 0; plugins[idx]->apis[jdx].name != NULL; jdx++) {
555                 AFB_privateApi *private = malloc (sizeof (AFB_privateApi));
556                 if (plugins[idx]->apis[jdx].private != NULL) {
557                     fprintf (stderr, "WARNING: plugin=%s api=%s private handle should be NULL=0x%x\n"
558                             ,plugins[idx]->prefix,plugins[idx]->apis[jdx].name, plugins[idx]->apis[jdx].private);
559                 }
560                 private->len = strlen (plugins[idx]->apis[jdx].name);
561                 private->jtype=json_object_new_string(plugins[idx]->apis[jdx].name);
562                 json_object_get(private->jtype); // increase reference count to make it permanent
563                 plugins[idx]->apis[jdx].private = private;
564             }
565         }
566     }
567     return (plugins);
568 }
569
570 void initPlugins(AFB_session *session) {
571     static AFB_plugin **plugins;
572     AFB_plugin* (*pluginRegisterFct)(void);
573     void *plugin;
574     char *pluginPath;
575     struct dirent *pluginDir;
576     DIR *dir;
577     afbJsonType = json_object_new_string (AFB_MSG_JTYPE);
578     int num = 0;
579
580     /* pre-allocate for 20 plugins, we will downsize if necessary */
581     plugins = (AFB_plugin **) malloc (20*sizeof(AFB_plugin));
582
583     if ((dir = opendir(session->config->plugins)) == NULL) {
584         fprintf(stderr, "Could not open plugin directory [%s], exiting...\n", session->config->plugins);
585         exit (-1);
586     }
587
588     while ((pluginDir = readdir(dir)) != NULL) {
589
590         if (!strstr (pluginDir->d_name, ".so"))
591             continue;
592
593         asprintf (&pluginPath, "%s/%s", session->config->plugins, pluginDir->d_name);
594         plugin = dlopen (pluginPath, RTLD_NOW | RTLD_LOCAL);
595         pluginRegisterFct = dlsym (plugin, "pluginRegister");
596         free (pluginPath);
597         if (!plugin) {
598             if (verbose) fprintf(stderr, "[%s] is not loadable, continuing...\n", pluginDir->d_name);
599             continue;
600         } else if (!pluginRegisterFct) {
601             if (verbose) fprintf(stderr, "[%s] is not an AFB plugin, continuing...\n", pluginDir->d_name);
602             continue;
603         }
604
605         if (verbose) fprintf(stderr, "[%s] is a valid AFB plugin, loading it\n", pluginDir->d_name);
606         plugins[num] = (AFB_plugin *) malloc (sizeof(AFB_plugin));
607         plugins[num] = (**pluginRegisterFct)();
608         num++;
609         /* only 20 plugins are supported at that time */
610         if (num == 20) break;
611     }
612     plugins = (AFB_plugin **) realloc (plugins, (num+1)*sizeof(AFB_plugin));
613     plugins[num] = NULL;
614
615     closedir (dir);
616
617     if (plugins[0] == NULL) {
618         fprintf(stderr, "No plugins found, afb-daemon is unlikely to work in this configuration, exiting...\n");
619         exit (-1);
620     }
621
622     // complete plugins and save them within current sessions    
623     session->plugins = RegisterJsonPlugins(plugins);
624     session->pluginCount = num;
625 }