refactoring (in progress, tbf)
[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 #include "session.h"
35
36 #define AFB_MSG_JTYPE "AJB_reply"
37
38 #define JSON_CONTENT  "application/json"
39 #define FORM_CONTENT  MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
40
41 static json_object *afbJsonType;
42
43 // Because of POST call multiple time requestApi we need to free POST handle here
44 // Note this method is called from http-svc just before closing session
45 PUBLIC void endPostRequest(AFB_PostHandle * postHandle)
46 {
47
48         if (postHandle->type == AFB_POST_JSON) {
49                 // if (verbose) fprintf(stderr, "End PostJson Request UID=%d\n", postHandle->uid);
50         }
51
52         if (postHandle->type == AFB_POST_FORM) {
53                 if (verbose)
54                         fprintf(stderr, "End PostForm Request UID=%d\n", postHandle->uid);
55         }
56         if (postHandle->privatebuf)
57                 free(postHandle->privatebuf);
58         free(postHandle);
59 }
60
61 // Check of apiurl is declare in this plugin and call it
62 static AFB_error doCallPluginApi(AFB_request * request, int apiidx, int verbidx, void *context)
63 {
64         enum AFB_sessionE session;
65         json_object *jresp, *jcall, *jreqt;
66         AFB_clientCtx *clientCtx = NULL;
67
68         // Request was found and at least partially executed
69         jreqt = json_object_new_object();
70         json_object_object_add(jreqt, "jtype", json_object_get(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->method));
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);
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                 request->context = clientCtx->contexts[apiidx];
91                 request->uuid = clientCtx->uuid;
92
93                 if (verbose)
94                         fprintf(stderr, "Plugin=[%s] Api=[%s] Middleware=[%d] Client=[%p] Uuid=[%s] Token=[%s]\n", request->prefix, request->method, session, clientCtx, clientCtx->uuid, clientCtx->token);
95
96                 switch (session) {
97
98                 case AFB_SESSION_CREATE:
99                         if (clientCtx->token[0] != '\0' && request->config->token[0] != '\0') {
100                                 request->errcode = MHD_HTTP_UNAUTHORIZED;
101                                 json_object_object_add(jcall, "status", json_object_new_string("exist"));
102                                 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CREATE Session already exist"));
103                                 json_object_object_add(jreqt, "request", jcall);
104                                 goto ExitOnDone;
105                         }
106
107                         if (AFB_SUCCESS != ctxTokenCreate(clientCtx, request)) {
108                                 request->errcode = MHD_HTTP_UNAUTHORIZED;
109                                 json_object_object_add(jcall, "status", json_object_new_string("fail"));
110                                 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CREATE Invalid Initial Token"));
111                                 json_object_object_add(jreqt, "request", jcall);
112                                 goto ExitOnDone;
113                         } else {
114                                 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
115                                 json_object_object_add(jcall, "token", json_object_new_string(clientCtx->token));
116                                 json_object_object_add(jcall, "timeout", json_object_new_int(request->config->cntxTimeout));
117                         }
118                         break;
119
120                 case AFB_SESSION_RENEW:
121                         if (AFB_SUCCESS != ctxTokenRefresh(clientCtx, request)) {
122                                 request->errcode = MHD_HTTP_UNAUTHORIZED;
123                                 json_object_object_add(jcall, "status", json_object_new_string("fail"));
124                                 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_REFRESH Broken Exchange Token Chain"));
125                                 json_object_object_add(jreqt, "request", jcall);
126                                 goto ExitOnDone;
127                         } else {
128                                 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
129                                 json_object_object_add(jcall, "token", json_object_new_string(clientCtx->token));
130                                 json_object_object_add(jcall, "timeout", json_object_new_int(request->config->cntxTimeout));
131                         }
132                         break;
133
134                 case AFB_SESSION_CLOSE:
135                         if (AFB_SUCCESS != ctxTokenCheck(clientCtx, request)) {
136                                 request->errcode = MHD_HTTP_UNAUTHORIZED;
137                                 json_object_object_add(jcall, "status", json_object_new_string("empty"));
138                                 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CLOSE Not a Valid Access Token"));
139                                 json_object_object_add(jreqt, "request", jcall);
140                                 goto ExitOnDone;
141                         } else {
142                                 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
143                         }
144                         break;
145
146                 case AFB_SESSION_CHECK:
147                 default:
148                         // default action is check
149                         if (AFB_SUCCESS != ctxTokenCheck(clientCtx, request)) {
150                                 request->errcode = MHD_HTTP_UNAUTHORIZED;
151                                 json_object_object_add(jcall, "status", json_object_new_string("fail"));
152                                 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CHECK Invalid Active Token"));
153                                 json_object_object_add(jreqt, "request", jcall);
154                                 goto ExitOnDone;
155                         }
156                         break;
157                 }
158         }
159
160         // Effectively CALL PLUGIN API with a subset of the context
161         jresp = afb_apis_get(apiidx, verbidx)->callback(request, context);
162
163         // Store context in case it was updated by plugins
164         if (request->context != NULL)
165                 clientCtx->contexts[apiidx] = request->context;
166
167         // handle intermediary Post Iterates out of band
168         if ((jresp == NULL) && (request->errcode == MHD_HTTP_OK))
169                 return AFB_SUCCESS;
170
171         // Session close is done after the API call so API can still use session in closing API
172         if (AFB_SESSION_CLOSE == session)
173                 ctxTokenReset(clientCtx, request);
174
175         // API should return NULL of a valid Json Object
176         if (jresp == NULL) {
177                 json_object_object_add(jcall, "status", json_object_new_string("null"));
178                 json_object_object_add(jreqt, "request", jcall);
179                 request->errcode = MHD_HTTP_NO_RESPONSE;
180
181         } else {
182                 json_object_object_add(jcall, "status", json_object_new_string("processed"));
183                 json_object_object_add(jreqt, "request", jcall);
184                 json_object_object_add(jreqt, "response", jresp);
185         }
186
187 ExitOnDone:
188         request->jresp = jreqt;
189         return AFB_DONE;
190 }
191
192 // Check of apiurl is declare in this plugin and call it
193 extern __thread sigjmp_buf *error_handler;
194 static AFB_error callPluginApi(AFB_request * request, int apiidx, int verbidx, void *context)
195 {
196         sigjmp_buf jmpbuf, *older;
197
198         json_object *jcall, *jreqt;
199         int status;
200
201         // save context before calling the API
202         status = setjmp(jmpbuf);
203         if (status != 0) {
204
205                 // Request was found and at least partially executed
206                 jreqt = json_object_new_object();
207                 json_object_object_add(jreqt, "jtype", json_object_get(afbJsonType));
208
209                 // prepare an object to store calling values
210                 jcall = json_object_new_object();
211                 json_object_object_add(jcall, "prefix", json_object_new_string(request->prefix));
212                 json_object_object_add(jcall, "api", json_object_new_string(request->method));
213
214                 // Plugin aborted somewhere during its execution
215                 json_object_object_add(jcall, "status", json_object_new_string("abort"));
216                 json_object_object_add(jcall, "info", json_object_new_string("Plugin broke during execution"));
217                 json_object_object_add(jreqt, "request", jcall);
218                 request->jresp = jreqt;
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                 older = error_handler;
226                 error_handler = &jmpbuf;
227                 doCallPluginApi(request, apiidx, verbidx, context);
228                 error_handler = older;
229
230                 // cancel timeout and plugin signal handle before next call
231                 alarm(0);
232         }
233         return AFB_DONE;
234 }
235
236 STATIC AFB_error findAndCallApi(AFB_request * request, void *context)
237 {
238         int apiidx, verbidx;
239         AFB_error status;
240
241         if (!request->method || !request->prefix)
242                 return AFB_FAIL;
243
244         /* get the plugin if any */
245         apiidx = afb_apis_get_apiidx(request->prefix, 0);
246         if (apiidx < 0) {
247                 request->jresp = jsonNewMessage(AFB_FATAL, "No Plugin=[%s] Url=%s", request->prefix, request->url);
248                 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
249                 return AFB_FAIL;
250         }
251
252         /* get the verb if any */
253         verbidx = afb_apis_get_verbidx(apiidx, request->method);
254         if (verbidx < 0) {
255                 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->method, request->prefix, request->url);
256                 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
257                 return AFB_FAIL;
258         }
259
260         /* Search for a plugin with this urlpath */
261         status = callPluginApi(request, apiidx, verbidx, context);
262
263         /* plugin callback did not return a valid Json Object */
264         if (status == AFB_FAIL) {
265                 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->method, request->prefix, request->url);
266                 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
267                 return AFB_FAIL;
268         }
269         // Everything look OK
270         return status;
271 }
272
273 // This CB is call for every item with a form post it reformat iterator values
274 // and callback Plugin API for each Item within PostForm.
275 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)
276 {
277
278         AFB_error status;
279         AFB_PostItem item;
280
281         // retrieve API request from Post iterator handle  
282         AFB_PostHandle *postHandle = (AFB_PostHandle *) cls;
283         AFB_request *request = (AFB_request *) postHandle->privatebuf;
284         AFB_PostRequest postRequest;
285
286         if (verbose)
287                 fprintf(stderr, "postHandle key=%s filename=%s len=%zu mime=%s\n", key, filename, size, mimetype);
288
289         // Create and Item value for Plugin API
290         item.kind = kind;
291         item.key = key;
292         item.filename = filename;
293         item.mimetype = mimetype;
294         item.encoding = encoding;
295         item.len = size;
296         item.data = data;
297         item.offset = offset;
298
299         // Reformat Request to make it somehow similar to GET/PostJson case
300         postRequest.data = (char *)postHandle;
301         postRequest.len = size;
302         postRequest.type = AFB_POST_FORM;;
303         request->post = &postRequest;
304
305         // effectively call plugin API                 
306         status = findAndCallApi(request, &item);
307         // when returning no processing of postform stop
308         if (status != AFB_SUCCESS)
309                 return MHD_NO;
310
311         // let's allow iterator to move to next item
312         return MHD_YES;
313 }
314
315 STATIC void freeRequest(AFB_request * request)
316 {
317
318         free((void*)request->prefix);
319         free((void*)request->method);
320         free(request);
321 }
322
323 STATIC AFB_request *createRequest(struct MHD_Connection *connection, AFB_session * session, const char *url)
324 {
325
326         AFB_request *request;
327
328         // Start with a clean request
329         request = calloc(1, sizeof(AFB_request));
330         char *urlcpy1, *urlcpy2;
331         char *baseapi, *baseurl;
332
333         // Extract plugin urlpath from request and make two copy because strsep overload copy
334         urlcpy1 = urlcpy2 = strdup(url);
335         baseurl = strsep(&urlcpy2, "/");
336         if (baseurl == NULL) {
337                 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call url=[%s]", url);
338                 request->errcode = MHD_HTTP_BAD_REQUEST;
339                 goto Done;
340         }
341         // let's compute URL and call API
342         baseapi = strsep(&urlcpy2, "/");
343         if (baseapi == NULL) {
344                 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call plugin=[%s] url=[%s]", baseurl, url);
345                 request->errcode = MHD_HTTP_BAD_REQUEST;
346                 goto Done;
347         }
348         // build request structure
349 //      request->connection = connection;
350         request->config = session->config;
351         request->url = url;
352         request->prefix = strdup(baseurl);
353         request->method = strdup(baseapi);
354
355  Done:
356         free(urlcpy1);
357         return (request);
358 }
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374 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)
375 {
376
377         static int postcount = 0;       // static counter to debug POST protocol
378         json_object *errMessage;
379         AFB_error status;
380         struct MHD_Response *webResponse;
381         const char *serialized;
382         AFB_request *request = NULL;
383         AFB_PostHandle *postHandle;
384         AFB_PostRequest postRequest;
385         int ret;
386
387         // fprintf (stderr, "doRestAPI method=%s posthandle=%p\n", method, con_cls);
388
389         // if post data may come in multiple calls
390         const char *encoding, *param;
391         int contentlen = -1;
392         postHandle = *con_cls;
393
394         // This is the initial post event let's create form post structure POST data come in multiple events
395         if (postHandle == NULL) {
396
397                 // allocate application POST processor handle to zero
398                 postHandle = calloc(1, sizeof(AFB_PostHandle));
399                 postHandle->uid = postcount++;  // build a UID for DEBUG
400                 *con_cls = postHandle;  // update context with posthandle
401
402                 // Let make sure we have the right encoding and a valid length
403                 encoding = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE);
404
405                 // We are facing an empty post let's process it as a get
406                 if (encoding == NULL) {
407                         postHandle->type = AFB_POST_EMPTY;
408                         return MHD_YES;
409                 }
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                 }
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         // This time we receive partial/all Post data. Note that even if we get all POST data. We should nevertheless
456         // return MHD_YES and not process the request directly. Otherwise Libmicrohttpd is unhappy and fails with
457         // 'Internal application error, closing connection'.            
458         if (*upload_data_size) {
459
460                 if (postHandle->type == AFB_POST_FORM) {
461                         // if (verbose) fprintf(stderr, "Processing PostForm[uid=%d]\n", postHandle->uid);
462                         MHD_post_process(postHandle->pp, upload_data, *upload_data_size);
463                 }
464                 // Process JsonPost request when buffer is completed let's call API    
465                 if (postHandle->type == AFB_POST_JSON) {
466                         // if (verbose) fprintf(stderr, "Updating PostJson[uid=%d]\n", postHandle->uid);
467                         memcpy(&postHandle->privatebuf[postHandle->len], upload_data, *upload_data_size);
468                         postHandle->len = postHandle->len + *upload_data_size;
469                 }
470
471                 *upload_data_size = 0;
472                 return MHD_YES;
473
474         }
475
476         if (postHandle->type == AFB_POST_FORM)
477                 request = postHandle->privatebuf;
478         else
479                 // Create a request structure to finalise the request
480                 request = createRequest(connection, session, url);
481
482         if (request->jresp != NULL) {
483                 errMessage = request->jresp;
484                 goto ExitOnError;
485         }
486         postRequest.type = postHandle->type;
487
488         // Postform add application context handle to request
489         if (postHandle->type == AFB_POST_FORM) {
490                 postRequest.data = (char *)postHandle;
491                 request->post = &postRequest;
492         }
493
494         if (postHandle->type == AFB_POST_JSON) {
495                 // if (verbose) fprintf(stderr, "Processing PostJson[uid=%d]\n", postHandle->uid);
496
497                 param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
498                 if (param)
499                         sscanf(param, "%i", &contentlen);
500
501                 // At this level we're may verify that we got everything and process DATA
502                 if (postHandle->len != contentlen) {
503                         errMessage = jsonNewMessage(AFB_FATAL, "Post Data Incomplete UID=%d Len %d != %d", postHandle->uid, contentlen, postHandle->len);
504                         goto ExitOnError;
505                 }
506                 // Before processing data, make sure buffer string is properly ended
507                 postHandle->privatebuf[postHandle->len] = '\0';
508                 postRequest.data = postHandle->privatebuf;
509                 request->post = &postRequest;
510
511                 // if (verbose) fprintf(stderr, "Close Post[%d] Buffer=%s\n", postHandle->uid, request->post->data);
512         }
513
514  ProcessApiCall:
515         // Request is ready let's call API without any extra handle
516         status = findAndCallApi(request, NULL);
517
518         serialized = json_object_to_json_string(request->jresp);
519         webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
520
521         // client did not pass token on URI let's use cookies 
522         if ((!request->restfull) && (request->context != NULL)) {
523                 char cookie[256];
524                 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);
525                 MHD_add_response_header(webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
526         }
527         // if requested add an error status
528         if (request->errcode != 0)
529                 ret = MHD_queue_response(connection, request->errcode, webResponse);
530         else
531                 MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
532
533         MHD_destroy_response(webResponse);
534         json_object_put(request->jresp);        // decrease reference rqtcount to free the json object
535         freeRequest(request);
536         return MHD_YES;
537
538  ExitOnError:
539         freeRequest(request);
540         serialized = json_object_to_json_string(errMessage);
541         webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
542         MHD_queue_response(connection, MHD_HTTP_BAD_REQUEST, webResponse);
543         MHD_destroy_response(webResponse);
544         json_object_put(errMessage);    // decrease reference rqtcount to free the json object
545         return MHD_YES;
546 }
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567 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)
568 {
569         AFB_error status;
570         struct MHD_Response *webResponse;
571         const char *serialized;
572         AFB_request *request = NULL;
573         int ret;
574
575         // fprintf (stderr, "doRestAPI method=%s posthandle=%p\n", method, con_cls);
576
577         // if post data may come in multiple calls
578         // this is a get we only need a request
579         request = createRequest(connection, session, url);
580
581         // Request is ready let's call API without any extra handle
582         status = findAndCallApi(request, NULL);
583
584         serialized = json_object_to_json_string(request->jresp);
585         webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
586
587         // client did not pass token on URI let's use cookies 
588         if ((!request->restfull) && (request->context != NULL)) {
589                 char cookie[256];
590                 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);
591                 MHD_add_response_header(webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
592         }
593         // if requested add an error status
594         if (request->errcode != 0)
595                 ret = MHD_queue_response(connection, request->errcode, webResponse);
596         else
597                 MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
598
599         MHD_destroy_response(webResponse);
600         json_object_put(request->jresp);        // decrease reference rqtcount to free the json object
601         freeRequest(request);
602         return MHD_YES;
603 }
604
605 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)
606 {
607         int rc;
608
609         if (afbJsonType == NULL)
610                 afbJsonType = json_object_new_string (AFB_MSG_JTYPE);
611
612         if (0 == strcmp(method, MHD_HTTP_METHOD_POST)) {
613                 rc = doRestApiPost(connection, session, url, method, upload_data, upload_data_size, con_cls);
614         } else {
615                 rc = doRestApiGet(connection, session, url, method, upload_data, upload_data_size, con_cls);
616         }
617         return rc;
618 }
619