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
20 * https://www.gnu.org/software/libmicrohttpd/tutorial.html [search 'FILE *fp']
23 #include "../include/local-def.h"
28 #define AFB_MSG_JTYPE "AJB_reply"
31 // handle to hold queryAll values
38 static json_object *afbJsonType;
41 // Sample Generic Ping Debug API
42 PUBLIC json_object* apiPingTest(AFB_request *request) {
44 json_object *response;
49 AFB_clientCtx *client=request->client; // get client context from request
51 // request all query key/value
52 len = getQueryAll (request, query, sizeof(query));
53 if (len == 0) strncpy (query, "NoSearchQueryList", sizeof(query));
55 // check if we have some post data
56 if (request->post == NULL) request->post->data="NoData";
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);
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);
68 // Helper to retrieve argument from connection
69 PUBLIC const char* getQueryValue(AFB_request * request, char *name) {
72 value = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, name);
76 STATIC int getQueryCB (void*handle, enum MHD_ValueKind kind, const char *key, const char *value) {
77 queryHandleT *query = (queryHandleT*)handle;
79 query->idx += snprintf (&query->msg[query->idx],query->len," %s: \'%s\',", key, value);
82 // Helper to retrieve argument from connection
83 PUBLIC int getQueryAll(AFB_request * request, char *buffer, size_t len) {
85 buffer[0] = '\0'; // start with an empty string
90 MHD_get_connection_values (request->connection, MHD_GET_ARGUMENT_KIND, getQueryCB, &query);
94 // Because of POST call multiple time requestApi we need to free POST handle here
95 PUBLIC void endPostRequest(AFB_PostHandle *postHandle) {
97 if (postHandle->type == AFB_POST_JSON) {
98 if (verbose) fprintf(stderr, "End PostJson Request UID=%d\n", postHandle->uid);
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);
105 // call API termination callback
106 if (!postHandle->private) {
107 if (!postHandle->completeCB) postHandle->completeCB (postHandle->private);
110 free(postHandle->private);
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};
120 /*---------------------------------------------------------------
121 | Signal handler defined inside CallPluginApi to access Request
122 +---------------------------------------------------------------- */
123 void pluginError (int signum) {
125 AFB_clientCtx *context;
127 // unlock signal to allow a new signal to come
128 sigemptyset (&sigset);
129 sigaddset (&sigset, signum);
130 sigprocmask (SIG_UNBLOCK, &sigset, 0);
132 fprintf (stderr, "Oops:%s Plugin Api Timeout timeout\n", configTime());
133 longjmp (request->checkPluginCall, signum);
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)) {
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);
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));
151 // save context before calling the API
152 status = setjmp (request->checkPluginCall);
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);
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);
173 // Trigger a timer to protect from unacceptable long time execution
174 alarm (request->config->apiTimeout);
177 // Out of SessionNone every call get a client context session
178 if (AFB_SESSION_NONE != plugin->apis[idx].session) {
180 // add client context to request
181 ctxClientGet(request, plugin);
183 if (verbose) fprintf(stderr, "Plugin=[%s] Api=[%s] Middleware=[%d] Client=[0x%x] Uuid=[%s] Token=[%s]\n"
184 , request->plugin, request->api, plugin->apis[idx].session, request->client, request->client->uuid, request->client->token);
186 switch(plugin->apis[idx].session) {
188 case AFB_SESSION_CREATE:
189 if (request->client->token[0] != '\0') {
190 request->errcode=MHD_HTTP_UNAUTHORIZED;
191 json_object_object_add(jcall, "status", json_object_new_string ("exist"));
192 json_object_object_add(jcall, "info", json_object_new_string ("AFB_SESSION_CREATE Session already exist"));
193 json_object_object_add(request->jresp, "request", jcall);
197 if (AFB_SUCCESS != ctxTokenCreate (request)) {
198 request->errcode=MHD_HTTP_UNAUTHORIZED;
199 json_object_object_add(jcall, "status", json_object_new_string ("fail"));
200 json_object_object_add(jcall, "info", json_object_new_string ("AFB_SESSION_CREATE Invalid Initial Token"));
201 json_object_object_add(request->jresp, "request", jcall);
204 json_object_object_add(jcall, "uuid", json_object_new_string (request->client->uuid));
205 json_object_object_add(jcall, "token", json_object_new_string (request->client->token));
206 json_object_object_add(jcall, "timeout", json_object_new_int (request->config->cntxTimeout));
211 case AFB_SESSION_RENEW:
212 if (AFB_SUCCESS != ctxTokenRefresh (request)) {
213 request->errcode=MHD_HTTP_UNAUTHORIZED;
214 json_object_object_add(jcall, "status", json_object_new_string ("fail"));
215 json_object_object_add(jcall, "info", json_object_new_string ("AFB_SESSION_REFRESH Broken Exchange Token Chain"));
216 json_object_object_add(request->jresp, "request", jcall);
219 json_object_object_add(jcall, "uuid", json_object_new_string (request->client->uuid));
220 json_object_object_add(jcall, "token", json_object_new_string (request->client->token));
221 json_object_object_add(jcall, "timeout", json_object_new_int (request->config->cntxTimeout));
225 case AFB_SESSION_CLOSE:
226 if (AFB_SUCCESS != ctxTokenCheck (request)) {
227 request->errcode=MHD_HTTP_UNAUTHORIZED;
228 json_object_object_add(jcall, "status", json_object_new_string ("empty"));
229 json_object_object_add(jcall, "info", json_object_new_string ("AFB_SESSION_CLOSE Not a Valid Access Token"));
230 json_object_object_add(request->jresp, "request", jcall);
233 json_object_object_add(jcall, "uuid", json_object_new_string (request->client->uuid));
237 case AFB_SESSION_CHECK:
239 // default action is check
240 if (AFB_SUCCESS != ctxTokenCheck (request)) {
241 request->errcode=MHD_HTTP_UNAUTHORIZED;
242 json_object_object_add(jcall, "status", json_object_new_string ("fail"));
243 json_object_object_add(jcall, "info", json_object_new_string ("AFB_SESSION_CHECK Invalid Active Token"));
244 json_object_object_add(request->jresp, "request", jcall);
251 // Effectively call the API with a subset of the context
252 jresp = plugin->apis[idx].callback(request, context);
254 // Session close is done after the API call so API can still use session in closing API
255 if (AFB_SESSION_CLOSE == plugin->apis[idx].session) ctxTokenReset (request);
257 // API should return NULL of a valid Json Object
259 json_object_object_add(jcall, "status", json_object_new_string ("null"));
260 json_object_object_add(request->jresp, "request", jcall);
261 request->errcode = MHD_HTTP_NO_RESPONSE;
264 json_object_object_add(jcall, "status", json_object_new_string ("processed"));
265 json_object_object_add(request->jresp, "request", jcall);
266 json_object_object_add(request->jresp, "response", jresp);
268 // cancel timeout and plugin signal handle before next call
269 if (request->config->apiTimeout > 0) {
271 for (sig=0; signals[sig] != 0; sig++) {
272 signal (signals[sig], SIG_DFL);
283 STATIC AFB_error findAndCallApi (AFB_request *request, void *context) {
288 // Search for a plugin with this urlpath
289 for (idx = 0; request->plugins[idx] != NULL; idx++) {
290 if (!strcmp(request->plugins[idx]->prefix, request->plugin)) {
291 status =callPluginApi(request->plugins[idx], request, context);
295 // No plugin was found
296 if (request->plugins[idx] == NULL) {
297 request->jresp = jsonNewMessage(AFB_FATAL, "No Plugin=[%s]", request->plugin);
301 // plugin callback did not return a valid Json Object
302 if (status != AFB_DONE) {
303 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s]", request->api, request->plugin);
310 // Everything look OK
314 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
318 // This CB is call for every item with a form post it reformat iterator values
319 // and callback Plugin API for each Item within PostForm.
320 doPostIterate (void *cls, enum MHD_ValueKind kind, const char *key,
321 const char *filename, const char *mimetype,
322 const char *encoding, const char *data, uint64_t offset,
328 // retrieve API request from Post iterator handle
329 AFB_PostHandle *postHandle = (AFB_PostHandle*)cls;
330 AFB_request *request = (AFB_request*)postHandle->private;
331 AFB_PostRequest postRequest;
334 // Create and Item value for Plugin API
337 item.filename = filename;
338 item.mimetype = mimetype;
339 item.encoding = encoding;
342 item.offset = offset;
344 // Reformat Request to make it somehow similar to GET/PostJson case
345 postRequest.data= (char*) postHandle;
346 postRequest.len = size;
347 postRequest.type= AFB_POST_FORM;;
348 request->post = &postRequest;
350 // effectively call plugin API
351 status = findAndCallApi (request, &item);
353 // when returning no processing of postform stop
354 if (status != AFB_SUCCESS) return MHD_NO;
356 // let's allow iterator to move to next item
360 STATIC void freeRequest (AFB_request *request) {
362 free (request->plugin);
367 STATIC AFB_request *createRequest (struct MHD_Connection *connection, AFB_session *session, const char* url) {
369 AFB_request *request;
371 // Start with a clean request
372 request = calloc (1, sizeof (AFB_request));
373 char *urlcpy1, *urlcpy2;
374 char *baseapi, *baseurl;
376 // Extract plugin urlpath from request and make two copy because strsep overload copy
377 urlcpy1 = urlcpy2 = strdup(url);
378 baseurl = strsep(&urlcpy2, "/");
379 if (baseurl == NULL) {
380 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call url=[%s]", url);
383 // let's compute URL and call API
384 baseapi = strsep(&urlcpy2, "/");
385 if (baseapi == NULL) {
386 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call url=[%s]", url);
389 // build request structure
390 request->connection = connection;
391 request->config = session->config;
393 request->plugin = strdup (baseurl);
394 request->api = strdup (baseapi);
395 request->plugins= session->plugins;
401 // process rest API query
402 PUBLIC int doRestApi(struct MHD_Connection *connection, AFB_session *session, const char* url, const char *method
403 , const char *upload_data, size_t *upload_data_size, void **con_cls) {
405 static int postcount = 0; // static counter to debug POST protocol
406 json_object *errMessage;
408 struct MHD_Response *webResponse;
409 const char *serialized;
410 AFB_request *request;
411 AFB_PostHandle *postHandle;
412 AFB_PostRequest postRequest;
415 // if post data may come in multiple calls
416 if (0 == strcmp(method, MHD_HTTP_METHOD_POST)) {
417 const char *encoding, *param;
419 postHandle = *con_cls;
421 // This is the initial post event let's create form post structure POST datas come in multiple events
422 if (postHandle == NULL) {
424 // allocate application POST processor handle to zero
425 postHandle = calloc(1, sizeof (AFB_PostHandle));
426 postHandle->uid = postcount++; // build a UID for DEBUG
427 *con_cls = postHandle; // attache POST handle to current HTTP request
429 // Let make sure we have the right encoding and a valid length
430 encoding = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE);
432 // Form post is handle through a PostProcessor and call API once per form key
433 if (strcasestr(encoding, FORM_CONTENT) != NULL) {
434 if (verbose) fprintf(stderr, "Create PostForm[uid=%d]\n", postHandle->uid);
436 request = createRequest (connection, session, url);
437 if (request->jresp != NULL) {
438 errMessage = request->jresp;
441 postHandle = malloc(sizeof (AFB_PostHandle)); // allocate application POST processor handle
442 postHandle->type = AFB_POST_FORM;
443 postHandle->pp = MHD_create_post_processor (connection, MAX_POST_SIZE, doPostIterate, postHandle);
444 postHandle->private= (void*)request;
446 if (NULL == postHandle->pp) {
447 fprintf(stderr,"OOPS: Internal error fail to allocate MHD_create_post_processor\n");
454 // POST json is store into a buffer and present in one piece to API
455 if (strcasestr(encoding, JSON_CONTENT) != NULL) {
457 param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
458 if (param) sscanf(param, "%i", &contentlen);
460 // Because PostJson are build in RAM size is constrained
461 if (contentlen > MAX_POST_SIZE) {
462 errMessage = jsonNewMessage(AFB_FATAL, "Post Date to big %d > %d", contentlen, MAX_POST_SIZE);
466 // Size is OK, let's allocate a buffer to hold post data
467 postHandle->type = AFB_POST_JSON;
468 postHandle->private = malloc(contentlen + 1); // allocate memory for full POST data + 1 for '\0' enf of string
470 if (verbose) fprintf(stderr, "Create PostJson[uid=%d] Size=%d\n", postHandle->uid, contentlen);
474 // We only support Json and Form Post format
475 errMessage = jsonNewMessage(AFB_FATAL, "Post Date wrong type encoding=%s != %s", encoding, JSON_CONTENT);
481 // This time we receive partial/all Post data. Note that even if we get all POST data. We should nevertheless
482 // return MHD_YES and not process the request directly. Otherwise Libmicrohttpd is unhappy and fails with
483 // 'Internal application error, closing connection'.
484 if (*upload_data_size) {
486 if (postHandle->type == AFB_POST_FORM) {
487 if (verbose) fprintf(stderr, "Processing PostForm[uid=%d]\n", postHandle->uid);
488 MHD_post_process (postHandle->pp, upload_data, *upload_data_size);
491 // Process JsonPost request when buffer is completed let's call API
492 if (postHandle->type == AFB_POST_JSON) {
493 if (verbose) fprintf(stderr, "Updating PostJson[uid=%d]\n", postHandle->uid);
495 memcpy(&postHandle->private[postHandle->len], upload_data, *upload_data_size);
496 postHandle->len = postHandle->len + *upload_data_size;
497 *upload_data_size = 0;
501 } else { // we have finish with Post reception let's finish the work
503 // Create a request structure to finalise the request
504 request= createRequest (connection, session, url);
505 if (request->jresp != NULL) {
506 errMessage = request->jresp;
511 if (postHandle->type == AFB_POST_JSON) {
512 if (verbose) fprintf(stderr, "Processing PostJson[uid=%d]\n", postHandle->uid);
514 param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
515 if (param) sscanf(param, "%i", &contentlen);
517 // At this level we're may verify that we got everything and process DATA
518 if (postHandle->len != contentlen) {
519 errMessage = jsonNewMessage(AFB_FATAL, "Post Data Incomplete UID=%d Len %d != %d", postHandle->uid, contentlen, postHandle->len);
523 // Before processing data, make sure buffer string is properly ended
524 postHandle->private[postHandle->len] = '\0';
525 postRequest.data = postHandle->private;
526 postRequest.type = postHandle->type;
527 request->post = &postRequest;
529 if (verbose) fprintf(stderr, "Close Post[%d] Buffer=%s\n", postHandle->uid, request->post->data);
533 // this is a get we only need a request
534 request= createRequest (connection, session, url);
537 // Request is ready let's call API without any extra handle
538 status = findAndCallApi (request, NULL);
541 serialized = json_object_to_json_string(request->jresp);
542 webResponse = MHD_create_response_from_buffer(strlen(serialized), (void*) serialized, MHD_RESPMEM_MUST_COPY);
544 // client did not pass token on URI let's use cookies
545 if ((!request->restfull) && (request->client != NULL)) {
547 snprintf (cookie, sizeof (cookie), "%s=%s", COOKIE_NAME, request->client->uuid);
548 MHD_add_response_header (webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
551 // if requested add an error status
552 if (request->errcode != 0) ret=MHD_queue_response (connection, request->errcode, webResponse);
553 else MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
555 MHD_destroy_response(webResponse);
556 json_object_put(request->jresp); // decrease reference rqtcount to free the json object
557 freeRequest (request);
561 freeRequest (request);
562 serialized = json_object_to_json_string(errMessage);
563 webResponse = MHD_create_response_from_buffer(strlen(serialized), (void*) serialized, MHD_RESPMEM_MUST_COPY);
564 MHD_queue_response(connection, MHD_HTTP_BAD_REQUEST, webResponse);
565 MHD_destroy_response(webResponse);
566 json_object_put(errMessage); // decrease reference rqtcount to free the json object
571 // Loop on plugins. Check that they have the right type, prepare a JSON object with prefix
572 STATIC AFB_plugin ** RegisterJsonPlugins(AFB_plugin **plugins) {
575 for (idx = 0; plugins[idx] != NULL; idx++) {
576 if (plugins[idx]->type != AFB_PLUGIN_JSON) {
577 fprintf(stderr, "ERROR: AFSV plugin[%d] invalid type=%d != %d\n", idx, AFB_PLUGIN_JSON, plugins[idx]->type);
579 // some sanity controls
580 if ((plugins[idx]->prefix == NULL) || (plugins[idx]->info == NULL) || (plugins[idx]->apis == NULL)) {
581 if (plugins[idx]->prefix == NULL) plugins[idx]->prefix = "No URL prefix for APIs";
582 if (plugins[idx]->info == NULL) plugins[idx]->info = "No Info describing plugin APIs";
583 fprintf(stderr, "ERROR: plugin[%d] invalid prefix=%s info=%s", idx, plugins[idx]->prefix, plugins[idx]->info);
587 if (verbose) fprintf(stderr, "Loading plugin[%d] prefix=[%s] info=%s\n", idx, plugins[idx]->prefix, plugins[idx]->info);
589 // Prebuild plugin jtype to boost API response
590 plugins[idx]->jtype = json_object_new_string(plugins[idx]->prefix);
591 json_object_get(plugins[idx]->jtype); // increase reference count to make it permanent
592 plugins[idx]->prefixlen = strlen(plugins[idx]->prefix);
595 // Prebuild each API jtype to boost API json response
596 for (jdx = 0; plugins[idx]->apis[jdx].name != NULL; jdx++) {
597 AFB_privateApi *private = malloc (sizeof (AFB_privateApi));
598 if (plugins[idx]->apis[jdx].private != NULL) {
599 fprintf (stderr, "WARNING: plugin=%s api=%s private handle should be NULL=0x%x\n"
600 ,plugins[idx]->prefix,plugins[idx]->apis[jdx].name, plugins[idx]->apis[jdx].private);
602 private->len = strlen (plugins[idx]->apis[jdx].name);
603 private->jtype=json_object_new_string(plugins[idx]->apis[jdx].name);
604 json_object_get(private->jtype); // increase reference count to make it permanent
605 plugins[idx]->apis[jdx].private = private;
612 void initPlugins(AFB_session *session) {
613 static AFB_plugin * plugins[10];
614 afbJsonType = json_object_new_string (AFB_MSG_JTYPE);
617 plugins[i++] = tokenRegister(session),
618 plugins[i++] = helloWorldRegister(session),
619 #ifdef HAVE_AUDIO_PLUGIN
620 plugins[i++] = audioRegister(session),
622 #ifdef HAVE_RADIO_PLUGIN
623 plugins[i++] = radioRegister(session),
627 // complete plugins and save them within current sessions
628 session->plugins = RegisterJsonPlugins(plugins);