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