+ free(urlcpy1);
+}
+
+// process rest API query
+PUBLIC 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) {
+
+ static int postcount = 0; // static counter to debug POST protocol
+ json_object *errMessage;
+ AFB_error status;
+ struct MHD_Response *webResponse;
+ const char *serialized;
+ AFB_request request;
+ AFB_PostHandle *posthandle;
+ int ret;
+
+ // if post data may come in multiple calls
+ if (0 == strcmp(method, MHD_HTTP_METHOD_POST)) {
+ const char *encoding, *param;
+ int contentlen = -1;
+ posthandle = *con_cls;
+
+ // This is the initial post event let's create form post structure POST datas come in multiple events
+ if (posthandle == NULL) {
+ fprintf(stderr, "This is the 1st Post Event postuid=%d\n", posthandle->uid);
+
+ // allocate application POST processor handle to zero
+ posthandle = cmalloc(1, sizeof (AFB_PostHandle));
+ posthandle->uid = postcount++; // build a UID for DEBUG
+ *con_cls = posthandle; // attache POST handle to current HTTP request
+
+ // Let make sure we have the right encoding and a valid length
+ encoding = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE);
+ param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
+ if (param) sscanf(param, "%i", &contentlen);
+
+ // Form post is handle through a PostProcessor and call API once per form key
+ if (strcasestr(encoding, FORM_CONTENT) != NULL) {
+
+ posthandle = malloc(sizeof (AFB_PostHandle)); // allocate application POST processor handle
+ posthandle->type = AFB_POST_FORM;
+ posthandle->private= (void*)createRequest (connection, session, url);
+ posthandle->pp = MHD_create_post_processor (connection, MAX_POST_SIZE, doPostIterate, posthandle);
+
+ if (NULL == posthandle->pp) {
+ fprintf(stderr,"OOPS: Internal error fail to allocate MHD_create_post_processor\n");
+ free (posthandle);
+ return MHD_NO;
+ }
+ return MHD_YES;
+ }
+
+ // POST json is store into a buffer and present in one piece to API
+ if (strcasestr(encoding, JSON_CONTENT) != NULL) {
+
+ if (contentlen > MAX_POST_SIZE) {
+ errMessage = jsonNewMessage(AFB_FATAL, "Post Date to big %d > %d", contentlen, MAX_POST_SIZE);
+ goto ExitOnError;
+ }
+
+ if (posthandle == NULL) {
+ posthandle->type = AFB_POST_JSON;
+ posthandle->private = malloc(contentlen + 1); // allocate memory for full POST data + 1 for '\0' enf of string
+
+ if (verbose) fprintf(stderr, "Create PostJson[%d] Size=%d\n", posthandle->uid, contentlen);
+ return MHD_YES;
+ }
+
+ // We only support Json and Form Post format
+ errMessage = jsonNewMessage(AFB_FATAL, "Post Date wrong type encoding=%s != %s", encoding, JSON_CONTENT);
+ goto ExitOnError;
+ }