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