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