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