#include <curl/curl.h>
#include <curl/easy.h>

typedef struct _response
{
	size_t length;
	char* response;
} response;

size_t write_callback(void *ptr, size_t size, size_t nmemb, void *stream)
{
	if (size * nmemb) {
		char* tmp;
		if ((tmp = (char*)realloc(((response*)stream)->response, ((response*)stream)->length + size * nmemb + 1))) {
			((response*)stream)->response = tmp;
			memcpy(((response*)stream)->response + ((response*)stream)->length , ptr, size * nmemb);
			((response*)stream)->response[((response*)stream)->length + size * nmemb] = 0;
			((response*)stream)->length += size * nmemb;
		}
	}
	return size * nmemb;
}

int main(int argc, char* argv[])
{
	int status;
	char url[] = "http://69.232.142.37/index.asp";
	char username[] = "test";
	char password[] = "test";
	char postdata[] = "AnyField=1&AnotherField=2";
	char* szUserPass = NULL;
	CURL* curl;
	response resp = {0, NULL};
	curl_global_init(CURL_GLOBAL_ALL);
	if ((curl = curl_easy_init())) {
		if (username && password && username[0] && password[0]) {
			//this allocation fails gracefully we will try to post with no password
			szUserPass = (char*)malloc(strlen(username) + strlen(password) + 2);
			sprintf(szUserPass, "%s:%s", username, password);
		}
		if (url && url[0]) {
			if (((status = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback)) == 0) &&
			((status = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &resp)) == 0) &&
			((status = curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata)) == 0) &&
			((status = curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0)) == 0) &&
			((status = curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0)) == 0) &&
			((status = curl_easy_setopt(curl, CURLOPT_CAPATH, NULL)) == 0) &&
			((status = curl_easy_setopt(curl, CURLOPT_CAINFO, NULL)) == 0) &&
			((status = curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(postdata))) == 0) &&
			((status = curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY)) == 0) &&
			((status = curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1)) == 0) &&
			((status = curl_easy_setopt(curl, CURLOPT_VERBOSE, 1)) == 0) &&
			(szUserPass ? ((status = curl_easy_setopt(curl, CURLOPT_USERPWD, szUserPass)) == 0) : 1)) {
				if ((status = curl_easy_setopt(curl, CURLOPT_URL, url)) == 0) {
					if (((status = curl_easy_perform(curl)) == 0) && (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status) == CURLE_OK) && (status == 200)) {
						// Infinite loop in function Transfer (in transfer.c)
					}
				}
			}
			if (resp.response)
				free(resp.response);
		}
		if (szUserPass)
			free(szUserPass);
		curl_easy_cleanup(curl);
	}
	curl_global_cleanup();
}
