refactoring
[src/app-framework-binder.git] / src / afb-rest-api.c
1 /*
2  * Copyright (C) 2016 "IoT.bzh"
3  * Author "Fulup Ar Foll"
4  * Author José Bollo <jose.bollo@iot.bzh>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  * 
19  * Contain all generic part to handle REST/API
20  * 
21  *  https://www.gnu.org/software/libmicrohttpd/tutorial.html [search 'largepost.c']
22  */
23
24 #define _GNU_SOURCE
25
26 #include "../include/local-def.h"
27
28 #include <dirent.h>
29 #include <dlfcn.h>
30 #include <setjmp.h>
31 #include <signal.h>
32
33 #include "afb-apis.h"
34
35 #define AFB_MSG_JTYPE "AJB_reply"
36
37 #define JSON_CONTENT  "application/json"
38 #define FORM_CONTENT  "multipart/form-data"     /* TODO: replace with MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA */
39
40 static json_object *afbJsonType;
41
42 // Because of POST call multiple time requestApi we need to free POST handle here
43 // Note this method is called from http-svc just before closing session
44 PUBLIC void endPostRequest(AFB_PostHandle * postHandle)
45 {
46
47         if (postHandle->type == AFB_POST_JSON) {
48                 // if (verbose) fprintf(stderr, "End PostJson Request UID=%d\n", postHandle->uid);
49         }
50
51         if (postHandle->type == AFB_POST_FORM) {
52                 if (verbose)
53                         fprintf(stderr, "End PostForm Request UID=%d\n", postHandle->uid);
54         }
55         if (postHandle->privatebuf)
56                 free(postHandle->privatebuf);
57         free(postHandle);
58 }
59
60 // Check of apiurl is declare in this plugin and call it
61 static AFB_error doCallPluginApi(AFB_request * request, int apiidx, int verbidx, void *context)
62 {
63         enum AFB_sessionE session;
64         json_object *jresp, *jcall, *jreqt;
65         AFB_clientCtx *clientCtx = NULL;
66
67         // Request was found and at least partially executed
68         jreqt = json_object_new_object();
69         json_object_get(afbJsonType);   // increate jsontype reference count
70         json_object_object_add(jreqt, "jtype", afbJsonType);
71
72         // prepare an object to store calling values
73         jcall = json_object_new_object();
74         json_object_object_add(jcall, "prefix", json_object_new_string(request->prefix));
75         json_object_object_add(jcall, "api", json_object_new_string(request->api));
76
77         // Out of SessionNone every call get a client context session
78         session = afb_apis_get(apiidx, verbidx)->session;
79         if (AFB_SESSION_NONE != session) {
80
81                 // add client context to request
82                 clientCtx = ctxClientGet(request, apiidx);
83                 if (clientCtx == NULL) {
84                         request->errcode = MHD_HTTP_INSUFFICIENT_STORAGE;
85                         json_object_object_add(jcall, "status", json_object_new_string("fail"));
86                         json_object_object_add(jcall, "info", json_object_new_string("Client Session Context Full !!!"));
87                         json_object_object_add(jreqt, "request", jcall);
88                         goto ExitOnDone;
89                 };
90
91                 if (verbose)
92                         fprintf(stderr, "Plugin=[%s] Api=[%s] Middleware=[%d] Client=[%p] Uuid=[%s] Token=[%s]\n", request->prefix, request->api, session, clientCtx, clientCtx->uuid, clientCtx->token);
93
94                 switch (session) {
95
96                 case AFB_SESSION_CREATE:
97                         if (clientCtx->token[0] != '\0' && request->config->token[0] != '\0') {
98                                 request->errcode = MHD_HTTP_UNAUTHORIZED;
99                                 json_object_object_add(jcall, "status", json_object_new_string("exist"));
100                                 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CREATE Session already exist"));
101                                 json_object_object_add(jreqt, "request", jcall);
102                                 goto ExitOnDone;
103                         }
104
105                         if (AFB_SUCCESS != ctxTokenCreate(clientCtx, request)) {
106                                 request->errcode = MHD_HTTP_UNAUTHORIZED;
107                                 json_object_object_add(jcall, "status", json_object_new_string("fail"));
108                                 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CREATE Invalid Initial Token"));
109                                 json_object_object_add(jreqt, "request", jcall);
110                                 goto ExitOnDone;
111                         } else {
112                                 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
113                                 json_object_object_add(jcall, "token", json_object_new_string(clientCtx->token));
114                                 json_object_object_add(jcall, "timeout", json_object_new_int(request->config->cntxTimeout));
115                         }
116                         break;
117
118                 case AFB_SESSION_RENEW:
119                         if (AFB_SUCCESS != ctxTokenRefresh(clientCtx, request)) {
120                                 request->errcode = MHD_HTTP_UNAUTHORIZED;
121                                 json_object_object_add(jcall, "status", json_object_new_string("fail"));
122                                 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_REFRESH Broken Exchange Token Chain"));
123                                 json_object_object_add(jreqt, "request", jcall);
124                                 goto ExitOnDone;
125                         } else {
126                                 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
127                                 json_object_object_add(jcall, "token", json_object_new_string(clientCtx->token));
128                                 json_object_object_add(jcall, "timeout", json_object_new_int(request->config->cntxTimeout));
129                         }
130                         break;
131
132                 case AFB_SESSION_CLOSE:
133                         if (AFB_SUCCESS != ctxTokenCheck(clientCtx, request)) {
134                                 request->errcode = MHD_HTTP_UNAUTHORIZED;
135                                 json_object_object_add(jcall, "status", json_object_new_string("empty"));
136                                 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CLOSE Not a Valid Access Token"));
137                                 json_object_object_add(jreqt, "request", jcall);
138                                 goto ExitOnDone;
139                         } else {
140                                 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
141                         }
142                         break;
143
144                 case AFB_SESSION_CHECK:
145                 default:
146                         // default action is check
147                         if (AFB_SUCCESS != ctxTokenCheck(clientCtx, request)) {
148                                 request->errcode = MHD_HTTP_UNAUTHORIZED;
149                                 json_object_object_add(jcall, "status", json_object_new_string("fail"));
150                                 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CHECK Invalid Active Token"));
151                                 json_object_object_add(jreqt, "request", jcall);
152                                 goto ExitOnDone;
153                         }
154                         break;
155                 }
156         }
157         // Effectively CALL PLUGIN API with a subset of the context
158         jresp = afb_apis_get(apiidx, verbidx)->callback(request, context);
159
160         // Store context in case it was updated by plugins
161         if (request->context != NULL)
162                 clientCtx->contexts[apiidx] = request->context;
163
164         // handle intermediary Post Iterates out of band
165         if ((jresp == NULL) && (request->errcode == MHD_HTTP_OK))
166                 return AFB_SUCCESS;
167
168         // Session close is done after the API call so API can still use session in closing API
169         if (AFB_SESSION_CLOSE == session)
170                 ctxTokenReset(clientCtx, request);
171
172         // API should return NULL of a valid Json Object
173         if (jresp == NULL) {
174                 json_object_object_add(jcall, "status", json_object_new_string("null"));
175                 json_object_object_add(jreqt, "request", jcall);
176                 request->errcode = MHD_HTTP_NO_RESPONSE;
177
178         } else {
179                 json_object_object_add(jcall, "status", json_object_new_string("processed"));
180                 json_object_object_add(jreqt, "request", jcall);
181                 json_object_object_add(jreqt, "response", jresp);
182         }
183
184 ExitOnDone:
185         request->jresp = jreqt;
186         return AFB_DONE;
187 }
188
189 // Check of apiurl is declare in this plugin and call it
190 extern __thread sigjmp_buf *error_handler;
191 static AFB_error callPluginApi(AFB_request * request, int apiidx, int verbidx, void *context)
192 {
193         sigjmp_buf jmpbuf;
194
195         json_object *jcall, *jreqt;
196         int status;
197
198         // save context before calling the API
199         status = setjmp(jmpbuf);
200         if (status != 0) {
201
202                 // Request was found and at least partially executed
203                 jreqt = json_object_new_object();
204                 json_object_get(afbJsonType);   // increate jsontype reference count
205                 json_object_object_add(jreqt, "jtype", afbJsonType);
206
207                 // prepare an object to store calling values
208                 jcall = json_object_new_object();
209                 json_object_object_add(jcall, "prefix", json_object_new_string(request->prefix));
210                 json_object_object_add(jcall, "api", json_object_new_string(request->api));
211
212                 // Plugin aborted somewhere during its execution
213                 json_object_object_add(jcall, "status", json_object_new_string("abort"));
214                 json_object_object_add(jcall, "info", json_object_new_string("Plugin broke during execution"));
215                 json_object_object_add(jreqt, "request", jcall);
216                 request->jresp = jreqt;
217                 goto ExitOnDone;
218
219         } else {
220
221                 // Trigger a timer to protect from unacceptable long time execution
222                 if (request->config->apiTimeout > 0)
223                         alarm((unsigned)request->config->apiTimeout);
224
225                 error_handler = &jmpbuf;
226                 doCallPluginApi(request, apiidx, verbidx, context);
227                 error_handler = NULL;
228
229                 // cancel timeout and plugin signal handle before next call
230                 alarm(0);
231         }
232
233 ExitOnDone:
234         return AFB_DONE;
235 }
236
237 STATIC AFB_error findAndCallApi(AFB_request * request, void *context)
238 {
239         int apiidx, verbidx;
240         AFB_error status;
241
242         if (!request->api || !request->prefix)
243                 return AFB_FAIL;
244
245         /* get the plugin if any */
246         apiidx = afb_apis_get_apiidx(request->prefix, 0);
247         if (apiidx < 0) {
248                 request->jresp = jsonNewMessage(AFB_FATAL, "No Plugin=[%s] Url=%s", request->prefix, request->url);
249                 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
250                 return AFB_FAIL;
251         }
252
253         /* get the verb if any */
254         verbidx = afb_apis_get_verbidx(apiidx, request->api);
255         if (verbidx < 0) {
256                 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->api, request->prefix, request->url);
257                 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
258                 return AFB_FAIL;
259         }
260
261         /* Search for a plugin with this urlpath */
262         status = callPluginApi(request, apiidx, verbidx, context);
263
264         /* plugin callback did not return a valid Json Object */
265         if (status == AFB_FAIL) {
266                 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->api, request->prefix, request->url);
267                 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
268                 return AFB_FAIL;
269         }
270         // Everything look OK
271         return status;
272 }
273
274 // This CB is call for every item with a form post it reformat iterator values
275 // and callback Plugin API for each Item within PostForm.
276 STATIC int doPostIterate(void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *mimetype, const char *encoding, const char *data, uint64_t offset, size_t size)
277 {
278
279         AFB_error status;
280         AFB_PostItem item;
281
282         // retrieve API request from Post iterator handle  
283         AFB_PostHandle *postHandle = (AFB_PostHandle *) cls;
284         AFB_request *request = (AFB_request *) postHandle->privatebuf;
285         AFB_PostRequest postRequest;
286
287         if (verbose)
288                 fprintf(stderr, "postHandle key=%s filename=%s len=%zu mime=%s\n", key, filename, size, mimetype);
289
290         // Create and Item value for Plugin API
291         item.kind = kind;
292         item.key = key;
293         item.filename = filename;
294         item.mimetype = mimetype;
295         item.encoding = encoding;
296         item.len = size;
297         item.data = data;
298         item.offset = offset;
299
300         // Reformat Request to make it somehow similar to GET/PostJson case
301         postRequest.data = (char *)postHandle;
302         postRequest.len = size;
303         postRequest.type = AFB_POST_FORM;;
304         request->post = &postRequest;
305
306         // effectively call plugin API                 
307         status = findAndCallApi(request, &item);
308         // when returning no processing of postform stop
309         if (status != AFB_SUCCESS)
310                 return MHD_NO;
311
312         // let's allow iterator to move to next item
313         return MHD_YES;
314 }
315
316 STATIC void freeRequest(AFB_request * request)
317 {
318
319         free(request->prefix);
320         free(request->api);
321         free(request);
322 }
323
324 STATIC AFB_request *createRequest(struct MHD_Connection *connection, AFB_session * session, const char *url)
325 {
326
327         AFB_request *request;
328
329         // Start with a clean request
330         request = calloc(1, sizeof(AFB_request));
331         char *urlcpy1, *urlcpy2;
332         char *baseapi, *baseurl;
333
334         // Extract plugin urlpath from request and make two copy because strsep overload copy
335         urlcpy1 = urlcpy2 = strdup(url);
336         baseurl = strsep(&urlcpy2, "/");
337         if (baseurl == NULL) {
338                 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call url=[%s]", url);
339                 request->errcode = MHD_HTTP_BAD_REQUEST;
340                 goto Done;
341         }
342         // let's compute URL and call API
343         baseapi = strsep(&urlcpy2, "/");
344         if (baseapi == NULL) {
345                 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call plugin=[%s] url=[%s]", baseurl, url);
346                 request->errcode = MHD_HTTP_BAD_REQUEST;
347                 goto Done;
348         }
349         // build request structure
350         request->connection = connection;
351         request->config = session->config;
352         request->url = url;
353         request->prefix = strdup(baseurl);
354         request->api = strdup(baseapi);
355
356  Done:
357         free(urlcpy1);
358         return (request);
359 }
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375 static int doRestApiPost(struct MHD_Connection *connection, AFB_session * session, const char *url, const char *method, const char *upload_data, size_t * upload_data_size, void **con_cls)
376 {
377
378         static int postcount = 0;       // static counter to debug POST protocol
379         json_object *errMessage;
380         AFB_error status;
381         struct MHD_Response *webResponse;
382         const char *serialized;
383         AFB_request *request = NULL;
384         AFB_PostHandle *postHandle;
385         AFB_PostRequest postRequest;
386         int ret;
387
388         // fprintf (stderr, "doRestAPI method=%s posthandle=%p\n", method, con_cls);
389
390         // if post data may come in multiple calls
391         const char *encoding, *param;
392         int contentlen = -1;
393         postHandle = *con_cls;
394
395         // This is the initial post event let's create form post structure POST data come in multiple events
396         if (postHandle == NULL) {
397
398                 // allocate application POST processor handle to zero
399                 postHandle = calloc(1, sizeof(AFB_PostHandle));
400                 postHandle->uid = postcount++;  // build a UID for DEBUG
401                 *con_cls = postHandle;  // update context with posthandle
402
403                 // Let make sure we have the right encoding and a valid length
404                 encoding = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE);
405
406                 // We are facing an empty post let's process it as a get
407                 if (encoding == NULL) {
408                         postHandle->type = AFB_POST_EMPTY;
409                         return MHD_YES;
410                 }
411                 // Form post is handle through a PostProcessor and call API once per form key
412                 if (strcasestr(encoding, FORM_CONTENT) != NULL) {
413                         if (verbose)
414                                 fprintf(stderr, "Create doPostIterate[uid=%d posthandle=%p]\n", postHandle->uid, postHandle);
415
416                         request = createRequest(connection, session, url);
417                         if (request->jresp != NULL)
418                                 goto ProcessApiCall;
419                         postHandle->type = AFB_POST_FORM;
420                         postHandle->privatebuf = (void *)request;
421                         postHandle->pp = MHD_create_post_processor(connection, MAX_POST_SIZE, &doPostIterate, postHandle);
422
423                         if (NULL == postHandle->pp) {
424                                 fprintf(stderr, "OOPS: Internal error fail to allocate MHD_create_post_processor\n");
425                                 free(postHandle);
426                                 return MHD_NO;
427                         }
428                         return MHD_YES;
429                 }
430                 // POST json is store into a buffer and present in one piece to API
431                 if (strcasestr(encoding, JSON_CONTENT) != NULL) {
432
433                         param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
434                         if (param)
435                                 sscanf(param, "%i", &contentlen);
436
437                         // Because PostJson are build in RAM size is constrained
438                         if (contentlen > MAX_POST_SIZE) {
439                                 errMessage = jsonNewMessage(AFB_FATAL, "Post Date to big %d > %d", contentlen, MAX_POST_SIZE);
440                                 goto ExitOnError;
441                         }
442                         // Size is OK, let's allocate a buffer to hold post data
443                         postHandle->type = AFB_POST_JSON;
444                         postHandle->privatebuf = malloc((unsigned)contentlen + 1);      // allocate memory for full POST data + 1 for '\0' enf of string
445
446                         // if (verbose) fprintf(stderr, "Create PostJson[uid=%d] Size=%d\n", postHandle->uid, contentlen);
447                         return MHD_YES;
448
449                 } else {
450                         // We only support Json and Form Post format
451                         errMessage = jsonNewMessage(AFB_FATAL, "Post Date wrong type encoding=%s != %s", encoding, JSON_CONTENT);
452                         goto ExitOnError;
453                 }
454         }
455
456         // This time we receive partial/all Post data. Note that even if we get all POST data. We should nevertheless
457         // return MHD_YES and not process the request directly. Otherwise Libmicrohttpd is unhappy and fails with
458         // 'Internal application error, closing connection'.            
459         if (*upload_data_size) {
460
461                 if (postHandle->type == AFB_POST_FORM) {
462                         // if (verbose) fprintf(stderr, "Processing PostForm[uid=%d]\n", postHandle->uid);
463                         MHD_post_process(postHandle->pp, upload_data, *upload_data_size);
464                 }
465                 // Process JsonPost request when buffer is completed let's call API    
466                 if (postHandle->type == AFB_POST_JSON) {
467                         // if (verbose) fprintf(stderr, "Updating PostJson[uid=%d]\n", postHandle->uid);
468                         memcpy(&postHandle->privatebuf[postHandle->len], upload_data, *upload_data_size);
469                         postHandle->len = postHandle->len + *upload_data_size;
470                 }
471
472                 *upload_data_size = 0;
473                 return MHD_YES;
474
475         } else {        // we have finish with Post reception let's finish the work
476
477                 // Create a request structure to finalise the request
478                 request = createRequest(connection, session, url);
479                 if (request->jresp != NULL) {
480                         errMessage = request->jresp;
481                         goto ExitOnError;
482                 }
483                 postRequest.type = postHandle->type;
484
485                 // Postform add application context handle to request
486                 if (postHandle->type == AFB_POST_FORM) {
487                         postRequest.data = (char *)postHandle;
488                         request->post = &postRequest;
489                 }
490
491                 if (postHandle->type == AFB_POST_JSON) {
492                         // if (verbose) fprintf(stderr, "Processing PostJson[uid=%d]\n", postHandle->uid);
493
494                         param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
495                         if (param)
496                                 sscanf(param, "%i", &contentlen);
497
498                         // At this level we're may verify that we got everything and process DATA
499                         if (postHandle->len != contentlen) {
500                                 errMessage = jsonNewMessage(AFB_FATAL, "Post Data Incomplete UID=%d Len %d != %d", postHandle->uid, contentlen, postHandle->len);
501                                 goto ExitOnError;
502                         }
503                         // Before processing data, make sure buffer string is properly ended
504                         postHandle->privatebuf[postHandle->len] = '\0';
505                         postRequest.data = postHandle->privatebuf;
506                         request->post = &postRequest;
507
508                         // if (verbose) fprintf(stderr, "Close Post[%d] Buffer=%s\n", postHandle->uid, request->post->data);
509                 }
510         }
511
512  ProcessApiCall:
513         // Request is ready let's call API without any extra handle
514         status = findAndCallApi(request, NULL);
515
516         serialized = json_object_to_json_string(request->jresp);
517         webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
518
519         // client did not pass token on URI let's use cookies 
520         if ((!request->restfull) && (request->context != NULL)) {
521                 char cookie[256];
522                 snprintf(cookie, sizeof(cookie), "%s-%d=%s; Path=%s; Max-Age=%d; HttpOnly", COOKIE_NAME, request->config->httpdPort, request->uuid, request->config->rootapi, request->config->cntxTimeout);
523                 MHD_add_response_header(webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
524         }
525         // if requested add an error status
526         if (request->errcode != 0)
527                 ret = MHD_queue_response(connection, request->errcode, webResponse);
528         else
529                 MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
530
531         MHD_destroy_response(webResponse);
532         json_object_put(request->jresp);        // decrease reference rqtcount to free the json object
533         freeRequest(request);
534         return MHD_YES;
535
536  ExitOnError:
537         freeRequest(request);
538         serialized = json_object_to_json_string(errMessage);
539         webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
540         MHD_queue_response(connection, MHD_HTTP_BAD_REQUEST, webResponse);
541         MHD_destroy_response(webResponse);
542         json_object_put(errMessage);    // decrease reference rqtcount to free the json object
543         return MHD_YES;
544 }
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565 static int doRestApiGet(struct MHD_Connection *connection, AFB_session * session, const char *url, const char *method, const char *upload_data, size_t * upload_data_size, void **con_cls)
566 {
567         AFB_error status;
568         struct MHD_Response *webResponse;
569         const char *serialized;
570         AFB_request *request = NULL;
571         int ret;
572
573         // fprintf (stderr, "doRestAPI method=%s posthandle=%p\n", method, con_cls);
574
575         // if post data may come in multiple calls
576         // this is a get we only need a request
577         request = createRequest(connection, session, url);
578
579         // Request is ready let's call API without any extra handle
580         status = findAndCallApi(request, NULL);
581
582         serialized = json_object_to_json_string(request->jresp);
583         webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
584
585         // client did not pass token on URI let's use cookies 
586         if ((!request->restfull) && (request->context != NULL)) {
587                 char cookie[256];
588                 snprintf(cookie, sizeof(cookie), "%s-%d=%s; Path=%s; Max-Age=%d; HttpOnly", COOKIE_NAME, request->config->httpdPort, request->uuid, request->config->rootapi, request->config->cntxTimeout);
589                 MHD_add_response_header(webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
590         }
591         // if requested add an error status
592         if (request->errcode != 0)
593                 ret = MHD_queue_response(connection, request->errcode, webResponse);
594         else
595                 MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
596
597         MHD_destroy_response(webResponse);
598         json_object_put(request->jresp);        // decrease reference rqtcount to free the json object
599         freeRequest(request);
600         return MHD_YES;
601 }
602
603 int doRestApi(struct MHD_Connection *connection, AFB_session * session, const char *url, const char *method, const char *upload_data, size_t * upload_data_size, void **con_cls)
604 {
605         int rc;
606
607         if (afbJsonType == NULL)
608                 afbJsonType = json_object_new_string (AFB_MSG_JTYPE);
609
610         if (0 == strcmp(method, MHD_HTTP_METHOD_POST)) {
611                 rc = doRestApiPost(connection, session, url, method, upload_data, upload_data_size, con_cls);
612         } else {
613                 rc = doRestApiGet(connection, session, url, method, upload_data, upload_data_size, con_cls);
614         }
615         return rc;
616 }
617