b3b1c2583aa95827a77b3235a47342373204b11b
[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
21 #include "../include/local-def.h"
22
23 #include <setjmp.h>
24 #include <signal.h>
25
26 #define AFB_MSG_JTYPE "AJB_reply"
27
28
29 // handle to hold queryAll values
30 typedef struct {
31      char    *msg;
32      int     idx;
33      size_t  len;
34 } queryHandleT;
35
36 static json_object *afbJsonType;
37
38 // Helper to retrieve argument from  connection
39 PUBLIC const char* getQueryValue(AFB_request * request, char *name) {
40     const char *value;
41
42     value = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, name);
43     return (value);
44 }
45
46 STATIC int getQueryCB (void*handle, enum MHD_ValueKind kind, const char *key, const char *value) {
47     queryHandleT *query = (queryHandleT*)handle;
48         
49     query->idx += snprintf (&query->msg[query->idx],query->len," %s: \'%s\',", key, value);
50 }
51
52 // Helper to retrieve argument from  connection
53 PUBLIC int getQueryAll(AFB_request * request, char *buffer, size_t len) {
54     queryHandleT query;
55     
56     query.msg= buffer;
57     query.len= len;
58     query.idx= 0;
59
60     MHD_get_connection_values (request->connection, MHD_GET_ARGUMENT_KIND, getQueryCB, &query);
61     return (len);
62 }
63
64
65 // Sample Generic Ping Debug API
66 PUBLIC json_object* apiPingTest(AFB_session *session, AFB_request *request, void* handle) {
67     static pingcount = 0;
68     json_object *response;
69     char query [512];
70     int len;
71
72     // request all query key/value
73     len = getQueryAll (request, query, sizeof(query));
74     if (len == 0) strcpy (query,"NoSearchQueryList");
75     
76     // check if we have some post data
77     if (request->post == NULL)  request->post="NoData";  
78         
79     // return response to caller
80     response = jsonNewMessage(AFB_SUCCESS, "Ping Binder Daemon %d query={%s} PostData: \'%s\' ", pingcount++, query, request->post);
81     return (response);
82 }
83
84
85 // Because of POST call multiple time requestApi we need to free POST handle here
86
87 STATIC void endRequest(void *cls, struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode toe) {
88     AFB_HttpPost *posthandle = *con_cls;
89
90     // if post handle was used let's free everything
91     if (posthandle) {
92         if (verbose) fprintf(stderr, "End Post Request UID=%d\n", posthandle->uid);
93         free(posthandle->data);
94         free(posthandle);
95     }
96 }
97
98 // Check of apiurl is declare in this plugin and call it
99 STATIC AFB_error callPluginApi(AFB_plugin *plugin, AFB_session *session, AFB_request *request) {
100     json_object *jresp, *jcall;
101     int idx, status, sig;
102     int signals[]= {SIGALRM, SIGSEGV, SIGFPE, 0};
103     
104     /*---------------------------------------------------------------
105     | Signal handler defined inside CallPluginApi to access Request
106     +---------------------------------------------------------------- */
107     void pluginError (int signum) {
108       sigset_t sigset;
109
110       // unlock signal to allow a new signal to come
111       sigemptyset (&sigset);
112       sigaddset   (&sigset, signum);
113       sigprocmask (SIG_UNBLOCK, &sigset, 0);
114
115       fprintf (stderr, "Oops:%s Plugin Api Timeout timeout\n", configTime());
116       longjmp (request->checkPluginCall, signum);
117     }
118
119     
120     // If a plugin hold this urlpath call its callback
121     for (idx = 0; plugin->apis[idx].callback != NULL; idx++) {
122         if (!strcmp(plugin->apis[idx].name, request->api)) {
123             
124             // prepare an object to store calling values
125             jcall=json_object_new_object();
126             json_object_object_add(jcall, "prefix", json_object_new_string (plugin->prefix));
127             json_object_object_add(jcall, "api"   , json_object_new_string (plugin->apis[idx].name));
128             
129             // save context before calling the API
130             status = setjmp (request->checkPluginCall);
131             if (status != 0) {    
132                 
133                 // Plugin aborted somewhere during its execution
134                 json_object_object_add(jcall, "status", json_object_new_string ("abort"));
135                 json_object_object_add(jcall, "info" ,  json_object_new_string ("Plugin broke during execution"));
136                 json_object_object_add(request->jresp, "request", jcall);
137                 
138             } else {
139                 
140                 // If timeout protection==0 we are in debug and we do not apply signal protection
141                 if (session->config->apiTimeout > 0) {
142                     for (sig=0; signals[sig] != 0; sig++) {
143                        if (signal (signals[sig], pluginError) == SIG_ERR) {
144                           fprintf (stderr, "%s ERR: main no Signal/timeout handler installed.", configTime());
145                           return AFB_FAIL;
146                        }
147                     }
148                     // Trigger a timer to protect from inacceptable long time execution
149                     alarm (session->config->apiTimeout);
150                 }
151
152                 // Effectively call the API
153                 jresp = plugin->apis[idx].callback(session, request, plugin->apis[idx].handle);
154
155                 // API should return NULL of a valid Json Object
156                 if (jresp == NULL) {
157                     json_object_object_add(jcall, "status", json_object_new_string ("fail"));
158                     json_object_object_add(request->jresp, "request", jcall);
159                     
160                 } else {
161                     json_object_object_add(jcall, "status", json_object_new_string ("success"));
162                     json_object_object_add(request->jresp, "request", jcall);
163                     json_object_object_add(request->jresp, "response", jresp);
164
165                 }
166                 // cancel timeout and plugin signal handle before next call
167                 if (session->config->apiTimeout > 0) {
168                     alarm (0);
169                     for (sig=0; signals[sig] != 0; sig++) {
170                        signal (signals[sig], SIG_DFL);
171                     }
172                 }              
173             }    
174         
175             return (AFB_DONE);
176         }
177     }
178     return (AFB_FAIL);
179 }
180
181
182 // process rest API query
183
184 PUBLIC int doRestApi(struct MHD_Connection *connection, AFB_session *session, const char* url, const char *method
185     , const char *upload_data, size_t *upload_data_size, void **con_cls) {
186     
187     static int postcount = 0; // static counter to debug POST protocol
188     char *baseurl, *baseapi, *urlcpy1, *urlcpy2, *query;
189     json_object *errMessage;
190     AFB_error status;
191     struct MHD_Response *webResponse;
192     const char *serialized, parsedurl;
193     AFB_request request;
194     AFB_HttpPost *posthandle = *con_cls;
195     int idx, ret;
196
197     // Extract plugin urlpath from request and make two copy because strsep overload copy
198     urlcpy1 = urlcpy2 = strdup(url);
199     baseurl = strsep(&urlcpy2, "/");
200     if (baseurl == NULL) {
201         errMessage = jsonNewMessage(AFB_FATAL, "Invalid Plugin/API call url=%s", url);
202         goto ExitOnError;
203     }
204
205     baseapi = strsep(&urlcpy2, "/");
206     if (baseapi == NULL) {
207         errMessage = jsonNewMessage(AFB_FATAL, "Invalid Plugin/API call url=%s", url);
208         goto ExitOnError;
209     }
210     
211
212     // if post data may come in multiple calls
213     if (0 == strcmp(method, MHD_HTTP_METHOD_POST)) {
214         const char *encoding, *param;
215         int contentlen = -1;
216         AFB_HttpPost *posthandle = *con_cls;
217
218         // Let make sure we have the right encoding and a valid length
219         encoding = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE);
220         param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
221         if (param) sscanf(param, "%i", &contentlen);
222
223         // POST datas may come in multiple chunk. Even when it never happen on AFB, we still have to handle the case
224         if (strcasestr(encoding, JSON_CONTENT) == 0) {
225             errMessage = jsonNewMessage(AFB_FATAL, "Post Date wrong type encoding=%s != %s", encoding, JSON_CONTENT);
226             goto ExitOnError;
227         }
228
229         if (contentlen > MAX_POST_SIZE) {
230             errMessage = jsonNewMessage(AFB_FATAL, "Post Date to big %d > %d", contentlen, MAX_POST_SIZE);
231             goto ExitOnError;
232         }
233
234         // In POST mode first libmicrohttp call only establishes POST handling.
235         if (posthandle == NULL) {
236             posthandle = malloc(sizeof (AFB_HttpPost)); // allocate application POST processor handle
237             posthandle->uid = postcount++; // build a UID for DEBUG
238             posthandle->len = 0; // effective length within POST handler
239             posthandle->data = malloc(contentlen + 1); // allocate memory for full POST data + 1 for '\0' enf of string
240             *con_cls = posthandle; // attache POST handle to current HTTP session
241
242             if (verbose) fprintf(stderr, "Create Post[%d] Size=%d\n", posthandle->uid, contentlen);
243             return MHD_YES;
244         }
245
246         // This time we receive partial/all Post data. Note that even if we get all POST data. We should nevertheless
247         // return MHD_YES and not process the request directly. Otherwise Libmicrohttpd is unhappy and fails with
248         // 'Internal application error, closing connection'.
249         if (*upload_data_size) {
250             if (verbose) fprintf(stderr, "Update Post[%d]\n", posthandle->uid);
251
252             memcpy(&posthandle->data[posthandle->len], upload_data, *upload_data_size);
253             posthandle->len = posthandle->len + *upload_data_size;
254             *upload_data_size = 0;
255             return MHD_YES;
256         }
257
258         // We should only start to process DATA after Libmicrohttpd call or application handler with *upload_data_size==0
259         // At this level we're may verify that we got everything and process DATA
260         if (posthandle->len != contentlen) {
261             errMessage = jsonNewMessage(AFB_FATAL, "Post Data Incomplete UID=%d Len %d != %s", posthandle->uid, contentlen, posthandle->len);
262             goto ExitOnError;
263         }
264
265         // Before processing data, make sure buffer string is properly ended
266         posthandle->data[posthandle->len] = '\0';
267         request.post = posthandle->data;
268
269         if (verbose) fprintf(stderr, "Close Post[%d] Buffer=%s\n", posthandle->uid, request.post);
270
271     } else {
272         request.post = NULL;
273     };
274
275    
276     // build request structure
277     memset(&request, 0, sizeof (request));
278     request.connection = connection;
279     request.url = url;
280     request.plugin = baseurl;
281     request.api = baseapi;
282     request.jresp = json_object_new_object();
283     
284     // increase reference count and add jtype to response    
285     json_object_get (afbJsonType);
286     json_object_object_add (request.jresp, "jtype", afbJsonType);
287     
288     // Search for a plugin with this urlpath
289     for (idx = 0; session->plugins[idx] != NULL; idx++) {
290         if (!strcmp(session->plugins[idx]->prefix, baseurl)) {
291             status =callPluginApi(session->plugins[idx], session, &request);
292             free(urlcpy1);
293             break;
294         }
295     }
296     // No plugin was found
297     if (session->plugins[idx] == NULL) {
298         errMessage = jsonNewMessage(AFB_FATAL, "No Plugin for %s", baseurl);
299         free(urlcpy1);
300         goto ExitOnError;
301     }
302
303     // plugin callback did not return a valid Json Object
304     if (status != AFB_DONE) {
305         errMessage = jsonNewMessage(AFB_FATAL, "No Plugin/API for %s/%s", baseurl, baseapi);
306         goto ExitOnError;
307     }
308
309     serialized = json_object_to_json_string(request.jresp);
310     webResponse = MHD_create_response_from_buffer(strlen(serialized), (void*) serialized, MHD_RESPMEM_MUST_COPY);
311
312     ret = MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
313     MHD_destroy_response(webResponse);
314     json_object_put(request.jresp); // decrease reference rqtcount to free the json object
315     return ret;
316
317 ExitOnError:
318     serialized = json_object_to_json_string(errMessage);
319     webResponse = MHD_create_response_from_buffer(strlen(serialized), (void*) serialized, MHD_RESPMEM_MUST_COPY);
320     ret = MHD_queue_response(connection, MHD_HTTP_BAD_REQUEST, webResponse);
321     MHD_destroy_response(webResponse);
322     json_object_put(errMessage); // decrease reference rqtcount to free the json object
323     return ret;
324 }
325
326
327 // Loop on plugins. Check that they have the right type, prepare a JSON object with prefix
328 STATIC AFB_plugin ** RegisterPlugins(AFB_plugin **plugins) {
329     int idx, jdx;
330
331     for (idx = 0; plugins[idx] != NULL; idx++) {
332         if (plugins[idx]->type != AFB_PLUGIN) {
333             fprintf(stderr, "ERROR: AFSV plugin[%d] invalid type=%d != %d\n", idx, AFB_PLUGIN, plugins[idx]->type);
334         } else {
335             // some sanity controls
336             if ((plugins[idx]->prefix == NULL) || (plugins[idx]->info == NULL) || (plugins[idx]->apis == NULL)) {
337                 if (plugins[idx]->prefix == NULL) plugins[idx]->prefix = "No URL prefix for APIs";
338                 if (plugins[idx]->info == NULL) plugins[idx]->info = "No Info describing plugin APIs";
339                 fprintf(stderr, "ERROR: plugin[%d] invalid prefix=%s info=%s", idx, plugins[idx]->prefix, plugins[idx]->info);
340                 return NULL;
341             }
342
343             if (verbose) fprintf(stderr, "Loading plugin[%d] prefix=[%s] info=%s\n", idx, plugins[idx]->prefix, plugins[idx]->info);
344
345             // Prebuild plugin jtype to boost API response
346             plugins[idx]->jtype = json_object_new_string(plugins[idx]->prefix);
347             json_object_get(plugins[idx]->jtype); // increase reference count to make it permanent
348             plugins[idx]->prefixlen = strlen(plugins[idx]->prefix);
349             
350               
351             // Prebuild each API jtype to boost API json response
352             for (jdx = 0; plugins[idx]->apis[jdx].name != NULL; jdx++) {
353                 AFB_privateApi *private = malloc (sizeof (AFB_privateApi));
354                 if (plugins[idx]->apis[jdx].private != NULL) {
355                     fprintf (stderr, "WARNING: plugin=%s api=%s private handle should be NULL\n"
356                             ,plugins[idx]->prefix,plugins[idx]->apis[jdx].name);
357                 }
358                 private->len = strlen (plugins[idx]->apis[jdx].name);
359                 private->jtype=json_object_new_string(plugins[idx]->apis[jdx].name);
360                 json_object_get(private->jtype); // increase reference count to make it permanent
361                 plugins[idx]->apis[jdx].private = private;
362             }
363         }
364     }
365     return (plugins);
366 }
367
368 void initPlugins(AFB_session *session) {
369     static AFB_plugin * plugins[10];
370     afbJsonType = json_object_new_string (AFB_MSG_JTYPE);
371     
372     plugins[0] = afsvRegister(session),
373             plugins[1] = dbusRegister(session),
374             plugins[2] = alsaRegister(session),
375             plugins[3] = NULL;
376
377     // complete plugins and save them within current sessions    
378     session->plugins = RegisterPlugins(plugins);
379 }