refactor context usage
[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);
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->api, 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         // Effectively CALL PLUGIN API with a subset of the context
160         jresp = afb_apis_get(apiidx, verbidx)->callback(request, context);
161
162         // Store context in case it was updated by plugins
163         if (request->context != NULL)
164                 clientCtx->contexts[apiidx] = request->context;
165
166         // handle intermediary Post Iterates out of band
167         if ((jresp == NULL) && (request->errcode == MHD_HTTP_OK))
168                 return AFB_SUCCESS;
169
170         // Session close is done after the API call so API can still use session in closing API
171         if (AFB_SESSION_CLOSE == session)
172                 ctxTokenReset(clientCtx, request);
173
174         // API should return NULL of a valid Json Object
175         if (jresp == NULL) {
176                 json_object_object_add(jcall, "status", json_object_new_string("null"));
177                 json_object_object_add(jreqt, "request", jcall);
178                 request->errcode = MHD_HTTP_NO_RESPONSE;
179
180         } else {
181                 json_object_object_add(jcall, "status", json_object_new_string("processed"));
182                 json_object_object_add(jreqt, "request", jcall);
183                 json_object_object_add(jreqt, "response", jresp);
184         }
185
186 ExitOnDone:
187         request->jresp = jreqt;
188         return AFB_DONE;
189 }
190
191 // Check of apiurl is declare in this plugin and call it
192 extern __thread sigjmp_buf *error_handler;
193 static AFB_error callPluginApi(AFB_request * request, int apiidx, int verbidx, void *context)
194 {
195         sigjmp_buf jmpbuf;
196
197         json_object *jcall, *jreqt;
198         int status;
199
200         // save context before calling the API
201         status = setjmp(jmpbuf);
202         if (status != 0) {
203
204                 // Request was found and at least partially executed
205                 jreqt = json_object_new_object();
206                 json_object_get(afbJsonType);   // increate jsontype reference count
207                 json_object_object_add(jreqt, "jtype", 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->api));
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                 goto ExitOnDone;
220
221         } else {
222
223                 // Trigger a timer to protect from unacceptable long time execution
224                 if (request->config->apiTimeout > 0)
225                         alarm((unsigned)request->config->apiTimeout);
226
227                 error_handler = &jmpbuf;
228                 doCallPluginApi(request, apiidx, verbidx, context);
229                 error_handler = NULL;
230
231                 // cancel timeout and plugin signal handle before next call
232                 alarm(0);
233         }
234
235 ExitOnDone:
236         return AFB_DONE;
237 }
238
239 STATIC AFB_error findAndCallApi(AFB_request * request, void *context)
240 {
241         int apiidx, verbidx;
242         AFB_error status;
243
244         if (!request->api || !request->prefix)
245                 return AFB_FAIL;
246
247         /* get the plugin if any */
248         apiidx = afb_apis_get_apiidx(request->prefix, 0);
249         if (apiidx < 0) {
250                 request->jresp = jsonNewMessage(AFB_FATAL, "No Plugin=[%s] Url=%s", request->prefix, request->url);
251                 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
252                 return AFB_FAIL;
253         }
254
255         /* get the verb if any */
256         verbidx = afb_apis_get_verbidx(apiidx, request->api);
257         if (verbidx < 0) {
258                 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->api, request->prefix, request->url);
259                 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
260                 return AFB_FAIL;
261         }
262
263         /* Search for a plugin with this urlpath */
264         status = callPluginApi(request, apiidx, verbidx, context);
265
266         /* plugin callback did not return a valid Json Object */
267         if (status == AFB_FAIL) {
268                 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->api, request->prefix, request->url);
269                 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
270                 return AFB_FAIL;
271         }
272         // Everything look OK
273         return status;
274 }
275
276 // This CB is call for every item with a form post it reformat iterator values
277 // and callback Plugin API for each Item within PostForm.
278 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)
279 {
280
281         AFB_error status;
282         AFB_PostItem item;
283
284         // retrieve API request from Post iterator handle  
285         AFB_PostHandle *postHandle = (AFB_PostHandle *) cls;
286         AFB_request *request = (AFB_request *) postHandle->privatebuf;
287         AFB_PostRequest postRequest;
288
289         if (verbose)
290                 fprintf(stderr, "postHandle key=%s filename=%s len=%zu mime=%s\n", key, filename, size, mimetype);
291
292         // Create and Item value for Plugin API
293         item.kind = kind;
294         item.key = key;
295         item.filename = filename;
296         item.mimetype = mimetype;
297         item.encoding = encoding;
298         item.len = size;
299         item.data = data;
300         item.offset = offset;
301
302         // Reformat Request to make it somehow similar to GET/PostJson case
303         postRequest.data = (char *)postHandle;
304         postRequest.len = size;
305         postRequest.type = AFB_POST_FORM;;
306         request->post = &postRequest;
307
308         // effectively call plugin API                 
309         status = findAndCallApi(request, &item);
310         // when returning no processing of postform stop
311         if (status != AFB_SUCCESS)
312                 return MHD_NO;
313
314         // let's allow iterator to move to next item
315         return MHD_YES;
316 }
317
318 STATIC void freeRequest(AFB_request * request)
319 {
320
321         free(request->prefix);
322         free(request->api);
323         free(request);
324 }
325
326 STATIC AFB_request *createRequest(struct MHD_Connection *connection, AFB_session * session, const char *url)
327 {
328
329         AFB_request *request;
330
331         // Start with a clean request
332         request = calloc(1, sizeof(AFB_request));
333         char *urlcpy1, *urlcpy2;
334         char *baseapi, *baseurl;
335
336         // Extract plugin urlpath from request and make two copy because strsep overload copy
337         urlcpy1 = urlcpy2 = strdup(url);
338         baseurl = strsep(&urlcpy2, "/");
339         if (baseurl == NULL) {
340                 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call url=[%s]", url);
341                 request->errcode = MHD_HTTP_BAD_REQUEST;
342                 goto Done;
343         }
344         // let's compute URL and call API
345         baseapi = strsep(&urlcpy2, "/");
346         if (baseapi == NULL) {
347                 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call plugin=[%s] url=[%s]", baseurl, url);
348                 request->errcode = MHD_HTTP_BAD_REQUEST;
349                 goto Done;
350         }
351         // build request structure
352         request->connection = connection;
353         request->config = session->config;
354         request->url = url;
355         request->prefix = strdup(baseurl);
356         request->api = strdup(baseapi);
357
358  Done:
359         free(urlcpy1);
360         return (request);
361 }
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377 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)
378 {
379
380         static int postcount = 0;       // static counter to debug POST protocol
381         json_object *errMessage;
382         AFB_error status;
383         struct MHD_Response *webResponse;
384         const char *serialized;
385         AFB_request *request = NULL;
386         AFB_PostHandle *postHandle;
387         AFB_PostRequest postRequest;
388         int ret;
389
390         // fprintf (stderr, "doRestAPI method=%s posthandle=%p\n", method, con_cls);
391
392         // if post data may come in multiple calls
393         const char *encoding, *param;
394         int contentlen = -1;
395         postHandle = *con_cls;
396
397         // This is the initial post event let's create form post structure POST data come in multiple events
398         if (postHandle == NULL) {
399
400                 // allocate application POST processor handle to zero
401                 postHandle = calloc(1, sizeof(AFB_PostHandle));
402                 postHandle->uid = postcount++;  // build a UID for DEBUG
403                 *con_cls = postHandle;  // update context with posthandle
404
405                 // Let make sure we have the right encoding and a valid length
406                 encoding = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE);
407
408                 // We are facing an empty post let's process it as a get
409                 if (encoding == NULL) {
410                         postHandle->type = AFB_POST_EMPTY;
411                         return MHD_YES;
412                 }
413                 // Form post is handle through a PostProcessor and call API once per form key
414                 if (strcasestr(encoding, FORM_CONTENT) != NULL) {
415                         if (verbose)
416                                 fprintf(stderr, "Create doPostIterate[uid=%d posthandle=%p]\n", postHandle->uid, postHandle);
417
418                         request = createRequest(connection, session, url);
419                         if (request->jresp != NULL)
420                                 goto ProcessApiCall;
421                         postHandle->type = AFB_POST_FORM;
422                         postHandle->privatebuf = (void *)request;
423                         postHandle->pp = MHD_create_post_processor(connection, MAX_POST_SIZE, &doPostIterate, postHandle);
424
425                         if (NULL == postHandle->pp) {
426                                 fprintf(stderr, "OOPS: Internal error fail to allocate MHD_create_post_processor\n");
427                                 free(postHandle);
428                                 return MHD_NO;
429                         }
430                         return MHD_YES;
431                 }
432                 // POST json is store into a buffer and present in one piece to API
433                 if (strcasestr(encoding, JSON_CONTENT) != NULL) {
434
435                         param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
436                         if (param)
437                                 sscanf(param, "%i", &contentlen);
438
439                         // Because PostJson are build in RAM size is constrained
440                         if (contentlen > MAX_POST_SIZE) {
441                                 errMessage = jsonNewMessage(AFB_FATAL, "Post Date to big %d > %d", contentlen, MAX_POST_SIZE);
442                                 goto ExitOnError;
443                         }
444                         // Size is OK, let's allocate a buffer to hold post data
445                         postHandle->type = AFB_POST_JSON;
446                         postHandle->privatebuf = malloc((unsigned)contentlen + 1);      // allocate memory for full POST data + 1 for '\0' enf of string
447
448                         // if (verbose) fprintf(stderr, "Create PostJson[uid=%d] Size=%d\n", postHandle->uid, contentlen);
449                         return MHD_YES;
450
451                 } else {
452                         // We only support Json and Form Post format
453                         errMessage = jsonNewMessage(AFB_FATAL, "Post Date wrong type encoding=%s != %s", encoding, JSON_CONTENT);
454                         goto ExitOnError;
455                 }
456         }
457
458         // This time we receive partial/all Post data. Note that even if we get all POST data. We should nevertheless
459         // return MHD_YES and not process the request directly. Otherwise Libmicrohttpd is unhappy and fails with
460         // 'Internal application error, closing connection'.            
461         if (*upload_data_size) {
462
463                 if (postHandle->type == AFB_POST_FORM) {
464                         // if (verbose) fprintf(stderr, "Processing PostForm[uid=%d]\n", postHandle->uid);
465                         MHD_post_process(postHandle->pp, upload_data, *upload_data_size);
466                 }
467                 // Process JsonPost request when buffer is completed let's call API    
468                 if (postHandle->type == AFB_POST_JSON) {
469                         // if (verbose) fprintf(stderr, "Updating PostJson[uid=%d]\n", postHandle->uid);
470                         memcpy(&postHandle->privatebuf[postHandle->len], upload_data, *upload_data_size);
471                         postHandle->len = postHandle->len + *upload_data_size;
472                 }
473
474                 *upload_data_size = 0;
475                 return MHD_YES;
476
477         } else {        // we have finish with Post reception let's finish the work
478
479                 // Create a request structure to finalise the request
480                 request = createRequest(connection, session, url);
481                 if (request->jresp != NULL) {
482                         errMessage = request->jresp;
483                         goto ExitOnError;
484                 }
485                 postRequest.type = postHandle->type;
486
487                 // Postform add application context handle to request
488                 if (postHandle->type == AFB_POST_FORM) {
489                         postRequest.data = (char *)postHandle;
490                         request->post = &postRequest;
491                 }
492
493                 if (postHandle->type == AFB_POST_JSON) {
494                         // if (verbose) fprintf(stderr, "Processing PostJson[uid=%d]\n", postHandle->uid);
495
496                         param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
497                         if (param)
498                                 sscanf(param, "%i", &contentlen);
499
500                         // At this level we're may verify that we got everything and process DATA
501                         if (postHandle->len != contentlen) {
502                                 errMessage = jsonNewMessage(AFB_FATAL, "Post Data Incomplete UID=%d Len %d != %d", postHandle->uid, contentlen, postHandle->len);
503                                 goto ExitOnError;
504                         }
505                         // Before processing data, make sure buffer string is properly ended
506                         postHandle->privatebuf[postHandle->len] = '\0';
507                         postRequest.data = postHandle->privatebuf;
508                         request->post = &postRequest;
509
510                         // if (verbose) fprintf(stderr, "Close Post[%d] Buffer=%s\n", postHandle->uid, request->post->data);
511                 }
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