renaming of field api
[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  "multipart/form-data"     /* TODO: replace with 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_get(afbJsonType);   // increate jsontype reference count
71         json_object_object_add(jreqt, "jtype", afbJsonType);
72
73         // prepare an object to store calling values
74         jcall = json_object_new_object();
75         json_object_object_add(jcall, "prefix", json_object_new_string(request->prefix));
76         json_object_object_add(jcall, "api", json_object_new_string(request->method));
77
78         // Out of SessionNone every call get a client context session
79         session = afb_apis_get(apiidx, verbidx)->session;
80         if (AFB_SESSION_NONE != session) {
81
82                 // add client context to request
83                 clientCtx = ctxClientGet(request);
84                 if (clientCtx == NULL) {
85                         request->errcode = MHD_HTTP_INSUFFICIENT_STORAGE;
86                         json_object_object_add(jcall, "status", json_object_new_string("fail"));
87                         json_object_object_add(jcall, "info", json_object_new_string("Client Session Context Full !!!"));
88                         json_object_object_add(jreqt, "request", jcall);
89                         goto ExitOnDone;
90                 }
91                 request->context = clientCtx->contexts[apiidx];
92                 request->uuid = clientCtx->uuid;
93
94                 if (verbose)
95                         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);
96
97                 switch (session) {
98
99                 case AFB_SESSION_CREATE:
100                         if (clientCtx->token[0] != '\0' && request->config->token[0] != '\0') {
101                                 request->errcode = MHD_HTTP_UNAUTHORIZED;
102                                 json_object_object_add(jcall, "status", json_object_new_string("exist"));
103                                 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CREATE Session already exist"));
104                                 json_object_object_add(jreqt, "request", jcall);
105                                 goto ExitOnDone;
106                         }
107
108                         if (AFB_SUCCESS != ctxTokenCreate(clientCtx, request)) {
109                                 request->errcode = MHD_HTTP_UNAUTHORIZED;
110                                 json_object_object_add(jcall, "status", json_object_new_string("fail"));
111                                 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CREATE Invalid Initial Token"));
112                                 json_object_object_add(jreqt, "request", jcall);
113                                 goto ExitOnDone;
114                         } else {
115                                 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
116                                 json_object_object_add(jcall, "token", json_object_new_string(clientCtx->token));
117                                 json_object_object_add(jcall, "timeout", json_object_new_int(request->config->cntxTimeout));
118                         }
119                         break;
120
121                 case AFB_SESSION_RENEW:
122                         if (AFB_SUCCESS != ctxTokenRefresh(clientCtx, request)) {
123                                 request->errcode = MHD_HTTP_UNAUTHORIZED;
124                                 json_object_object_add(jcall, "status", json_object_new_string("fail"));
125                                 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_REFRESH Broken Exchange Token Chain"));
126                                 json_object_object_add(jreqt, "request", jcall);
127                                 goto ExitOnDone;
128                         } else {
129                                 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
130                                 json_object_object_add(jcall, "token", json_object_new_string(clientCtx->token));
131                                 json_object_object_add(jcall, "timeout", json_object_new_int(request->config->cntxTimeout));
132                         }
133                         break;
134
135                 case AFB_SESSION_CLOSE:
136                         if (AFB_SUCCESS != ctxTokenCheck(clientCtx, request)) {
137                                 request->errcode = MHD_HTTP_UNAUTHORIZED;
138                                 json_object_object_add(jcall, "status", json_object_new_string("empty"));
139                                 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CLOSE Not a Valid Access Token"));
140                                 json_object_object_add(jreqt, "request", jcall);
141                                 goto ExitOnDone;
142                         } else {
143                                 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
144                         }
145                         break;
146
147                 case AFB_SESSION_CHECK:
148                 default:
149                         // default action is check
150                         if (AFB_SUCCESS != ctxTokenCheck(clientCtx, request)) {
151                                 request->errcode = MHD_HTTP_UNAUTHORIZED;
152                                 json_object_object_add(jcall, "status", json_object_new_string("fail"));
153                                 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CHECK Invalid Active Token"));
154                                 json_object_object_add(jreqt, "request", jcall);
155                                 goto ExitOnDone;
156                         }
157                         break;
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;
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_get(afbJsonType);   // increate jsontype reference count
208                 json_object_object_add(jreqt, "jtype", afbJsonType);
209
210                 // prepare an object to store calling values
211                 jcall = json_object_new_object();
212                 json_object_object_add(jcall, "prefix", json_object_new_string(request->prefix));
213                 json_object_object_add(jcall, "api", json_object_new_string(request->method));
214
215                 // Plugin aborted somewhere during its execution
216                 json_object_object_add(jcall, "status", json_object_new_string("abort"));
217                 json_object_object_add(jcall, "info", json_object_new_string("Plugin broke during execution"));
218                 json_object_object_add(jreqt, "request", jcall);
219                 request->jresp = jreqt;
220                 goto ExitOnDone;
221
222         } else {
223
224                 // Trigger a timer to protect from unacceptable long time execution
225                 if (request->config->apiTimeout > 0)
226                         alarm((unsigned)request->config->apiTimeout);
227
228                 error_handler = &jmpbuf;
229                 doCallPluginApi(request, apiidx, verbidx, context);
230                 error_handler = NULL;
231
232                 // cancel timeout and plugin signal handle before next call
233                 alarm(0);
234         }
235
236 ExitOnDone:
237         return AFB_DONE;
238 }
239
240 STATIC AFB_error findAndCallApi(AFB_request * request, void *context)
241 {
242         int apiidx, verbidx;
243         AFB_error status;
244
245         if (!request->method || !request->prefix)
246                 return AFB_FAIL;
247
248         /* get the plugin if any */
249         apiidx = afb_apis_get_apiidx(request->prefix, 0);
250         if (apiidx < 0) {
251                 request->jresp = jsonNewMessage(AFB_FATAL, "No Plugin=[%s] Url=%s", request->prefix, request->url);
252                 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
253                 return AFB_FAIL;
254         }
255
256         /* get the verb if any */
257         verbidx = afb_apis_get_verbidx(apiidx, request->method);
258         if (verbidx < 0) {
259                 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->method, request->prefix, request->url);
260                 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
261                 return AFB_FAIL;
262         }
263
264         /* Search for a plugin with this urlpath */
265         status = callPluginApi(request, apiidx, verbidx, context);
266
267         /* plugin callback did not return a valid Json Object */
268         if (status == AFB_FAIL) {
269                 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->method, request->prefix, request->url);
270                 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
271                 return AFB_FAIL;
272         }
273         // Everything look OK
274         return status;
275 }
276
277 // This CB is call for every item with a form post it reformat iterator values
278 // and callback Plugin API for each Item within PostForm.
279 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)
280 {
281
282         AFB_error status;
283         AFB_PostItem item;
284
285         // retrieve API request from Post iterator handle  
286         AFB_PostHandle *postHandle = (AFB_PostHandle *) cls;
287         AFB_request *request = (AFB_request *) postHandle->privatebuf;
288         AFB_PostRequest postRequest;
289
290         if (verbose)
291                 fprintf(stderr, "postHandle key=%s filename=%s len=%zu mime=%s\n", key, filename, size, mimetype);
292
293         // Create and Item value for Plugin API
294         item.kind = kind;
295         item.key = key;
296         item.filename = filename;
297         item.mimetype = mimetype;
298         item.encoding = encoding;
299         item.len = size;
300         item.data = data;
301         item.offset = offset;
302
303         // Reformat Request to make it somehow similar to GET/PostJson case
304         postRequest.data = (char *)postHandle;
305         postRequest.len = size;
306         postRequest.type = AFB_POST_FORM;;
307         request->post = &postRequest;
308
309         // effectively call plugin API                 
310         status = findAndCallApi(request, &item);
311         // when returning no processing of postform stop
312         if (status != AFB_SUCCESS)
313                 return MHD_NO;
314
315         // let's allow iterator to move to next item
316         return MHD_YES;
317 }
318
319 STATIC void freeRequest(AFB_request * request)
320 {
321
322         free(request->prefix);
323         free(request->method);
324         free(request);
325 }
326
327 STATIC AFB_request *createRequest(struct MHD_Connection *connection, AFB_session * session, const char *url)
328 {
329
330         AFB_request *request;
331
332         // Start with a clean request
333         request = calloc(1, sizeof(AFB_request));
334         char *urlcpy1, *urlcpy2;
335         char *baseapi, *baseurl;
336
337         // Extract plugin urlpath from request and make two copy because strsep overload copy
338         urlcpy1 = urlcpy2 = strdup(url);
339         baseurl = strsep(&urlcpy2, "/");
340         if (baseurl == NULL) {
341                 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call url=[%s]", url);
342                 request->errcode = MHD_HTTP_BAD_REQUEST;
343                 goto Done;
344         }
345         // let's compute URL and call API
346         baseapi = strsep(&urlcpy2, "/");
347         if (baseapi == NULL) {
348                 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call plugin=[%s] url=[%s]", baseurl, url);
349                 request->errcode = MHD_HTTP_BAD_REQUEST;
350                 goto Done;
351         }
352         // build request structure
353         request->connection = connection;
354         request->config = session->config;
355         request->url = url;
356         request->prefix = strdup(baseurl);
357         request->method = strdup(baseapi);
358
359  Done:
360         free(urlcpy1);
361         return (request);
362 }
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378 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)
379 {
380
381         static int postcount = 0;       // static counter to debug POST protocol
382         json_object *errMessage;
383         AFB_error status;
384         struct MHD_Response *webResponse;
385         const char *serialized;
386         AFB_request *request = NULL;
387         AFB_PostHandle *postHandle;
388         AFB_PostRequest postRequest;
389         int ret;
390
391         // fprintf (stderr, "doRestAPI method=%s posthandle=%p\n", method, con_cls);
392
393         // if post data may come in multiple calls
394         const char *encoding, *param;
395         int contentlen = -1;
396         postHandle = *con_cls;
397
398         // This is the initial post event let's create form post structure POST data come in multiple events
399         if (postHandle == NULL) {
400
401                 // allocate application POST processor handle to zero
402                 postHandle = calloc(1, sizeof(AFB_PostHandle));
403                 postHandle->uid = postcount++;  // build a UID for DEBUG
404                 *con_cls = postHandle;  // update context with posthandle
405
406                 // Let make sure we have the right encoding and a valid length
407                 encoding = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE);
408
409                 // We are facing an empty post let's process it as a get
410                 if (encoding == NULL) {
411                         postHandle->type = AFB_POST_EMPTY;
412                         return MHD_YES;
413                 }
414                 // Form post is handle through a PostProcessor and call API once per form key
415                 if (strcasestr(encoding, FORM_CONTENT) != NULL) {
416                         if (verbose)
417                                 fprintf(stderr, "Create doPostIterate[uid=%d posthandle=%p]\n", postHandle->uid, postHandle);
418
419                         request = createRequest(connection, session, url);
420                         if (request->jresp != NULL)
421                                 goto ProcessApiCall;
422                         postHandle->type = AFB_POST_FORM;
423                         postHandle->privatebuf = (void *)request;
424                         postHandle->pp = MHD_create_post_processor(connection, MAX_POST_SIZE, &doPostIterate, postHandle);
425
426                         if (NULL == postHandle->pp) {
427                                 fprintf(stderr, "OOPS: Internal error fail to allocate MHD_create_post_processor\n");
428                                 free(postHandle);
429                                 return MHD_NO;
430                         }
431                         return MHD_YES;
432                 }
433                 // POST json is store into a buffer and present in one piece to API
434                 if (strcasestr(encoding, JSON_CONTENT) != NULL) {
435
436                         param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
437                         if (param)
438                                 sscanf(param, "%i", &contentlen);
439
440                         // Because PostJson are build in RAM size is constrained
441                         if (contentlen > MAX_POST_SIZE) {
442                                 errMessage = jsonNewMessage(AFB_FATAL, "Post Date to big %d > %d", contentlen, MAX_POST_SIZE);
443                                 goto ExitOnError;
444                         }
445                         // Size is OK, let's allocate a buffer to hold post data
446                         postHandle->type = AFB_POST_JSON;
447                         postHandle->privatebuf = malloc((unsigned)contentlen + 1);      // allocate memory for full POST data + 1 for '\0' enf of string
448
449                         // if (verbose) fprintf(stderr, "Create PostJson[uid=%d] Size=%d\n", postHandle->uid, contentlen);
450                         return MHD_YES;
451
452                 } else {
453                         // We only support Json and Form Post format
454                         errMessage = jsonNewMessage(AFB_FATAL, "Post Date wrong type encoding=%s != %s", encoding, JSON_CONTENT);
455                         goto ExitOnError;
456                 }
457         }
458
459         // This time we receive partial/all Post data. Note that even if we get all POST data. We should nevertheless
460         // return MHD_YES and not process the request directly. Otherwise Libmicrohttpd is unhappy and fails with
461         // 'Internal application error, closing connection'.            
462         if (*upload_data_size) {
463
464                 if (postHandle->type == AFB_POST_FORM) {
465                         // if (verbose) fprintf(stderr, "Processing PostForm[uid=%d]\n", postHandle->uid);
466                         MHD_post_process(postHandle->pp, upload_data, *upload_data_size);
467                 }
468                 // Process JsonPost request when buffer is completed let's call API    
469                 if (postHandle->type == AFB_POST_JSON) {
470                         // if (verbose) fprintf(stderr, "Updating PostJson[uid=%d]\n", postHandle->uid);
471                         memcpy(&postHandle->privatebuf[postHandle->len], upload_data, *upload_data_size);
472                         postHandle->len = postHandle->len + *upload_data_size;
473                 }
474
475                 *upload_data_size = 0;
476                 return MHD_YES;
477
478         } else {        // we have finish with Post reception let's finish the work
479
480                 // Create a request structure to finalise the request
481                 request = createRequest(connection, session, url);
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
515  ProcessApiCall:
516         // Request is ready let's call API without any extra handle
517         status = findAndCallApi(request, NULL);
518
519         serialized = json_object_to_json_string(request->jresp);
520         webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
521
522         // client did not pass token on URI let's use cookies 
523         if ((!request->restfull) && (request->context != NULL)) {
524                 char cookie[256];
525                 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);
526                 MHD_add_response_header(webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
527         }
528         // if requested add an error status
529         if (request->errcode != 0)
530                 ret = MHD_queue_response(connection, request->errcode, webResponse);
531         else
532                 MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
533
534         MHD_destroy_response(webResponse);
535         json_object_put(request->jresp);        // decrease reference rqtcount to free the json object
536         freeRequest(request);
537         return MHD_YES;
538
539  ExitOnError:
540         freeRequest(request);
541         serialized = json_object_to_json_string(errMessage);
542         webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
543         MHD_queue_response(connection, MHD_HTTP_BAD_REQUEST, webResponse);
544         MHD_destroy_response(webResponse);
545         json_object_put(errMessage);    // decrease reference rqtcount to free the json object
546         return MHD_YES;
547 }
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568 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)
569 {
570         AFB_error status;
571         struct MHD_Response *webResponse;
572         const char *serialized;
573         AFB_request *request = NULL;
574         int ret;
575
576         // fprintf (stderr, "doRestAPI method=%s posthandle=%p\n", method, con_cls);
577
578         // if post data may come in multiple calls
579         // this is a get we only need a request
580         request = createRequest(connection, session, url);
581
582         // Request is ready let's call API without any extra handle
583         status = findAndCallApi(request, NULL);
584
585         serialized = json_object_to_json_string(request->jresp);
586         webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
587
588         // client did not pass token on URI let's use cookies 
589         if ((!request->restfull) && (request->context != NULL)) {
590                 char cookie[256];
591                 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);
592                 MHD_add_response_header(webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
593         }
594         // if requested add an error status
595         if (request->errcode != 0)
596                 ret = MHD_queue_response(connection, request->errcode, webResponse);
597         else
598                 MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
599
600         MHD_destroy_response(webResponse);
601         json_object_put(request->jresp);        // decrease reference rqtcount to free the json object
602         freeRequest(request);
603         return MHD_YES;
604 }
605
606 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)
607 {
608         int rc;
609
610         if (afbJsonType == NULL)
611                 afbJsonType = json_object_new_string (AFB_MSG_JTYPE);
612
613         if (0 == strcmp(method, MHD_HTTP_METHOD_POST)) {
614                 rc = doRestApiPost(connection, session, url, method, upload_data, upload_data_size, con_cls);
615         } else {
616                 rc = doRestApiGet(connection, session, url, method, upload_data, upload_data_size, con_cls);
617         }
618         return rc;
619 }
620