+ // if post data may come in multiple calls
+ if (0 == strcmp(method, MHD_HTTP_METHOD_POST)) {
+ const char *encoding, *param;
+ int contentlen = -1;
+ AFB_HttpPost *posthandle = *con_cls;
+
+ // 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);
+
+ // POST datas may come in multiple chunk. Even when it never happen on AFB, we still have to handle the case
+ if (strcasestr(encoding, JSON_CONTENT) == 0) {
+ errMessage = jsonNewMessage(AFB_FATAL, "Post Date wrong type encoding=%s != %s", encoding, JSON_CONTENT);
+ goto ExitOnError;
+ }
+
+ if (contentlen > MAX_POST_SIZE) {
+ errMessage = jsonNewMessage(AFB_FATAL, "Post Date to big %d > %d", contentlen, MAX_POST_SIZE);
+ goto ExitOnError;
+ }
+
+ // In POST mode first libmicrohttp call only establishes POST handling.
+ if (posthandle == NULL) {
+ posthandle = malloc(sizeof (AFB_HttpPost)); // allocate application POST processor handle
+ posthandle->uid = postcount++; // build a UID for DEBUG
+ posthandle->len = 0; // effective length within POST handler
+ posthandle->data = malloc(contentlen + 1); // allocate memory for full POST data + 1 for '\0' enf of string
+ *con_cls = posthandle; // attache POST handle to current HTTP session
+
+ if (verbose) fprintf(stderr, "Create Post[%d] Size=%d\n", posthandle->uid, contentlen);
+ return MHD_YES;
+ }
+
+ // This time we receive partial/all Post data. Note that even if we get all POST data. We should nevertheless
+ // return MHD_YES and not process the request directly. Otherwise Libmicrohttpd is unhappy and fails with
+ // 'Internal application error, closing connection'.
+ if (*upload_data_size) {
+ if (verbose) fprintf(stderr, "Update Post[%d]\n", posthandle->uid);
+
+ memcpy(&posthandle->data[posthandle->len], upload_data, *upload_data_size);
+ posthandle->len = posthandle->len + *upload_data_size;
+ *upload_data_size = 0;
+ return MHD_YES;
+ }
+
+ // We should only start to process DATA after Libmicrohttpd call or application handler with *upload_data_size==0
+ // At this level we're may verify that we got everything and process DATA
+ if (posthandle->len != contentlen) {
+ errMessage = jsonNewMessage(AFB_FATAL, "Post Data Incomplete UID=%d Len %d != %s", posthandle->uid, contentlen, posthandle->len);
+ goto ExitOnError;
+ }
+
+ // Before processing data, make sure buffer string is properly ended
+ posthandle->data[posthandle->len] = '\0';
+ request.post = posthandle->data;
+
+ if (verbose) fprintf(stderr, "Close Post[%d] Buffer=%s\n", posthandle->uid, request.post);
+