35e81d7e3c58636e3d83df9e93ce3081f2840864
[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     freeRequest (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             // prepare an object to store calling values
142             jcall=json_object_new_object();
143             json_object_object_add(jcall, "prefix", json_object_new_string (plugin->prefix));
144             json_object_object_add(jcall, "api"   , json_object_new_string (plugin->apis[idx].name));
145             
146             // save context before calling the API
147             status = setjmp (request->checkPluginCall);
148             if (status != 0) {    
149                 
150                 // Plugin aborted somewhere during its execution
151                 json_object_object_add(jcall, "status", json_object_new_string ("abort"));
152                 json_object_object_add(jcall, "info" ,  json_object_new_string ("Plugin broke during execution"));
153                 json_object_object_add(request->jresp, "request", jcall);
154                 
155             } else {
156                 
157                 // If timeout protection==0 we are in debug and we do not apply signal protection
158                 if (request->config->apiTimeout > 0) {
159                     for (sig=0; signals[sig] != 0; sig++) {
160                        if (signal (signals[sig], pluginError) == SIG_ERR) {
161                            request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
162                            request->jresp = jsonNewMessage(AFB_FATAL, "%s ERR: Signal/timeout handler activation fail.", configTime());
163                            return AFB_FAIL;
164                        }
165                     }
166                     // Trigger a timer to protect from unacceptable long time execution
167                     alarm (request->config->apiTimeout);
168                 }
169                 
170                 // add client context to request
171                 ctxClientGet(request, plugin);      
172              
173                 // Effectively call the API with a subset of the context
174                 jresp = plugin->apis[idx].callback(request, context);
175
176                 // Allocate Json object and build response
177                 request->jresp  = json_object_new_object();
178                 json_object_get (afbJsonType);  // increate jsontype reference count
179                 json_object_object_add (request->jresp, "jtype", afbJsonType);
180                 
181                 // API should return NULL of a valid Json Object
182                 if (jresp == NULL) {
183                     json_object_object_add(jcall, "status", json_object_new_string ("null"));
184                     json_object_object_add(request->jresp, "request", jcall);
185                     request->errcode = MHD_HTTP_NO_RESPONSE;
186                     
187                 } else {
188                     json_object_object_add(jcall, "status", json_object_new_string ("processed"));
189                     json_object_object_add(request->jresp, "request", jcall);
190                     json_object_object_add(request->jresp, "response", jresp);
191                 }
192                 // cancel timeout and plugin signal handle before next call
193                 if (request->config->apiTimeout > 0) {
194                     alarm (0);
195                     for (sig=0; signals[sig] != 0; sig++) {
196                        signal (signals[sig], SIG_DFL);
197                     }
198                 }              
199             }       
200             return (AFB_DONE);
201         }
202     }
203     return (AFB_FAIL);
204 }
205
206 STATIC AFB_error findAndCallApi (AFB_request *request, void *context) {
207     int idx;
208     char *baseurl, *baseapi;
209     AFB_error status;
210    
211     // Search for a plugin with this urlpath
212     for (idx = 0; request->plugins[idx] != NULL; idx++) {
213         if (!strcmp(request->plugins[idx]->prefix, baseurl)) {
214             status =callPluginApi(request->plugins[idx], request, context);
215             break;
216         }
217     }
218     // No plugin was found
219     if (request->plugins[idx] == NULL) {
220         request->jresp = jsonNewMessage(AFB_FATAL, "No Plugin=[%s]", request->plugin);
221         goto ExitOnError;
222     }  
223     
224     // plugin callback did not return a valid Json Object
225     if (status != AFB_DONE) {
226         request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s]", request->api, request->plugin);
227         goto ExitOnError;
228     }
229    
230     // Everything look OK
231     return (status);
232     
233 ExitOnError:
234     request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
235     return (AFB_FAIL);
236 }
237
238 // This CB is call for every item with a form post it reformat iterator values
239 // and callback Plugin API for each Item within PostForm.
240 doPostIterate (void *cls, enum MHD_ValueKind kind, const char *key,
241               const char *filename, const char *mimetype,
242               const char *encoding, const char *data, uint64_t offset,
243               size_t size) {
244   
245   AFB_error    status;
246   AFB_PostItem item;
247     
248   // retrieve API request from Post iterator handle  
249   AFB_PostHandle *postHandle  = (AFB_PostHandle*)cls;
250   AFB_request *request = (AFB_request*)postHandle->private;
251   AFB_PostRequest postRequest;
252   
253    
254   // Create and Item value for Plugin API
255   item.kind     = kind;
256   item.key      = key;
257   item.filename = filename;
258   item.mimetype = mimetype;
259   item.encoding = encoding;
260   item.len      = size;
261   item.data     = data;
262   item.offset   = offset;
263   
264   // Reformat Request to make it somehow similar to GET/PostJson case
265   post.data= (char*) postctx;
266   post.len = size;
267   post.type= AFB_POST_FORM;;
268   request->post = &post;
269   
270   // effectively call plugin API                 
271   status = findAndCallApi (request, &item);
272   
273   // when returning no processing of postform stop
274   if (status != AFB_SUCCESS) return MHD_NO;
275   
276   // let's allow iterator to move to next item
277   return (MHD_YES;);
278 }
279
280 STATIC void freeRequest (AFB_request *request) {
281  free (request->plugin);    
282  free (request->api);    
283  free (request);    
284 }
285
286 STATIC AFB_request *createRequest (struct MHD_Connection *connection, AFB_session *session, const char* url) {
287     
288     AFB_request *request;
289     
290     // Start with a clean request
291     request = calloc (1, sizeof (AFB_request));
292     char *urlcpy1, urlcpy2;
293       
294     // Extract plugin urlpath from request and make two copy because strsep overload copy
295     urlcpy1 = urlcpy2 = strdup(url);
296     baseurl = strsep(&urlcpy2, "/");
297     if (baseurl == NULL) {
298         errMessage = jsonNewMessage(AFB_FATAL, "Invalid API call url=[%s]", url);
299         goto ExitOnError;
300     }
301
302     // let's compute URL and call API
303     baseapi = strsep(&urlcpy2, "/");
304     if (baseapi == NULL) {
305         errMessage = jsonNewMessage(AFB_FATAL, "Invalid API call url=[%s]", url);
306         goto ExitOnError;
307     }
308     
309     // build request structure
310     request->connection = connection;
311     request->config = session.config;
312     request->url    = url;
313     request->plugin = strdup (baseurl);
314     request->api    = strdup (baseapi);
315     request->plugins= session->plugins;
316     
317     free(urlcpy1);
318 }
319
320 // process rest API query
321 PUBLIC int doRestApi(struct MHD_Connection *connection, AFB_session *session, const char* url, const char *method
322     , const char *upload_data, size_t *upload_data_size, void **con_cls) {
323     
324     static int postcount = 0; // static counter to debug POST protocol
325     json_object *errMessage;
326     AFB_error status;
327     struct MHD_Response *webResponse;
328     const char *serialized;
329     AFB_request request;
330     AFB_PostHandle *posthandle;
331     int ret;
332   
333     // if post data may come in multiple calls
334     if (0 == strcmp(method, MHD_HTTP_METHOD_POST)) {
335         const char *encoding, *param;
336         int contentlen = -1;
337         posthandle = *con_cls;
338
339         // This is the initial post event let's create form post structure POST datas come in multiple events
340         if (posthandle == NULL) {
341             fprintf(stderr, "This is the 1st Post Event postuid=%d\n", posthandle->uid);
342
343             // allocate application POST processor handle to zero
344             posthandle = cmalloc(1, sizeof (AFB_PostHandle));
345             posthandle->uid = postcount++; // build a UID for DEBUG
346             *con_cls = posthandle;         // attache POST handle to current HTTP request
347             
348             // Let make sure we have the right encoding and a valid length
349             encoding = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE);
350             param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
351             if (param) sscanf(param, "%i", &contentlen);
352         
353             // Form post is handle through a PostProcessor and call API once per form key
354             if (strcasestr(encoding, FORM_CONTENT) != NULL) {
355                
356                 posthandle = malloc(sizeof (AFB_PostHandle)); // allocate application POST processor handle
357                 posthandle->type   = AFB_POST_FORM;
358                 posthandle->private= (void*)createRequest (connection, session, url);
359                 posthandle->pp     = MHD_create_post_processor (connection, MAX_POST_SIZE, doPostIterate, posthandle);
360                
361                 if (NULL == posthandle->pp) {
362                     fprintf(stderr,"OOPS: Internal error fail to allocate MHD_create_post_processor\n");
363                     free (posthandle);
364                     return MHD_NO;
365                 }
366                 return MHD_YES;
367             }           
368         
369             // POST json is store into a buffer and present in one piece to API
370             if (strcasestr(encoding, JSON_CONTENT) != NULL) {
371
372                 if (contentlen > MAX_POST_SIZE) {
373                     errMessage = jsonNewMessage(AFB_FATAL, "Post Date to big %d > %d", contentlen, MAX_POST_SIZE);
374                     goto ExitOnError;
375                 }
376
377                 if (posthandle == NULL) {
378                     posthandle->type = AFB_POST_JSON;
379                     posthandle->private = malloc(contentlen + 1); // allocate memory for full POST data + 1 for '\0' enf of string
380
381                     if (verbose) fprintf(stderr, "Create PostJson[%d] Size=%d\n", posthandle->uid, contentlen);
382                     return MHD_YES;
383                 }
384
385                 // We only support Json and Form Post format
386                 errMessage = jsonNewMessage(AFB_FATAL, "Post Date wrong type encoding=%s != %s", encoding, JSON_CONTENT);
387                 goto ExitOnError;
388             }    
389         }
390
391         // This time we receive partial/all Post data. Note that even if we get all POST data. We should nevertheless
392         // return MHD_YES and not process the request directly. Otherwise Libmicrohttpd is unhappy and fails with
393         // 'Internal application error, closing connection'.            
394         if (*upload_data_size) {
395             if (verbose) fprintf(stderr, "Update Post[%d]\n", posthandle->uid);
396     
397             if (posthandle->type == AFB_POST_FORM) {
398                 MHD_post_process (con_info->postprocessor, upload_data, *upload_data_size);
399             }
400             
401             // Process JsonPost request when buffer is completed let's call API    
402             if (posthandle->type == AFB_POST_JSON) {
403
404                 memcpy(&posthandle->private[posthandle->len], upload_data, *upload_data_size);
405                 posthandle->len = posthandle->len + *upload_data_size;
406                 *upload_data_size = 0;
407             }
408             return MHD_YES;
409             
410         } else {  // we have finish with Post reception let's finish the work
411             
412             // Create a request structure to finalise the request
413             request= createRequest (connection, session, url);
414
415             // We should only start to process DATA after Libmicrohttpd call or application handler with *upload_data_size==0
416             if (posthandle->type == AFB_POST_FORM) {
417                 MHD_post_process (posthandle->pp, upload_data, *upload_data_size);
418             }
419             
420             if (posthandle->type == AFB_POST_JSON) {
421                 // At this level we're may verify that we got everything and process DATA
422                 if (posthandle->len != contentlen) {
423                     errMessage = jsonNewMessage(AFB_FATAL, "Post Data Incomplete UID=%d Len %d != %s", posthandle->uid, contentlen, posthandle->len);
424                     goto ExitOnError;
425                 }
426
427                 // Before processing data, make sure buffer string is properly ended
428                 posthandle->private[posthandle->len] = '\0';
429                 request->post.data = posthandle->private;
430                 request->post.type = posthandle->type;
431
432                 if (verbose) fprintf(stderr, "Close Post[%d] Buffer=%s\n", posthandle->uid, request.post);
433             }
434         }
435     } else {
436         // this is a get we only need a request
437         request= createRequest (connection, session, url);
438     };
439     
440     // Request is ready let's call API without any extra handle
441     status = findAndCallApi (request, NULL);
442     
443 ExitOnResponse:
444     freeRequest (request);
445     serialized = json_object_to_json_string(request.jresp);
446     webResponse = MHD_create_response_from_buffer(strlen(serialized), (void*) serialized, MHD_RESPMEM_MUST_COPY);
447     
448     // client did not pass token on URI let's use cookies 
449     if ((!request.restfull) && (request.client != NULL)) {
450        char cookie[64]; 
451        snprintf (cookie, sizeof (cookie), "%s=%s", COOKIE_NAME,  request.client->uuid); 
452        MHD_add_response_header (webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
453     }
454     
455     // if requested add an error status
456     if (request.errcode != 0)  ret=MHD_queue_response (connection, request.errcode, webResponse);
457     else MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
458     
459     MHD_destroy_response(webResponse);
460     json_object_put(request.jresp); // decrease reference rqtcount to free the json object
461     return MHD_YES;
462
463 ExitOnError:
464     freeRequest (request);
465     serialized = json_object_to_json_string(errMessage);
466     webResponse = MHD_create_response_from_buffer(strlen(serialized), (void*) serialized, MHD_RESPMEM_MUST_COPY);
467     MHD_queue_response(connection, MHD_HTTP_BAD_REQUEST, webResponse);
468     MHD_destroy_response(webResponse);
469     json_object_put(errMessage); // decrease reference rqtcount to free the json object
470     return MHD_YES;
471 }
472
473
474 // Loop on plugins. Check that they have the right type, prepare a JSON object with prefix
475 STATIC AFB_plugin ** RegisterJsonPlugins(AFB_plugin **plugins) {
476     int idx, jdx;
477
478     for (idx = 0; plugins[idx] != NULL; idx++) {
479         if (plugins[idx]->type != AFB_PLUGIN_JSON) {
480             fprintf(stderr, "ERROR: AFSV plugin[%d] invalid type=%d != %d\n", idx, AFB_PLUGIN_JSON, plugins[idx]->type);
481         } else {
482             // some sanity controls
483             if ((plugins[idx]->prefix == NULL) || (plugins[idx]->info == NULL) || (plugins[idx]->apis == NULL)) {
484                 if (plugins[idx]->prefix == NULL) plugins[idx]->prefix = "No URL prefix for APIs";
485                 if (plugins[idx]->info == NULL) plugins[idx]->info = "No Info describing plugin APIs";
486                 fprintf(stderr, "ERROR: plugin[%d] invalid prefix=%s info=%s", idx, plugins[idx]->prefix, plugins[idx]->info);
487                 return NULL;
488             }
489
490             if (verbose) fprintf(stderr, "Loading plugin[%d] prefix=[%s] info=%s\n", idx, plugins[idx]->prefix, plugins[idx]->info);
491             
492             // Prebuild plugin jtype to boost API response
493             plugins[idx]->jtype = json_object_new_string(plugins[idx]->prefix);
494             json_object_get(plugins[idx]->jtype); // increase reference count to make it permanent
495             plugins[idx]->prefixlen = strlen(plugins[idx]->prefix);
496             
497               
498             // Prebuild each API jtype to boost API json response
499             for (jdx = 0; plugins[idx]->apis[jdx].name != NULL; jdx++) {
500                 AFB_privateApi *private = malloc (sizeof (AFB_privateApi));
501                 if (plugins[idx]->apis[jdx].private != NULL) {
502                     fprintf (stderr, "WARNING: plugin=%s api=%s private handle should be NULL=0x%x\n"
503                             ,plugins[idx]->prefix,plugins[idx]->apis[jdx].name, plugins[idx]->apis[jdx].private);
504                 }
505                 private->len = strlen (plugins[idx]->apis[jdx].name);
506                 private->jtype=json_object_new_string(plugins[idx]->apis[jdx].name);
507                 json_object_get(private->jtype); // increase reference count to make it permanent
508                 plugins[idx]->apis[jdx].private = private;
509             }
510         }
511     }
512     return (plugins);
513 }
514
515 void initPlugins(AFB_session *session) {
516     static AFB_plugin * plugins[10];
517     afbJsonType = json_object_new_string (AFB_MSG_JTYPE);
518     int i = 0;
519
520     plugins[i++] = afsvRegister(session),
521     plugins[i++] = dbusRegister(session),
522     plugins[i++] = alsaRegister(session),
523 #ifdef HAVE_RADIO_PLUGIN
524     plugins[i++] = radioRegister(session),
525 #endif
526     plugins[i++] = NULL;
527     
528     // complete plugins and save them within current sessions    
529     session->plugins = RegisterJsonPlugins(plugins);
530 }