2 * Copyright (C) 2015 "IoT.bzh"
3 * Author "Fulup Ar Foll"
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.
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.
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/>.
18 * Contain all generic part to handle REST/API
21 #include "../include/local-def.h"
26 #define AFB_MSG_JTYPE "AJB_reply"
29 // handle to hold queryAll values
36 static json_object *afbJsonType;
38 // Helper to retrieve argument from connection
39 PUBLIC const char* getQueryValue(AFB_request * request, char *name) {
42 value = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, name);
46 STATIC int getQueryCB (void*handle, enum MHD_ValueKind kind, const char *key, const char *value) {
47 queryHandleT *query = (queryHandleT*)handle;
49 query->idx += snprintf (&query->msg[query->idx],query->len," %s: \'%s\',", key, value);
52 // Helper to retrieve argument from connection
53 PUBLIC int getQueryAll(AFB_request * request, char *buffer, size_t len) {
60 MHD_get_connection_values (request->connection, MHD_GET_ARGUMENT_KIND, getQueryCB, &query);
65 // Sample Generic Ping Debug API
66 PUBLIC json_object* apiPingTest(AFB_session *session, AFB_request *request, void* handle) {
68 json_object *response;
72 // request all query key/value
73 len = getQueryAll (request, query, sizeof(query));
74 if (len == 0) strcpy (&query,"NoSearchQueryList");
76 // check if we have some post data
77 if (request->post == NULL) request->post="NoData";
79 // return response to caller
80 response = jsonNewMessage(AFB_SUCCESS, "Ping Binder Daemon %d query={%s} PostData: \'%s\' ", pingcount++, query, request->post);
85 // Because of POST call multiple time requestApi we need to free POST handle here
87 STATIC void endRequest(void *cls, struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode toe) {
88 AFB_HttpPost *posthandle = *con_cls;
90 // if post handle was used let's free everything
92 if (verbose) fprintf(stderr, "End Post Request UID=%d\n", posthandle->uid);
93 free(posthandle->data);
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};
104 /*---------------------------------------------------------------
105 | Signal handler defined inside CallPluginApi to access Request
106 +---------------------------------------------------------------- */
107 void pluginError (int signum) {
110 // unlock signal to allow a new signal to come
111 sigemptyset (&sigset);
112 sigaddset (&sigset, signum);
113 sigprocmask (SIG_UNBLOCK, &sigset, 0);
115 fprintf (stderr, "Oops:%s Plugin Api Timeout timeout\n", configTime());
116 longjmp (request->checkPluginCall, signum);
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)) {
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));
129 // save context before calling the API
130 status = setjmp (request->checkPluginCall);
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);
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());
148 // Trigger a timer to protect from inacceptable long time execution
149 alarm (session->config->apiTimeout);
152 // Effectively call the API
153 jresp = plugin->apis[idx].callback(session, request, plugin->apis[idx].handle);
155 // API should return NULL of a valid Json Object
157 json_object_object_add(jcall, "status", json_object_new_string ("fail"));
158 json_object_object_add(request->jresp, "request", jcall);
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);
166 // cancel timeout and plugin signal handle before next call
167 if (session->config->apiTimeout > 0) {
169 for (sig=0; signals[sig] != 0; sig++) {
170 signal (signals[sig], SIG_DFL);
182 // process rest API query
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) {
187 static int postcount = 0; // static counter to debug POST protocol
188 char *baseurl, *baseapi, *urlcpy1, *urlcpy2, *query;
189 json_object *errMessage;
191 struct MHD_Response *webResponse;
192 const char *serialized, parsedurl;
194 AFB_HttpPost *posthandle = *con_cls;
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);
205 baseapi = strsep(&urlcpy2, "/");
206 if (baseapi == NULL) {
207 errMessage = jsonNewMessage(AFB_FATAL, "Invalid Plugin/API call url=%s", url);
212 // if post data may come in multiple calls
213 if (0 == strcmp(method, MHD_HTTP_METHOD_POST)) {
214 const char *encoding, *param;
216 AFB_HttpPost *posthandle = *con_cls;
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);
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);
229 if (contentlen > MAX_POST_SIZE) {
230 errMessage = jsonNewMessage(AFB_FATAL, "Post Date to big %d > %d", contentlen, MAX_POST_SIZE);
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
242 if (verbose) fprintf(stderr, "Create Post[%d] Size=%d\n", posthandle->uid, contentlen);
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);
252 memcpy(&posthandle->data[posthandle->len], upload_data, *upload_data_size);
253 posthandle->len = posthandle->len + *upload_data_size;
254 *upload_data_size = 0;
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);
265 // Before processing data, make sure buffer string is properly ended
266 posthandle->data[posthandle->len] = '\0';
267 request.post = posthandle->data;
269 if (verbose) fprintf(stderr, "Close Post[%d] Buffer=%s\n", posthandle->uid, request.post);
276 // build request structure
277 memset(&request, 0, sizeof (request));
278 request.connection = connection;
280 request.plugin = baseurl;
281 request.api = baseapi;
282 request.jresp = json_object_new_object();
284 // increase reference count and add jtype to response
285 json_object_get (afbJsonType);
286 json_object_object_add (request.jresp, "jtype", afbJsonType);
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);
296 // No plugin was found
297 if (session->plugins[idx] == NULL) {
298 errMessage = jsonNewMessage(AFB_FATAL, "No Plugin for %s", baseurl);
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);
309 serialized = json_object_to_json_string(request.jresp);
310 webResponse = MHD_create_response_from_buffer(strlen(serialized), (void*) serialized, MHD_RESPMEM_MUST_COPY);
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
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
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) {
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);
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);
343 if (verbose) fprintf(stderr, "Loading plugin[%d] prefix=[%s] info=%s\n", idx, plugins[idx]->prefix, plugins[idx]->info);
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);
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);
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;
368 void initPlugins(AFB_session *session) {
369 static AFB_plugin * plugins[10];
370 afbJsonType = json_object_new_string (AFB_MSG_JTYPE);
372 plugins[0] = afsvRegister(session),
373 plugins[1] = dbusRegister(session),
374 plugins[2] = alsaRegister(session),
377 // complete plugins and save them within current sessions
378 session->plugins = RegisterPlugins(plugins);