Exemplo n.º 1
0
		void					inet_reader::run(HINTERNET handle)
		{
			vector<char> buffer;
			while(true)
			{
				DWORD available=0;
				if(!InternetQueryDataAvailable(handle,&available,0,NULL))
					break;
				if(!available)
					break;
				buffer.resize(max(max(1,available),buffer.size()));
				__int64 bytes_to_read=(__int64)buffer.size();
				if(_bytes_to_read>=0)
					bytes_to_read=min(bytes_to_read,_bytes_to_read-_bytes_read);
				DWORD bytes_read=0;
				if(!InternetReadFile(handle,&buffer[0],(DWORD)bytes_to_read,&bytes_read))
					break;
				_bytes_read+=bytes_read;

				if(bytes_read)
					if(!read(&buffer[0],(long)bytes_read))
						break;

				if(_bytes_read==_bytes_to_read)
					break;
			}
			on_stop();
		}
Exemplo n.º 2
0
/**
 * Sends data to the Web Service.
 *
 * @param InputData
 * A std::string containing all the data, which is going to be submitted as HTTP POST data.
 *
 * @return
 * Returns a pointer to a char array containing the data received from the Web Service.
 * The caller needs to free that pointer.
 */
PCHAR
CWebService::DoRequest(const string& InputData)
{
    const WCHAR szHeaders[] = L"Content-Type: application/x-www-form-urlencoded";

    auto_array_ptr<char> Data;
    DWORD DataLength;

    /* Post our test results to the web service */
    m_hHTTPRequest = HttpOpenRequestW(m_hHTTP, L"POST", szServerFile, NULL, NULL, NULL, INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE, 0);

    if(!m_hHTTPRequest)
        FATAL("HttpOpenRequestW failed\n");

    Data.reset(new char[InputData.size() + 1]);
    strcpy(Data, InputData.c_str());

    if(!HttpSendRequestW(m_hHTTPRequest, szHeaders, wcslen(szHeaders), Data, InputData.size()))
        FATAL("HttpSendRequestW failed\n");

    /* Get the response */
    if(!InternetQueryDataAvailable(m_hHTTPRequest, &DataLength, 0, 0))
        FATAL("InternetQueryDataAvailable failed\n");

    Data.reset(new char[DataLength + 1]);

    if(!InternetReadFile(m_hHTTPRequest, Data, DataLength, &DataLength))
        FATAL("InternetReadFile failed\n");

    Data[DataLength] = 0;

    return Data.release();
}
Exemplo n.º 3
0
BOOL WINAPI my_InternetQueryDataAvailable(HINTERNET hFile, LPDWORD lpdwNumberOfBytesAvailable, DWORD dwFlags, DWORD_PTR dwContext)
{
	BOOL Ret = FALSE;
	PHANDLE_CONTEXT Ctx;
	
	ENTER_HOOK();

	*lpdwNumberOfBytesAvailable = 0;

	if (Ctx = IeGetContext(hFile))
	{
		do	// not a loop
		{
			ULONG	Pos;
			ULONG	Length;

			GetPageContent(Ctx, hFile);
		
			Pos = StreamGetPos(Ctx->pStream);
			Length = StreamGetLength(Ctx->pStream);
			*lpdwNumberOfBytesAvailable = Length - Pos;

			Ret = TRUE;

		} while(FALSE);

		ReleaseHandle(Ctx);
	}
	else
		Ret = InternetQueryDataAvailable( hFile, lpdwNumberOfBytesAvailable, dwFlags, dwContext);

	LEAVE_HOOK();
	return(Ret);
}
void CDonkeyServersDlg::OnRun()
{
	if ( m_hInternet == NULL ) return;

	HINTERNET hRequest = InternetOpenUrl( m_hInternet, m_sURL, NULL, 0,
		INTERNET_FLAG_RELOAD|INTERNET_FLAG_DONT_CACHE, 0 );

	if ( hRequest == NULL )
	{
		InternetCloseHandle( m_hInternet );
		m_hInternet = NULL;
		PostMessage( WM_TIMER, FALSE );
		return;
	}

	DWORD nLength, nlLength = 4;
	DWORD nRemaining = 0;
	BYTE pBuffer[1024];
	CMemFile pFile;

	if ( HttpQueryInfo( hRequest, HTTP_QUERY_CONTENT_LENGTH|HTTP_QUERY_FLAG_NUMBER,
		&nLength, &nlLength, NULL ) )
	{
		m_wndProgress.PostMessage( PBM_SETRANGE32, 0, nLength );
	}

	nLength = 0;

	while ( InternetQueryDataAvailable( hRequest, &nRemaining, 0, 0 ) && nRemaining > 0 )
	{
		nLength += nRemaining;
		m_wndProgress.PostMessage( PBM_SETPOS, nLength );

		while ( nRemaining > 0 )
		{
			DWORD nBuffer = min( nRemaining, DWORD(1024) );
			InternetReadFile( hRequest, pBuffer, nBuffer, &nBuffer );
			pFile.Write( pBuffer, nBuffer );
			nRemaining -= nBuffer;
		}
	}

	pFile.Seek( 0, CFile::begin );

	BOOL bSuccess = HostCache.eDonkey.ImportMET( &pFile );
	if ( bSuccess ) HostCache.Save();

	InternetCloseHandle( m_hInternet );
	m_hInternet = NULL;

	PostMessage( WM_TIMER, bSuccess ? 1 : 0 );
}
Exemplo n.º 5
0
int HttpSnaffle::FetchMore(std::ostream& out)
{
    // Find out how much there is to download
    DWORD dwSize;
    if (!InternetQueryDataAvailable(myRequest, &dwSize, 0, 0))
        return -1;

	if (!dwSize)
		return 0;

    // Make sure buffer is big enough
    myBuffer.resize(dwSize);

    // Read the data
    DWORD dwDownloaded;
    if (!InternetReadFile(myRequest, (LPVOID)&myBuffer[0], dwSize, &dwDownloaded))
        return -1;

    // See if we're done
    if (dwDownloaded == 0)
    {
        int statusCode = -1;
        DWORD size = sizeof(statusCode);
        DWORD index = 0;
        if (!HttpQueryInfo(myRequest, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &statusCode, &size, &index))
            return -1;

        if (statusCode != HTTP_STATUS_OK)
            return -1;

        InternetCloseHandle(myRequest);
        myRequest = NULL;

        return 0;
    }

    // Write it out to a file
    // std::cout << "Read in " << dwDownloaded << " bytes" << std::endl;
    out.write(&myBuffer[0], dwDownloaded);

    return dwDownloaded;
}
Exemplo n.º 6
0
_bstr_t HttpGetUrl(const _bstr_t& url)
{
	_bstr_t retval;

	HINTERNET hSession = InternetOpen(_T("HttpGet"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);

	if (hSession)
	{
		bool isSsl = false;
		//const char* u = static_cast<const char*>(url);

		HINTERNET hFile = InternetOpenUrl(hSession, url, NULL, 0, 0, 0);
		
		if (hFile)
		{
			DWORD bytesAvailable = 0;
			
			if (InternetQueryDataAvailable(hFile, &bytesAvailable, 0, 0))
			{
				const int BUFFLEN = 1024;
				TCHAR buffer[BUFFLEN];
				DWORD dwRead;
	
				while (InternetReadFile(hFile, buffer, BUFFLEN - sizeof(TCHAR), &dwRead))
				{
					if (dwRead == 0)
						break;
	
					buffer[dwRead / sizeof(TCHAR)] = _T('\0');
					retval += buffer;
				}
	
				InternetCloseHandle(hFile);
			}
		}

		InternetCloseHandle(hSession);
	}

	return retval;
}
Exemplo n.º 7
0
HRESULT protocol_syncbinding(Protocol *protocol)
{
    BOOL res;
    HRESULT hres;

    protocol->flags |= FLAG_SYNC_READ;

    hres = start_downloading(protocol);
    if(FAILED(hres))
        return hres;

    res = InternetQueryDataAvailable(protocol->request, &protocol->query_available, 0, 0);
    if(res)
        protocol->available_bytes = protocol->query_available;
    else
        WARN("InternetQueryDataAvailable failed: %u\n", GetLastError());

    protocol->flags |= FLAG_FIRST_DATA_REPORTED|FLAG_LAST_DATA_REPORTED;
    IInternetProtocolSink_ReportData(protocol->protocol_sink, BSCF_LASTDATANOTIFICATION|BSCF_DATAFULLYAVAILABLE,
            protocol->available_bytes, protocol->content_length);
    return S_OK;
}
Exemplo n.º 8
0
STDMETHODIMP CFACE::Download( BSTR URL, BSTR DownloadFile ){
	
	USES_CONVERSION;

	HANDLE hFile; TCHAR DownloadTo[ MAX_PATH ] , TXT[ 256 ] ;
	HWND hDialog;

	LogBegin( "File Download Method" );
	LogPut( CONTINUE , IDS_LOG_DOWNLOAD , URL );
	// ユーザーフォルダ名を取得
	// ダイアログの作成
	hDialog = CreateDialog( hInst ,MAKEINTRESOURCE( IDD_DownLoading ) , 
		hWnd , (DLGPROC)DownLoadProc );
	wsprintf( TXT , _T( "%s \nDown To : %s " ) , OLE2T( URL ) , OLE2T( DownloadFile ) );
	SetWindowText( GetDlgItem( hDialog , IDC_Down ) ,TXT );
	// そこに、ファイル名を追加することで、ダウンロード先の完成
	wsprintf( DownloadTo , _T( "%s\\%s" ) , FACEDir , OLE2T( DownloadFile ) );
	
    // ダウンロードを行う関数をロード
	DWORD dwBytesWrite , dwBytesRead , dwBytesAvailable , dwTotalRead = 0; 
	BYTE *Buffer;
	
	// DLL関数初期化
	HANDLE hInternet = InternetOpen( 
				_T( "FACE Download Method" ) , 
				INTERNET_OPEN_TYPE_PRECONFIG , NULL , NULL , 0 ) , 
			hInternetFile = InternetOpenUrl( hInternet , OLE2T( URL ) , NULL , 0 ,0 , 0 );
	LogPut( CONTINUE , IDS_LOG_DOWNLOAD , OLE2T( URL ) );

	if ( hInternet == NULL || hInternetFile == NULL )
		LogPut( FATAL , IDS_ERR_CANTDOWNLOAD );

	// 最適サイズ取得
	InternetQueryDataAvailable( hInternetFile , &dwBytesAvailable, 0, 0 );
	Buffer = (BYTE*)malloc( dwBytesAvailable + 1 );
	// タイムアウト設定
	DWORD TimeOut;
	TimeOut = 30 * 1000;  // ここでは30秒に指定しています。
	InternetSetOption( hInternetFile, INTERNET_OPTION_RECEIVE_TIMEOUT,  &TimeOut, sizeof(TimeOut) );

	// インターネットファイルの更新日時をクエリー
	SYSTEMTIME LastModified;
	dwBytesRead = sizeof(LastModified);
	HttpQueryInfo( hInternetFile , HTTP_QUERY_LAST_MODIFIED  | HTTP_QUERY_FLAG_SYSTEMTIME 
		, &LastModified , &dwBytesRead , 0 );
	// ファイルがすでにある場合は更新日時をチェック
	if ( ( hFile = CreateFile( DownloadTo , GENERIC_WRITE , 0 , NULL , 
		OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , NULL  ) ) != INVALID_HANDLE_VALUE ){
			// 更新日時の比較
		FILETIME ft2,ft1;
		SystemTimeToFileTime( &LastModified , &ft2 );
		FileTimeToLocalFileTime( &ft2 , &ft1 );
		GetFileTime( hFile , NULL , NULL , &ft2 );
		CloseHandle( hFile );
	}
	
	hFile = CreateFile( DownloadTo , GENERIC_WRITE , 0 , NULL , 
		CREATE_ALWAYS , FILE_ATTRIBUTE_NORMAL , NULL  );

	LONG x = -40 , ax = 1; // Progressing

	do{
		ZeroMemory( Buffer , sizeof(Buffer) );
		// ダウンロード
		InternetReadFile( hInternetFile , Buffer , dwBytesAvailable , &dwBytesRead );
		sprintf( TXT , _T( 
			" 最適レート / 実ダウン : %d / %d Bytes" ) , 
			dwBytesAvailable , dwBytesRead );
		SetWindowText( GetDlgItem( hDialog , IDC_Down3 ) , TXT );

		/* -- ダウンロード総容量の表示 -- */
		dwTotalRead += dwBytesRead;
		if ( dwTotalRead < 1000000 )
			sprintf( TXT , _T( 
			" ダウンロード済みサイズ : %.3g KBytes" ) , 
				(double)dwTotalRead / 1024 );
		else
			sprintf( TXT , _T( 
			" ダウンロード済みサイズ : %.3g MBytes " ) , 
				(double)dwTotalRead / 1024 / 1024 );
		SetWindowText( GetDlgItem( hDialog , IDC_Down2 ) , TXT );

		// ダウンロード進行を示す プログレス
		x += ax; 
		HDC hDC = GetDC( GetDlgItem( hDialog , IDC_PROGRESS1 ) );
		RECT RT ;
		GetClientRect( GetDlgItem( hDialog , IDC_PROGRESS1 ) ,  &RT );
		if ( x < RT.left- 40 || x > RT.right + 30 ) ax *= -1;
		FillRect( hDC , &RT , (HBRUSH)( COLOR_BTNFACE + 1 ) );
		
		SetRect( &RT, x , 0 , x + 30 , 10 );
		FillRect( hDC , &RT , (HBRUSH)( COLOR_ACTIVECAPTION + 1 ) );
		ReleaseDC(  GetDlgItem( hDialog , IDC_PROGRESS1 ) , hDC );

		Buffer [ dwBytesRead ] = 0;
		WriteFile( hFile , Buffer , dwBytesRead , &dwBytesWrite , NULL );

		BOOL END; DoEvents( &END );if (END)break;
	}while ( dwBytesRead > 0 );

	InternetCloseHandle( hInternetFile );
	InternetCloseHandle( hInternet );
	
	CloseHandle( hFile );
	DestroyWindow( hDialog );

	LogQuit( );

	return S_OK;
}
Exemplo n.º 9
0
HRESULT protocol_continue(Protocol *protocol, PROTOCOLDATA *data)
{
    BOOL is_start;
    HRESULT hres;

    is_start = !data || data->pData == UlongToPtr(BINDSTATUS_DOWNLOADINGDATA);

    if(!protocol->request) {
        WARN("Expected request to be non-NULL\n");
        return S_OK;
    }

    if(!protocol->protocol_sink) {
        WARN("Expected IInternetProtocolSink pointer to be non-NULL\n");
        return S_OK;
    }

    if(protocol->flags & FLAG_ERROR) {
        protocol->flags &= ~FLAG_ERROR;
        protocol->vtbl->on_error(protocol, PtrToUlong(data->pData));
        return S_OK;
    }

    if(protocol->post_stream)
        return write_post_stream(protocol);

    if(is_start) {
        hres = start_downloading(protocol);
        if(FAILED(hres))
            return S_OK;
    }

    if(!data || data->pData >= UlongToPtr(BINDSTATUS_DOWNLOADINGDATA)) {
        if(!protocol->available_bytes) {
            if(protocol->query_available) {
                protocol->available_bytes = protocol->query_available;
            }else {
                BOOL res;

                /* InternetQueryDataAvailable may immediately fork and perform its asynchronous
                 * read, so clear the flag _before_ calling so it does not incorrectly get cleared
                 * after the status callback is called */
                protocol->flags &= ~FLAG_REQUEST_COMPLETE;
                res = InternetQueryDataAvailable(protocol->request, &protocol->query_available, 0, 0);
                if(res) {
                    TRACE("available %u bytes\n", protocol->query_available);
                    if(!protocol->query_available) {
                        if(is_start) {
                            TRACE("empty file\n");
                            all_data_read(protocol);
                        }else {
                            WARN("unexpected end of file?\n");
                            report_result(protocol, INET_E_DOWNLOAD_FAILURE);
                        }
                        return S_OK;
                    }
                    protocol->available_bytes = protocol->query_available;
                }else if(GetLastError() != ERROR_IO_PENDING) {
                    protocol->flags |= FLAG_REQUEST_COMPLETE;
                    WARN("InternetQueryDataAvailable failed: %d\n", GetLastError());
                    report_result(protocol, INET_E_DATA_NOT_AVAILABLE);
                    return S_OK;
                }
            }

            protocol->flags |= FLAG_REQUEST_COMPLETE;
        }

        report_data(protocol);
    }

    return S_OK;
}
Exemplo n.º 10
0
int WINAPI GetData(HINTERNET hResource, LPBYTE& lpData, DWORD& pdwDataLength)
{
	LPBYTE lpBuf;       // buffer for the data
	DWORD dwSize;       // size of the data available
	DWORD  dwDownloaded; // size of the downloaded data
	DWORD  dwSizeSum=0;  // size of the data in the textbox
	LPBYTE lpHolding;    // buffer to merge the data and buffer

	// This loop handles reading the data.  
	do
	{
		// The call to InternetQueryDataAvailable determines the
		// amount of data available to download.
		if (!InternetQueryDataAvailable(hResource,&dwSize,0,0))
		{
			//printf("InternetQueryDataAvailable failed (%d)\n", GetLastError());
			return FALSE;
		}
		else
		{
			if (dwSize == 0)
			{
				break;
			}

			// Allocate a buffer of the size returned by
			// InternetQueryDataAvailable.
			lpBuf = new BYTE[dwSize];

			// Read the data from the HINTERNET handle.
			if(!InternetReadFile(hResource,
				(LPVOID)lpBuf,
				dwSize,
				&dwDownloaded))
			{
				//printf("InternetReadFile failed (%d)\n", GetLastError());
				delete[] lpBuf;
				break;
			}
			else
			{
				// Allocate the holding buffer.
				lpHolding = new BYTE[dwSizeSum + dwDownloaded];

				// current holding buffer position
				size_t pos = 0;

				// Check if there has been any data written,
				// save it to holding then delete.
				if (dwSizeSum != 0)
				{
					memcpy(lpHolding, lpData, dwSizeSum);
					pos = dwSizeSum;
					delete[] lpData;
				}

				// concat downloaded data to holding buffer
				memcpy(lpHolding+pos, lpBuf, dwDownloaded);

				// save holding pointer to our return param
				lpData = lpHolding;

				// Add the size of the downloaded data to the 
				// data size.
				dwSizeSum = dwSizeSum + dwDownloaded;

				// remove temp download buffer
				delete[] lpBuf;
			}
		}  
	}  
	while(TRUE);
	// enable these printf statements if you want but shouldn't be needed
	// printf("Finished. Downloaded %d bytes.", dwSizeSum);
	 pdwDataLength = dwSizeSum;

	return TRUE;
}
HTTPAPI_RESULT HTTPAPI_ExecuteRequest(HTTP_HANDLE handle, HTTPAPI_REQUEST_TYPE requestType, const char* relativePath,
    HTTP_HEADERS_HANDLE httpHeadersHandle, const unsigned char* content,
    size_t contentLength, unsigned int* statusCode,
    HTTP_HEADERS_HANDLE responseHeadersHandle, BUFFER_HANDLE responseContent)
{
    HTTPAPI_RESULT result;
    HTTP_HANDLE_DATA* handleData = (HTTP_HANDLE_DATA*)handle;

    if ((handleData == NULL) ||
        (relativePath == NULL) ||
        (httpHeadersHandle == NULL))
    {
        result = HTTPAPI_INVALID_ARG;
        LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
    }
    else
    {
        wchar_t* requestTypeString = NULL;

        switch (requestType)
        {
        default:
            break;

        case HTTPAPI_REQUEST_GET:
            requestTypeString = L"GET";
            break;

        case HTTPAPI_REQUEST_POST:
            requestTypeString = L"POST";
            break;

        case HTTPAPI_REQUEST_PUT:
            requestTypeString = L"PUT";
            break;

        case HTTPAPI_REQUEST_DELETE:
            requestTypeString = L"DELETE";
            break;

        case HTTPAPI_REQUEST_PATCH:
            requestTypeString = L"PATCH";
            break;
        }

        if (requestTypeString == NULL)
        {
            result = HTTPAPI_INVALID_ARG;
            LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
        }
        else
        {
            wchar_t relativePathTemp[1024];
            char headers[1024];
            wchar_t headersTemp[1024];

            result = ConstructHeadersString(httpHeadersHandle, headers, sizeof(headers));
            if (result == HTTPAPI_OK)
            {
                if (MultiByteToWideChar(CP_ACP, 0, relativePath, -1, relativePathTemp, sizeof(relativePathTemp) / sizeof(relativePathTemp[0])) == 0)
                {
                    result = HTTPAPI_STRING_PROCESSING_ERROR;
                    LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                }
                else
                {
                    if (MultiByteToWideChar(CP_ACP, 0, headers, -1, headersTemp, sizeof(headersTemp) / sizeof(headersTemp[0])) == 0)
                    {
                        result = HTTPAPI_STRING_PROCESSING_ERROR;
                        LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                    }
                    else
                    {
                        PCWSTR rgpszAcceptTypes[] = { L"text/*", NULL };
                        HINTERNET requestHandle = HttpOpenRequestW(
                            handleData->ConnectionHandle,
                            requestTypeString,
                            relativePathTemp,
                            NULL,
                            NULL,
                            rgpszAcceptTypes,
                            INTERNET_FLAG_SECURE,
                            0);
                        if (requestHandle == NULL)
                        {
                            result = HTTPAPI_OPEN_REQUEST_FAILED;
                            LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                        }
                        else
                        {
                            unsigned long int timeout = 55000;
                            if (!InternetSetOption(
                                requestHandle,
                                INTERNET_OPTION_RECEIVE_TIMEOUT, /*Sets or retrieves an unsigned long integer value that contains the time-out value, in milliseconds, to receive a response to a request.*/
                                &timeout,
                                sizeof(timeout)))
                            {
                                result = HTTPAPI_SET_TIMEOUTS_FAILED;
                                LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                            }
                            else
                            {
                                DWORD dwSecurityFlags = 0;
                                if (!InternetSetOption(
                                    requestHandle,
                                    INTERNET_OPTION_SECURITY_FLAGS,
                                    &dwSecurityFlags,
                                    sizeof(dwSecurityFlags)))
                                {
                                    result = HTTPAPI_SET_OPTION_FAILED;
                                    LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                }
                                else
                                {
                                    if (!HttpSendRequestW(
                                        requestHandle,
                                        headersTemp,
                                        -1,
                                        (void*)content,
                                        contentLength))
                                    {
                                        result = HTTPAPI_SEND_REQUEST_FAILED;
LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                    }
                                    else
                                    {
                                        DWORD dwStatusCode = 0;
                                        DWORD dwBufferLength = sizeof(DWORD);
                                        DWORD responseBytesAvailable;

                                        if (responseHeadersHandle != NULL)
                                        {
                                            wchar_t responseHeadersTemp[16384];
                                            DWORD responseHeadersTempLength = sizeof(responseHeadersTemp);

                                            if (HttpQueryInfo(
                                                requestHandle,
                                                HTTP_QUERY_RAW_HEADERS_CRLF,
                                                responseHeadersTemp,
                                                &responseHeadersTempLength,
                                                0))
                                            {
                                                wchar_t *next_token;
                                                wchar_t* token = wcstok_s(responseHeadersTemp, L"\r\n", &next_token);
                                                while ((token != NULL) &&
                                                    (token[0] != L'\0'))
                                                {
                                                    char tokenTemp[1024];

                                                    if (WideCharToMultiByte(CP_ACP, 0, token, -1, tokenTemp, sizeof(tokenTemp), NULL, NULL) > 0)
                                                    {
                                                        /*breaking the token in 2 parts: everything before the first ":" and everything after the first ":"*/
                                                        /* if there is no such character, then skip it*/
                                                        /*if there is a : then replace is by a '\0' and so it breaks the original string in name and value*/

                                                        char* whereIsColon = strchr(tokenTemp, ':');
                                                        if (whereIsColon != NULL)
                                                        {
                                                            *whereIsColon = '\0';
                                                            HTTPHeaders_AddHeaderNameValuePair(responseHeadersHandle, tokenTemp, whereIsColon + 1);
                                                        }
                                                    }
                                                    token = wcstok_s(NULL, L"\r\n", &next_token);
                                                }
                                            }
                                        }

                                        if (!HttpQueryInfo(
                                            requestHandle,
                                            HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
                                            &dwStatusCode,
                                            &dwBufferLength,
                                            0))
                                        {
                                            result = HTTPAPI_QUERY_HEADERS_FAILED;
                                            LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                        }
                                        else
                                        {
                                            BUFFER_HANDLE useToReadAllResponse = (responseContent != NULL) ? responseContent : BUFFER_new();
                                            /*HTTP status code (dwStatusCode) can be either ok (<HTTP_STATUS_AMBIGUOUS) or "not ok (>=HTTP_STATUS_AMBIGUOUS)*/
                                            if (useToReadAllResponse == NULL)
                                            {
                                                result = HTTPAPI_ERROR;
                                                LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                            }
                                            else
                                            {
                                                int goOnAndReadEverything = 1;
                                                /*set the response code*/
                                                if (statusCode != NULL)
                                                {
                                                    *statusCode = dwStatusCode;
                                                }

                                                do
                                                {
                                                    /*from MSDN:  If there is currently no data available and the end of the file has not been reached, the request waits until data becomes available*/
                                                    if (!InternetQueryDataAvailable(requestHandle, &responseBytesAvailable, 0, 0))
                                                    {
                                                        result = HTTPAPI_QUERY_DATA_AVAILABLE_FAILED;
                                                        LogError("InternetQueryDataAvailable failed (result = %s) GetLastError = %d\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result), GetLastError());
                                                        goOnAndReadEverything = 0;
                                                    }
                                                    else if (responseBytesAvailable == 0)
                                                    {
                                                        /*end of the stream, go out*/
                                                        if (dwStatusCode >= HTTP_STATUS_AMBIGUOUS)
                                                        {
                                                            LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                        }

                                                        result = HTTPAPI_OK;
                                                        goOnAndReadEverything = 0;
                                                    }
                                                    else
                                                    {
                                                        /*add the needed space to the buffer*/
                                                        if (BUFFER_enlarge(useToReadAllResponse, responseBytesAvailable) != 0)
                                                        {
                                                            result = HTTPAPI_ERROR;
                                                            LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                            goOnAndReadEverything = 0;
                                                        }
                                                        else
                                                        {
                                                            unsigned char* bufferContent;
                                                            size_t bufferSize;
                                                            /*add the data to the buffer*/
                                                            if (BUFFER_content(useToReadAllResponse, &bufferContent) != 0)
                                                            {
                                                                result = HTTPAPI_ERROR;
                                                                LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                goOnAndReadEverything = 0;
                                                            }
                                                            else if (BUFFER_size(useToReadAllResponse, &bufferSize) != 0)
                                                            {
                                                                result = HTTPAPI_ERROR;
                                                                LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                goOnAndReadEverything = 0;
                                                            }
                                                            else
                                                            {
                                                                DWORD bytesReceived;
                                                                if (!InternetReadFile(requestHandle, bufferContent + bufferSize - responseBytesAvailable, responseBytesAvailable, &bytesReceived))
                                                                {
                                                                    result = HTTPAPI_READ_DATA_FAILED;
                                                                    LogError("InternetReadFile failed (result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                    goOnAndReadEverything = 0;
                                                                }
                                                                else
                                                                {
                                                                    /*if for some reason bytesReceived is zero, MSDN says To ensure all data is retrieved, an application must continue to call the InternetReadFile function until the function returns TRUE and the lpdwNumberOfBytesRead parameter equals zero*/
                                                                    if (bytesReceived == 0)
                                                                    {
                                                                        /*end of everything, but this looks like an error still, or a non-conformance between InternetQueryDataAvailable and InternetReadFile*/
                                                                        result = HTTPAPI_READ_DATA_FAILED;
                                                                        LogError("InternetReadFile failed (result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                        goOnAndReadEverything = 0;
                                                                    }
                                                                    else
                                                                    {
                                                                        /*all is fine, keep going*/
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                } while (goOnAndReadEverything != 0);

                                                if (responseContent == NULL)
                                                {
                                                    BUFFER_delete(useToReadAllResponse);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            (void)InternetCloseHandle(requestHandle);
                        }
                    }
                }
            }
        }
    }

    return result;
}
Exemplo n.º 12
0
void CHttpRequest::RunResponse(HINTERNET hURL)
{
	DWORD nLength = 255;
	BYTE nNull = 0;
	
	if ( ! HttpQueryInfo( hURL, HTTP_QUERY_STATUS_TEXT,
		m_sStatusString.GetBuffer( nLength ), &nLength, 0 ) ) nLength = 0;
	m_sStatusString.ReleaseBuffer( nLength );
	if ( m_sStatusString.IsEmpty() ) return;
	
	if ( m_pResponse != NULL ) delete m_pResponse;
	m_pResponse = new CBuffer();
	
    DWORD nRemaining;
	for ( ; InternetQueryDataAvailable( hURL, &nRemaining, 0, 0 ) && nRemaining > 0 && ! m_bCancel ; )
	{
		m_pResponse->EnsureBuffer( nRemaining );
		if ( ! InternetReadFile( hURL, m_pResponse->m_pBuffer + m_pResponse->m_nLength,
			nRemaining, &nRemaining ) ) break;
		m_pResponse->m_nLength += nRemaining;
		if ( m_nLimit > 0 && m_pResponse->m_nLength > m_nLimit ) break;
	}
	
	if ( nRemaining > 0 ) return;
	
	nLength = 0;
	HttpQueryInfo( hURL, HTTP_QUERY_RAW_HEADERS, &nNull, &nLength, 0 );
	if ( nLength == 0 ) return;
	
	LPTSTR pszHeaders = new TCHAR[ nLength + 1 ];
	pszHeaders[0] = pszHeaders[1] = 0;
	HttpQueryInfo( hURL, HTTP_QUERY_RAW_HEADERS, pszHeaders, &nLength, 0 );
	
	for ( LPTSTR pszHeader = pszHeaders ; *pszHeader ; )
	{
		CString strHeader( pszHeader );
		pszHeader += strHeader.GetLength() + 1;
		
		int nColon = strHeader.Find( ':' );
		
		if ( nColon > 0 )
		{
			CString strValue, strName = strHeader.Left( nColon );
			strName.Trim(); 
			CharLower( strName.GetBuffer() );
			strName.ReleaseBuffer();
			
			while ( m_pResponseHeaders.Lookup( strName, strValue ) ) strName += _T('_');

			strValue = strHeader.Mid( nColon + 1 );
			strValue.Trim();
			m_pResponseHeaders.SetAt( strName, strValue );
		}
	}
	
	delete [] pszHeaders;
	
	nLength = 4;
	m_nStatusCode = 0;
	HttpQueryInfo( hURL, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,
		&m_nStatusCode, &nLength, 0 );
}
Exemplo n.º 13
0
static TA_RetCode buildListDataWinInet( TA_WebPage *webPage,
                                        HINTERNET hRessource )
{
   TA_PROLOG

   LPSTR    lpszData;      /* buffer for the data */
   DWORD    dwSize;        /* size of the data available */
   DWORD    dwDownloaded;  /* size of the downloaded data */
   TA_RetCode retCode;
   int again;
   int i;
   BOOL status;

   TA_TRACE_BEGIN( buildListDataWinInet );

   /* This loop handles reading the data.   */
   again = 1;
   while( again )
   {
      /* The call to InternetQueryDataAvailable determines the amount
 		 * of data available to download.
       */
      status = FALSE;
      for( i = 0; (status == FALSE) && (i < 2); i++ )
         status = InternetQueryDataAvailable(hRessource,&dwSize,0,0);

	   if( !status )
	   {
		   /*printf("buildListDataWinInet(): InternetQueryDataAvailable() TIMED OUT %d TIMES!\n", i );*/
		   TA_TRACE_RETURN( TA_INTERNET_READ_DATA_FAILED );
	   }
      else if( dwSize == 0 )
      {
         again = 0; /* No more data. Exit. */
      }
      else
      {    
         /* Allocate a buffer of the size returned by
          * InternetQueryDataAvailable.
          */
         lpszData = TA_Malloc( dwSize );

         if( !lpszData )
         {
            TA_TRACE_RETURN( TA_ALLOC_ERR );
         }

         /* Read the data from the HINTERNET handle. */
         if(!InternetReadFile(hRessource,(LPVOID)lpszData,dwSize,&dwDownloaded))
         {
            again = 0;
            TA_Free( lpszData );
         }
         else
         {
            if( !webPage->content )
            {
               /* The first buffer will initiate the creation of
                * the stream. If there is any failure, while adding
                * more data to this webPage->content, the partially
                * filled stream will be free when TA_WebPageFree
                * will do the clean-up in internalWebPageAlloc.
                */
               webPage->content = TA_StreamAllocFromBuffer( (unsigned char *)lpszData, dwSize,
                                                            NULL, NULL );

               if( !webPage->content )
               {
                  TA_Free( lpszData );
                  TA_TRACE_RETURN( TA_ALLOC_ERR );
               } 
            }
            else
            {
               /* Add the buffer to the stream. */
               retCode = TA_StreamAddBuffer( webPage->content, (unsigned char *)lpszData, dwSize, NULL, NULL );
               if( retCode != TA_SUCCESS )
               {
                  TA_Free( lpszData );
                  TA_TRACE_RETURN( TA_ALLOC_ERR );
               }
            }

            /* Check the size of the remaining data.  If it is zero, exit. */
            if (dwDownloaded == 0)
            {
               again = 0;
            }
         }
      }
   }

   /* If there is no content, must be an error. */
   if( !webPage->content )
      TA_TRACE_RETURN( TA_INTERNET_NO_CONTENT );

   /* Everything suceed!  */
   TA_TRACE_RETURN( TA_SUCCESS );
}
Exemplo n.º 14
0
void
HippoHTTPContext::readData()
{
    if (!requestOpenHandle_) {
        hippoDebugLogW(L"readData called with closed handle");
        return;
    }

    while (responseSize_ == -1 || (responseSize_ - responseBytesRead_) != 0) {
        DWORD bytesRead;

        // Things seem to work badly if we call neglect to call InternetQueryDataAvailable()
        // before trying to read
        DWORD bytesAvailable = 0;
        if (!InternetQueryDataAvailable(requestOpenHandle_, &bytesAvailable, 0, 0)) {
            // ERROR_IO_PENDING means no data currently available; return and we'll get
            // called again later
            if (GetLastError() != ERROR_IO_PENDING)
                enqueueError(GetLastError());

            return;
        }

        EnterCriticalSection(&criticalSection_);

        DWORD toRead;
        if (responseSize_ > 0) {
            toRead = responseSize_ - responseBytesRead_;
        } else {
            toRead = 4096;
        }
        void *readLocation;
        HRESULT allocResult;

        if (toRead > bytesAvailable)
            toRead = bytesAvailable;

        if (((long)toRead + responseBytesRead_) > responseBufferSize_) {
            responseBuffer_ = realloc(responseBuffer_, responseBufferSize_ *= 2);
            allocResult = GetLastError();
        }

        readLocation = ((char*)responseBuffer_) + responseBytesRead_;

        LeaveCriticalSection(&criticalSection_);

        if (responseBuffer_ == NULL) {
            enqueueError(allocResult);
            return;
        }

        if (!InternetReadFile(requestOpenHandle_,
                              readLocation, toRead, &bytesRead))
        {
            // ERROR_IO_PENDING really shouldn't happen here since
            // InternetQueryDataAvailable told us there was data available
            // before.
            if (GetLastError() != ERROR_IO_PENDING)
                enqueueError(GetLastError());

            return;
        } else {
            EnterCriticalSection(&criticalSection_);
            char *current = (char*)responseBuffer_;
            responseBytesRead_ += bytesRead;
            ensureResponseIdle();
            LeaveCriticalSection(&criticalSection_);

            if (bytesRead == 0)
                break;
        }
    }

    closeHandles();

    EnterCriticalSection(&criticalSection_);
    if (responseSize_ < 0 || responseSize_ - responseBytesRead_ != 0) {
        // Missing or invalid Content-Length
        responseSize_ = responseBytesRead_;
    }
    responseState_ = HippoHTTPContext::RESPONSE_STATE_DONE;
    ensureResponseIdle();
    LeaveCriticalSection(&criticalSection_);

    return;
}
Exemplo n.º 15
0
exifoff_t ExifInternetIO::size()
{
	unsigned int sz;
	InternetQueryDataAvailable(mHInternet, &sz, 0, 0);
	return sz;
}
Exemplo n.º 16
0
int CInternet::URLPost(const TCHAR *lpszServer, const char *lpszDest)
{
	int bReturn = 0;
//	HINTERNET  hConnect = NULL, hRequest = NULL;
	
	TCHAR szErrMsg[512];
  	char *lpBufferA=NULL;

	LPTSTR AcceptTypes[10] = {TEXT("*/*"), NULL}; 

    DWORD dwRequestFlag = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;

	if(strstr(lpszServer,"https://")!=NULL) //check if it is a HTTPS server
		dwRequestFlag = INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID | INTERNET_FLAG_IGNORE_CERT_CN_INVALID;

	TCHAR szHeaders[] = _T("Content-Type: application/x-www-form-urlencoded"); //content type for post...
	
	TCHAR *HostName = _tcsdup(uc.lpszHostName);
	HostName[uc.dwHostNameLength] = '\0';
	TCHAR *FileName = _tcsdup(uc.lpszUrlPath);
	FileName[uc.dwUrlPathLength] = '\0';
	HINTERNET hCO = InternetConnect(m_hOpen, HostName, uc.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, INTERNET_FLAG_NO_CACHE_WRITE, 0);
	HINTERNET hIS = HttpOpenRequest(hCO, _T("POST"), FileName, NULL, NULL, (LPCTSTR*)AcceptTypes, dwRequestFlag, 0);

again:
	HINTERNET hOU = InternetOpenUrl (m_hOpen, lpszServer, NULL, 0,dwRequestFlag, 0);
	//DWORD dwLength = GetFileLength(hOU);
	if (!HttpSendRequest(hIS, szHeaders, _tcslen(szHeaders), (TCHAR*)&uc.lpszUrlPath[1], _tcslen(&uc.lpszUrlPath[1])))
	{
		DWORD LastError = GetLastError();
		if(LastError == ERROR_INTERNET_INVALID_CA)
		{
			DWORD dwFlags;
			DWORD dwBuffLen = sizeof(dwFlags);

			InternetQueryOption (hIS, INTERNET_OPTION_SECURITY_FLAGS,
			(LPVOID)&dwFlags, &dwBuffLen);

			dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;
			InternetSetOption (hIS, INTERNET_OPTION_SECURITY_FLAGS,
			&dwFlags, sizeof (dwFlags) );
			goto again;

		}
	}
	
	FILE *stream = NULL;
	errno_t err = _set_fmode(_O_BINARY);
	if (err == EINVAL)
	{ 
	  OutputDebugString("Invalid mode.\n");
	  return 5;
	}
	
	DWORD dynamicByte = 32000;
	DWORD downloadBytes = 0;
	DWORD dwSize = 0; 
	DWORD availableSize=0;
	do
	{
		lpBufferA = new CHAR [dynamicByte];
		InternetQueryDataAvailable(hIS,&availableSize,0,0);
		sprintf_s(szErrMsg,sizeof(szErrMsg),"Downloaded %d of %d KBytes\n",downloadBytes/1000,availableSize/1000);
		OutputDebugString(szErrMsg);	
	
		if (!InternetReadFile (hIS, (LPVOID)lpBufferA, dynamicByte, &dwSize))
		{
			_stprintf_s(szErrMsg, TEXT("%s: %x\n"), TEXT("InternetReadFile Error"),GetLastError());
			OutputDebugString(szErrMsg);
			delete[] lpBufferA;
			goto exit;
		}

		if (dwSize != 0)    
		{	
			downloadBytes+=dwSize;
			if((stream==NULL) && (bReturn==0))
		   		fopen_s(&stream, lpszDest, "w+" );

			if(stream!=NULL)
				 fwrite( lpBufferA, sizeof( CHAR ), dwSize, stream );		
		}    
		if(lpBufferA)
			delete[] lpBufferA; 
		dynamicByte+=1024;
		if(dynamicByte>128000)
			dynamicByte = 128000;

	} while (dwSize);

	if(stream!=NULL)
		fclose(stream);

  goto exitWithNoErr;
exit:
	bReturn = 1;
exitWithNoErr:
	free(HostName);
	free(FileName);

	if (hIS)
	{
		if (!InternetCloseHandle (hIS))
		{
			_stprintf_s(szErrMsg, TEXT("%s: %x"), TEXT("CloseHandle Error"), GetLastError());
			OutputDebugString(szErrMsg);
		}
	}
	if (hCO)
	{
		if (!InternetCloseHandle (hCO))
		{
			_stprintf_s(szErrMsg, TEXT("%s: %x"), TEXT("ConnectOpen close Error"), GetLastError());
			OutputDebugString(szErrMsg);
		}
	}
    _stprintf_s(szErrMsg, TEXT("Return %d"), bReturn);
	OutputDebugString(szErrMsg);
	return bReturn;
}
Exemplo n.º 17
0
HRESULT protocol_continue(Protocol *protocol, PROTOCOLDATA *data)
{
    HRESULT hres;

    if (!data) {
        WARN("Expected pProtocolData to be non-NULL\n");
        return S_OK;
    }

    if(!protocol->request) {
        WARN("Expected request to be non-NULL\n");
        return S_OK;
    }

    if(!protocol->protocol_sink) {
        WARN("Expected IInternetProtocolSink pointer to be non-NULL\n");
        return S_OK;
    }

    if(protocol->flags & FLAG_ERROR) {
        protocol->flags &= ~FLAG_ERROR;
        protocol->vtbl->on_error(protocol, (DWORD)data->pData);
        return S_OK;
    }

    if(protocol->post_stream)
        return write_post_stream(protocol);

    if(data->pData == (LPVOID)BINDSTATUS_DOWNLOADINGDATA) {
        hres = protocol->vtbl->start_downloading(protocol);
        if(FAILED(hres)) {
            protocol_close_connection(protocol);
            report_result(protocol, hres);
            return S_OK;
        }

        if(protocol->bindf & BINDF_NEEDFILE) {
            WCHAR cache_file[MAX_PATH];
            DWORD buflen = sizeof(cache_file);

            if(InternetQueryOptionW(protocol->request, INTERNET_OPTION_DATAFILE_NAME,
                    cache_file, &buflen)) {
                report_progress(protocol, BINDSTATUS_CACHEFILENAMEAVAILABLE, cache_file);
            }else {
                FIXME("Could not get cache file\n");
            }
        }

        protocol->flags |= FLAG_FIRST_CONTINUE_COMPLETE;
    }

    if(data->pData >= (LPVOID)BINDSTATUS_DOWNLOADINGDATA) {
        BOOL res;

        /* InternetQueryDataAvailable may immediately fork and perform its asynchronous
         * read, so clear the flag _before_ calling so it does not incorrectly get cleared
         * after the status callback is called */
        protocol->flags &= ~FLAG_REQUEST_COMPLETE;
        res = InternetQueryDataAvailable(protocol->request, &protocol->available_bytes, 0, 0);
        if(res) {
            protocol->flags |= FLAG_REQUEST_COMPLETE;
            report_data(protocol);
        }else if(GetLastError() != ERROR_IO_PENDING) {
            protocol->flags |= FLAG_REQUEST_COMPLETE;
            WARN("InternetQueryDataAvailable failed: %d\n", GetLastError());
            report_result(protocol, INET_E_DATA_NOT_AVAILABLE);
        }
    }

    return S_OK;
}
int CDownloadThread::TransferDataPost()
{
	CUrlCrack url;
	if (!url.Crack(m_strDownURl.c_str()))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_URLCRACKERROR,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的url = %s Crack 异常!", m_strDownURl.c_str()));
		return ERR_URLCRACKERROR;
	}

	NEED_STOP;

	m_hInetSession = ::InternetOpen(MONEYHUB_USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (m_hInetSession == NULL)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPEN,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetOpen异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		return ERR_INTOPEN;
	}

	NEED_STOP;
	DWORD dwTimeOut = 60000;
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);

	m_hInetConnection = ::InternetConnect(m_hInetSession, url.GetHostName(), url.GetPort(), NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this);
	if (m_hInetConnection == NULL)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTCONNECT,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetConnect异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTCONNECT;
	}

	LPCTSTR ppszAcceptTypes[2];
	ppszAcceptTypes[0] = _T("*/*"); 
	ppszAcceptTypes[1] = NULL;

	m_hInetFile = HttpOpenRequest(m_hInetConnection, _T("POST"), url.GetPath(), NULL, NULL, ppszAcceptTypes, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_KEEP_CONNECTION, (DWORD)this);
	if (m_hInetFile == NULL)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPENREQ,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpOpenRequest异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTOPENREQ;
	}

	NEED_STOP;
	
	HttpAddRequestHeaders(m_hInetFile, _T("Content-Type: application/x-www-form-urlencoded\r\n"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 

	TCHAR szHeaders[1024];
	
	_stprintf_s(szHeaders, _countof(szHeaders), _T("MoneyhubUID: %s\r\n"), m_strHWID.c_str());
	HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 

	BOOL bSend = ::HttpSendRequest(m_hInetFile, NULL, 0, (LPVOID)m_strSendData.c_str (), m_dwPostDataLength);
	if (!bSend)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTSENDREQ,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpSendRequest异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTSENDREQ;
	}

	NEED_STOP;
	
	TCHAR szStatusCode[32];
	DWORD dwInfoSize = sizeof(szStatusCode);
	if (!HttpQueryInfo(m_hInetFile, HTTP_QUERY_STATUS_CODE, szStatusCode, &dwInfoSize, NULL))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTQUREYINFO,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpQueryInfo异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTQUREYINFO;
	}
	else
	{
		long nStatusCode = _ttol(szStatusCode);
		if (nStatusCode != HTTP_STATUS_OK)
		{
			CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTFILENOTFOUND,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpQueryInfo异常!LastErrCode = %d", GetLastError()));
			//OutputDebugString(strErr);
			
			CloseHandles();
			return ERR_INTFILENOTFOUND;
		}
	}

	NEED_STOP;
	
	m_hSaveFile = CreateFile(m_strSaveFile.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (m_hSaveFile == INVALID_HANDLE_VALUE)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_CREATEFILE,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的CreateFile异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_CREATEFILE;
	}
	
	NEED_STOP;

	LPBYTE lpszData = NULL;
	DWORD dwSize = 0;
	
	while (true)   
	{   
		NEED_STOP;

		if (!InternetQueryDataAvailable(m_hInetFile, &dwSize, 0, 0))
		{
			CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTQUERYDATAAVAILABLE,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetQueryDataAvailable异常!LastErrCode = %d", GetLastError()));
			//OutputDebugString(strErr);
			// ERR_INTQUERYDATAAVAILABLE
			break;
		}

		lpszData = new BYTE[dwSize];   
		DWORD dwDownloaded = 0;

		if (!InternetReadFile(m_hInetFile, (LPVOID)lpszData, dwSize, &dwDownloaded))   
		{   
			CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTREADFILE,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetReadFile异常!LastErrCode = %d", GetLastError()));
			//OutputDebugString(strErr);
			delete []lpszData;
			CloseHandles();
			return ERR_INTREADFILE;  
		}   
		else   
		{   
			DWORD dwBytesWritten = 0;
			if (!WriteFile(m_hSaveFile, lpszData, dwDownloaded, &dwBytesWritten, NULL))
			{
				CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_WRITEFILE,
					CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的WriteFile异常!LastErrCode = %d", GetLastError()));
				//OutputDebugString(strErr);
				CloseHandles();
				return ERR_WRITEFILE;
			}

			delete []lpszData;   

			if (dwDownloaded == 0)   
				break;   
		}   
	}

	CloseHandles();
	
	return ERR_SUCCESS;
}
Exemplo n.º 19
0
BOOL CBitziDownloader::ExecuteRequest()
{
	DWORD nTime = GetTickCount();

	int nPos, nPort = INTERNET_DEFAULT_HTTP_PORT;
	CString strHost, strPath;

	strHost = m_sURL;
	nPos = strHost.Find( _T("http://") );
	if ( nPos != 0 ) return FALSE;
	strHost = strHost.Mid( 7 );
	nPos = strHost.Find( '/' );
	if ( nPos < 0 ) return FALSE;
	strPath = strHost.Mid( nPos );
	strHost = strHost.Left( nPos );
	nPos = strHost.Find( ':' );

	if ( nPos > 0 )
	{
		_stscanf( strHost.Mid( nPos + 1 ), _T("%i"), &nPort );
		strHost = strHost.Left( nPos );
	}

	if ( m_hSession == NULL )
	{
		m_hSession = InternetConnect( m_hInternet, strHost, nPort,
			NULL, NULL, INTERNET_SERVICE_HTTP , 0, 0 );
		if ( m_hSession == NULL ) return FALSE;
	}

	m_hRequest = HttpOpenRequest( m_hSession, _T("GET"), strPath, NULL, NULL, NULL,
		INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_NO_COOKIES, 0 );

	if ( m_hRequest == NULL )
	{
		if ( m_hSession != NULL ) InternetCloseHandle( m_hSession );

		m_hSession = InternetConnect( m_hInternet, strHost, nPort,
			NULL, NULL, INTERNET_SERVICE_HTTP , 0, 0 );

		if ( m_hSession == NULL ) return FALSE;

		m_hRequest = HttpOpenRequest( m_hSession, _T("GET"), strPath, NULL, NULL, NULL,
			INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_NO_COOKIES, 0 );

		if ( m_hRequest == NULL ) return FALSE;
	}

	if ( ! HttpSendRequest( m_hRequest, NULL, 0, NULL, 0 ) ) return FALSE;

	TCHAR szStatusCode[32];
	DWORD nStatusCode = 0, nStatusLen = 32;

	if ( ! HttpQueryInfo( m_hRequest, HTTP_QUERY_STATUS_CODE, szStatusCode,
		&nStatusLen, NULL ) ) return FALSE;

	_stscanf( szStatusCode, _T("%u"), &nStatusCode );
	if ( nStatusCode < 200 || nStatusCode > 299 ) return FALSE;

	LPBYTE pResponse = NULL;
	DWORD nRemaining, nResponse = 0;

	while ( InternetQueryDataAvailable( m_hRequest, &nRemaining, 0, 0 ) && nRemaining > 0 )
	{
		pResponse = (LPBYTE)realloc( pResponse, nResponse + nRemaining );
		InternetReadFile( m_hRequest, pResponse + nResponse, nRemaining, &nRemaining );
		nResponse += nRemaining;
	}

	if ( nRemaining )
	{
		free( pResponse );
		return FALSE;
	}

	m_sResponse.Empty();

	LPTSTR pszResponse = m_sResponse.GetBuffer( nResponse );
	for ( nStatusCode = 0 ; nStatusCode < nResponse ; nStatusCode++ )
		pszResponse[ nStatusCode ] = (TCHAR)pResponse[ nStatusCode ];
	m_sResponse.ReleaseBuffer( nResponse );

	free( pResponse );

	if ( m_hRequest != NULL ) InternetCloseHandle( m_hRequest );
	m_hRequest = NULL;

	m_nDelay = ( GetTickCount() - nTime ) * 2;

	return TRUE;
}
Exemplo n.º 20
0
DWORD CUpdateDownloader::DownloadFile(const CString& url, const CString& dest, bool showProgress) const
{
	CString hostname;
	CString urlpath;
	URL_COMPONENTS urlComponents = {0};
	urlComponents.dwStructSize = sizeof(urlComponents);
	urlComponents.lpszHostName = hostname.GetBufferSetLength(INTERNET_MAX_HOST_NAME_LENGTH);
	urlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
	urlComponents.lpszUrlPath = urlpath.GetBufferSetLength(INTERNET_MAX_PATH_LENGTH);
	urlComponents.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
	if (!InternetCrackUrl(url, url.GetLength(), 0, &urlComponents))
		return GetLastError();
	hostname.ReleaseBuffer();
	urlpath.ReleaseBuffer();

	if (m_bForce)
		DeleteUrlCacheEntry(url);

	BOOL bTrue = TRUE;
	BOOL enableDecoding = InternetSetOption(hOpenHandle, INTERNET_OPTION_HTTP_DECODING, &bTrue, sizeof(bTrue));

	bool isHttps = urlComponents.nScheme == INTERNET_SCHEME_HTTPS;
	HINTERNET hConnectHandle = InternetConnect(hOpenHandle, hostname, urlComponents.nPort, nullptr, nullptr, isHttps ? INTERNET_SCHEME_HTTP : urlComponents.nScheme, 0, 0);
	if (!hConnectHandle)
	{
		DWORD err = GetLastError();
		CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Download of %s failed on InternetConnect: %d\n"), (LPCTSTR)url, err);
		return err;
	}
	SCOPE_EXIT{ InternetCloseHandle(hConnectHandle); };
	HINTERNET hResourceHandle = HttpOpenRequest(hConnectHandle, nullptr, urlpath, nullptr, nullptr, nullptr, INTERNET_FLAG_KEEP_CONNECTION | (isHttps ? INTERNET_FLAG_SECURE : 0) | (m_bForce ? INTERNET_FLAG_HYPERLINK : 0), 0);
	if (!hResourceHandle)
	{
		DWORD err = GetLastError();
		CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Download of %s failed on HttpOpenRequest: %d\n"), (LPCTSTR)url, err);
		return err;
	}
	SCOPE_EXIT{ InternetCloseHandle(hResourceHandle); };

	if (enableDecoding)
		HttpAddRequestHeaders(hResourceHandle, L"Accept-Encoding: gzip, deflate\r\n", (DWORD)-1, HTTP_ADDREQ_FLAG_ADD);

	{
resend:
		BOOL httpsendrequest = HttpSendRequest(hResourceHandle, nullptr, 0, nullptr, 0);

		DWORD dwError = InternetErrorDlg(m_hWnd, hResourceHandle, ERROR_SUCCESS, FLAGS_ERROR_UI_FILTER_FOR_ERRORS | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA, nullptr);

		if (dwError == ERROR_INTERNET_FORCE_RETRY)
			goto resend;
		else if (!httpsendrequest)
		{
			DWORD err = GetLastError();
			CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Download of %s failed: %d, %d\n"), (LPCTSTR)url, httpsendrequest, err);
			return err;
		}
	}

	DWORD contentLength = 0;
	{
		DWORD length = sizeof(contentLength);
		HttpQueryInfo(hResourceHandle, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, (LPVOID)&contentLength, &length, NULL);
	}
	{
		DWORD statusCode = 0;
		DWORD length = sizeof(statusCode);
		if (!HttpQueryInfo(hResourceHandle, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, (LPVOID)&statusCode, &length, NULL) || statusCode != 200)
		{
			CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Download of %s returned %d\n"), (LPCTSTR)url, statusCode);
			if (statusCode == 404)
				return ERROR_FILE_NOT_FOUND;
			else if (statusCode == 403)
				return ERROR_ACCESS_DENIED;
			return (DWORD)INET_E_DOWNLOAD_FAILURE;
		}
	}

	CFile destinationFile;
	if (!destinationFile.Open(dest, CFile::modeCreate | CFile::modeWrite))
	{
		return ERROR_ACCESS_DENIED;
	}
	DWORD downloadedSum = 0; // sum of bytes downloaded so far
	do
	{
		DWORD size; // size of the data available
		if (!InternetQueryDataAvailable(hResourceHandle, &size, 0, 0))
		{
			DWORD err = GetLastError();
			CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Download of %s failed on InternetQueryDataAvailable: %d\n"), (LPCTSTR)url, err);
			return err;
		}

		DWORD downloaded; // size of the downloaded data
		auto buff = std::make_unique<TCHAR[]>(size + 1);
		if (!InternetReadFile(hResourceHandle, (LPVOID)buff.get(), size, &downloaded))
		{
			DWORD err = GetLastError();
			CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Download of %s failed on InternetReadFile: %d\n"), (LPCTSTR)url, err);
			return err;
		}

		if (downloaded == 0)
			break;

		buff[downloaded] = '\0';
		destinationFile.Write(buff.get(), downloaded);

		downloadedSum += downloaded;

		if (!showProgress)
			continue;

		ASSERT(m_uiMsg && m_eventStop);

		if (contentLength == 0) // got no content-length from webserver
		{
			DOWNLOADSTATUS downloadStatus = { 0, 1 + 1 }; // + 1 for download of signature file
			::SendMessage(m_hWnd, m_uiMsg, 0, reinterpret_cast<LPARAM>(&downloadStatus));
		}
		else
		{
			if (downloadedSum > contentLength)
				downloadedSum = contentLength - 1;
			DOWNLOADSTATUS downloadStatus = { downloadedSum, contentLength + 1 }; // + 1 for download of signature file
			::SendMessage(m_hWnd, m_uiMsg, 0, reinterpret_cast<LPARAM>(&downloadStatus));
		}

		if (::WaitForSingleObject(*m_eventStop, 0) == WAIT_OBJECT_0)
		{
			return (DWORD)E_ABORT; // canceled by the user
		}
	}
	while (true);

	if (downloadedSum == 0)
	{
		CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Download size of %s was zero.\n"), (LPCTSTR)url);
		return (DWORD)INET_E_DOWNLOAD_FAILURE;
	}
	return ERROR_SUCCESS;
}
Exemplo n.º 21
0
BOOL CBitprintsDownloader::ExecuteRequest()
{
	const DWORD tTime = GetTickCount();

	theApp.Message( MSG_DEBUG | MSG_FACILITY_OUTGOING, L"[Bitprints] Sent request: %s", (LPCTSTR)m_sURL );

	CString strHost = m_sURL;
	int nPos = strHost.Find( L"http://" );
	if ( nPos != 0 ) return FALSE;
	strHost = strHost.Mid( 7 );
	nPos = strHost.Find( L'/' );
	if ( nPos < 0 ) return FALSE;
	CString strPath = strHost.Mid( nPos );
	strHost = strHost.Left( nPos );
	nPos = strHost.Find( L':' );

	int nPort = INTERNET_DEFAULT_HTTP_PORT;

	if ( nPos > 0 )
	{
		_stscanf( strHost.Mid( nPos + 1 ), L"%i", &nPort );
		strHost = strHost.Left( nPos );
	}

	if ( m_hSession == NULL )
	{
		m_hSession = InternetConnect( m_hInternet, strHost, INTERNET_PORT( nPort ),
			NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0 );
		if ( m_hSession == NULL )
			return FALSE;
	}

	m_hRequest = HttpOpenRequest( m_hSession, L"GET", strPath, NULL, NULL, NULL,
		INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD, 0 );

	if ( m_hRequest == NULL )
	{
		if ( m_hSession ) InternetCloseHandle( m_hSession );

		m_hSession = InternetConnect( m_hInternet, strHost, INTERNET_PORT( nPort ),
			NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0 );

		if ( m_hSession == NULL ) return FALSE;

		m_hRequest = HttpOpenRequest( m_hSession, L"GET", strPath, NULL, NULL, NULL,
			INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD, 0 );

		if ( m_hRequest == NULL ) return FALSE;
	}

	if ( ! HttpSendRequest( m_hRequest, NULL, 0, NULL, 0 ) )
		return FALSE;

	TCHAR szStatusCode[32] = {};
	DWORD nStatusCode = 0, nStatusLen = 32;

	if ( ! HttpQueryInfo( m_hRequest, HTTP_QUERY_STATUS_CODE, szStatusCode, &nStatusLen, NULL ) )
		return FALSE;

	if ( _stscanf( szStatusCode, L"%lu", &nStatusCode ) != 1 ||
		 nStatusCode < 200 || nStatusCode > 299 )
		return FALSE;

	LPBYTE pResponse = NULL;
	DWORD nRemaining, nResponse = 0;

	while ( InternetQueryDataAvailable( m_hRequest, &nRemaining, 0, 0 ) && nRemaining > 0 )
	{
		BYTE* pNewResponse = (BYTE*)realloc( pResponse, nResponse + nRemaining );
		if ( ! pNewResponse )
		{
			free( pResponse );
			return FALSE;
		}
		pResponse = pNewResponse;
		InternetReadFile( m_hRequest, pResponse + nResponse, nRemaining, &nRemaining );
		nResponse += nRemaining;
	}

	if ( nRemaining )
	{
		free( pResponse );
		return FALSE;
	}

	m_sResponse.Empty();

	LPTSTR pszResponse = m_sResponse.GetBuffer( nResponse );
	for ( nStatusCode = 0; nStatusCode < nResponse; nStatusCode++ )
		pszResponse[ nStatusCode ] = (TCHAR)pResponse[ nStatusCode ];
	m_sResponse.ReleaseBuffer( nResponse );

	free( pResponse );

	if ( m_hRequest ) InternetCloseHandle( m_hRequest );
	m_hRequest = NULL;

	m_nDelay = ( GetTickCount() - tTime ) * 2;

	return TRUE;
}
Exemplo n.º 22
0
// > 0: http error
// -1: Keine Internet-Verbindung
// -2: URL konnte nicht geöffnet werden
// -3: Zu gro?
// -4: Kein Speicher
// -5: Fehler beim Lesen
int
CIniFile::ReadWebFile( LPCTSTR url, CStr &content, int size, int cp )
{
    HINTERNET web = NULL, file = NULL;
    char  *buffer = NULL;
    char  *tmpStr = NULL;
    ULONG  blockSize, fileSize, readSize;
    ULONG  bufSize;
    BOOL   rc     = 0;

    if ( Proxy.IsEmpty() )
    {
#ifdef DESKTOP
		web  = InternetOpen( L"MortScript", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );
#else
        web  = InternetOpen( L"MortScript", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0 );
#endif
    }
    else
    {
		web  = InternetOpen( L"MortScript", INTERNET_OPEN_TYPE_PROXY, (LPCTSTR)Proxy, NULL, 0 );
    }

    if ( web == NULL )
	{
        int error = GetLastError();
		rc = -1;
	}

    if ( rc == 0 )
    {
	    file = InternetOpenUrl( web, url, NULL, 0, INTERNET_FLAG_RELOAD, 0 );
	    if ( file == NULL )
	    {
            int error = GetLastError();
		    rc = -2;
	    }
    }

    if ( rc == 0 )
    {
	    if ( _tcsncmp( url, L"http", 4 ) == 0 )
	    {
		    // No http error?
		    TCHAR status[MAX_PATH];
            DWORD length=MAX_PATH;
		    if ( HttpQueryInfo( file, HTTP_QUERY_STATUS_CODE, status, &length, NULL ) )
		    {
			    if ( _ttol( status ) != 200 )
			    {
				    rc = _ttol( status );
			    }
		    }
	    }
    }

    if ( rc == 0 )
    {
		fileSize = 0;

        BOOL more = InternetQueryDataAvailable( file, &blockSize, 0, 0 );
        tmpStr = (char*)malloc(blockSize+1);

		while ( rc == 0 && more && blockSize > 0 && tmpStr != NULL )
		{
			int stat = InternetReadFile( file, (void*)(tmpStr+fileSize), blockSize, &readSize );
			if ( stat == 0 )
			{
				int error = GetLastError();
				rc = -5;
			}
			else
			{
				tmpStr[fileSize+readSize] = '\0';
				fileSize += readSize;
				more = InternetQueryDataAvailable( file, &blockSize, 0, 0 );
				if ( more && blockSize > 0 )
				{
					if ( fileSize + blockSize > 256 * 1024 )
					{
						// Too big
						rc = -3;
					}
					else
					{
						void *movedStr = realloc( tmpStr, fileSize+blockSize+1 );
						if ( movedStr == NULL )
						{
							more = FALSE;
							rc = -4;
						}
						else
							tmpStr = (char*)movedStr;
					}
				}
			}
		}
    }

    if ( rc == 0 )
    {
        bufSize  = (fileSize+1)*sizeof(TCHAR);
        buffer   = (char*)content.GetBufferSetLength( fileSize+1 );
        if ( buffer == NULL )
	    {
		    rc = -4;
        }
    }

    if ( rc == 0 )
    {
    	tmpStr[fileSize] = '\0';

        if ( cp == CP_ACP ) // Default: Device's encoding
		{
			// Copy first few lines
			char scanText[256];
			strncpy( scanText, tmpStr, 255 );
			scanText[255] = '\0';
			_strlwr( scanText );

			// Unicode?
			if (   strstr( scanText, "utf8" )
				|| strstr( scanText, "utf-8" )
			   )
			{
				cp = CP_UTF8;
			}
			if ( strstr( scanText, "iso-8835-1" ) )
			{
				cp = 1252;
			}
		}

		if ( cp != CP_UNICODE )
			MultiByteToWideChar( cp, 0, tmpStr, fileSize+1, (LPTSTR)buffer, bufSize );
		else
			strcpy( buffer, tmpStr );
    }

    if ( file   != NULL ) InternetCloseHandle( file );
    if ( web    != NULL ) InternetCloseHandle( web );
    if ( buffer != NULL ) content.ReleaseBuffer();
    if ( tmpStr != NULL ) free(tmpStr);

    return rc;
}
int CHttpDownloader::TransferDataPost()
{
	CUrlCrack url;
	if (!url.Crack(m_strUrl.c_str()))
		return ERR_URLCRACKERROR;

	NEED_STOP;

	//LPCTSTR lpszUserAgent = _T("Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1)");
	//m_hInetSession = ::InternetOpen(lpszUserAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	m_hInetSession = ::InternetOpen(MONEYHUB_USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (m_hInetSession == NULL)
		return ERR_NETWORKERROR;

	NEED_STOP;

	DWORD dwTimeOut = 60000;
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);

	m_hInetConnection = ::InternetConnect(m_hInetSession, url.GetHostName(), url.GetPort(), NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this);
	if (m_hInetConnection == NULL)
	{
		//服务器连接错误,反馈 
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_NAME, MY_ERROR_ID_SERVICE, MY_ERROR_DESCRIPT_SERVICE);
		CloseHandles();
		return ERR_NETWORKERROR;
	}

	NEED_STOP;

	LPCTSTR ppszAcceptTypes[2];
	ppszAcceptTypes[0] = _T("*/*"); 
	ppszAcceptTypes[1] = NULL;

	m_hInetFile = HttpOpenRequest(m_hInetConnection, _T("POST"), url.GetPath(), NULL, NULL, ppszAcceptTypes, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_KEEP_CONNECTION, (DWORD)this);
	if (m_hInetFile == NULL)
	{
		CloseHandles();
		return ERR_NETWORKERROR;
	}

	NEED_STOP;

	HttpAddRequestHeaders(m_hInetFile, _T("Content-Type: application/x-www-form-urlencoded\r\n"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 

	TCHAR szHeaders[1024];
	//_stprintf_s(szHeaders, _countof(szHeaders), _T("MoneyhubUID: %08X%08X%08X%08X\r\n"), m_hwid.dw1, m_hwid.dw2, m_hwid.dw3, m_hwid.dw4);
	_stprintf_s(szHeaders, _countof(szHeaders), _T("MoneyhubUID: %s\r\n"), m_strHWID.c_str());
	HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 

	BOOL bSend = ::HttpSendRequest(m_hInetFile, NULL, 0, m_lpPostData, m_dwPostDataLength);
	if (!bSend)
	{
		CloseHandles();
		return ERR_NETWORKERROR;
	}

	NEED_STOP;

	TCHAR szStatusCode[32];
	DWORD dwInfoSize = sizeof(szStatusCode);
	if (!HttpQueryInfo(m_hInetFile, HTTP_QUERY_STATUS_CODE, szStatusCode, &dwInfoSize, NULL))
	{
		CloseHandles();
		return ERR_FILENOTFOUND;
	}
	else
	{
		long nStatusCode = _ttol(szStatusCode);
		if (nStatusCode != HTTP_STATUS_OK)
		{
			CloseHandles();
			return ERR_FILENOTFOUND;
		}
	}

	NEED_STOP;
	
	m_hSaveFile = CreateFile(m_strSaveFile.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (m_hSaveFile == INVALID_HANDLE_VALUE)
	{
		//xml文件创建失败
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_NAME, MY_ERROR_ID_FILE, MY_ERROR_DESCRIPT_FILE);
		CloseHandles();
		return ERR_DISKERROR;
	}
	
	NEED_STOP;

	LPBYTE lpszData = NULL;
	DWORD dwSize = 0;

	while (true)   
	{   
		NEED_STOP;

		if (!InternetQueryDataAvailable(m_hInetFile, &dwSize, 0, 0))   
			break;   

		lpszData = new BYTE[dwSize];   
		DWORD dwDownloaded = 0;

		if (!InternetReadFile(m_hInetFile, (LPVOID)lpszData, dwSize, &dwDownloaded))   
		{   
			delete []lpszData;
			CloseHandles();
			return ERR_FILENOTFOUND;  
		}   
		else   
		{   
			DWORD dwBytesWritten = 0;
			if (!WriteFile(m_hSaveFile, lpszData, dwDownloaded, &dwBytesWritten, NULL))
			{
				//xml文件写入失败
				CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_NAME, MY_EEEOR_ID_FILER, MY_ERROR_DESCRIPT_FILER);

				CloseHandles();
				return ERR_DISKERROR;
			}

			delete []lpszData;   

			if (dwDownloaded == 0)   
				break;   
		}   
	}

	CloseHandles();

	return ERR_SUCCESS;
}
int CDownloadThread::TransferDataPost(BOOL bWithFile)
{
	if(!bWithFile) // 不是用文件下载数据
	{
		ATLASSERT(NULL != m_pRead && m_nLength > 0 && NULL != m_pReadLength);
		if (NULL == m_pRead || m_nLength <= 0 || NULL == m_pReadLength)
			return ERR_PARAM;
	}

	CUrlCrack url;
	if (!url.Crack(m_strDownURl.c_str()))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_URLCRACKERROR,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的url = %s Crack 异常!", m_strDownURl.c_str()));
		return ERR_URLCRACKERROR;
	}

	NEED_STOP;

	m_hInetSession = ::InternetOpen(MONEYHUB_USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (m_hInetSession == NULL)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPEN,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetOpen异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		return ERR_INTOPEN;
	}

	NEED_STOP;
	DWORD dwTimeOut = 60000;
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);

	m_hInetConnection = ::InternetConnect(m_hInetSession, url.GetHostName(), url.GetPort(), NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this);
	if (m_hInetConnection == NULL)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTCONNECT,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetConnect异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTCONNECT;
	}

	LPCTSTR ppszAcceptTypes[2];
	ppszAcceptTypes[0] = _T("*/*"); 
	ppszAcceptTypes[1] = NULL;

	DWORD dwFlags = 0;
	if(INTERNET_DEFAULT_HTTPS_PORT == url.GetPort())
	{
		dwFlags = INTERNET_FLAG_SECURE;
		
	}
	else if(INTERNET_DEFAULT_HTTP_PORT == url.GetPort())
	{
		dwFlags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_KEEP_CONNECTION ;
	}

	m_hInetFile = HttpOpenRequest(m_hInetConnection, _T("POST"), url.GetPath(), NULL, NULL, ppszAcceptTypes, dwFlags, (DWORD)this);
	if (m_hInetFile == NULL)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPENREQ,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpOpenRequest异常!LastErrCode = %d", GetLastError()));
		
		CloseHandles();
		return ERR_INTOPENREQ;
	}

	if(INTERNET_DEFAULT_HTTPS_PORT == url.GetPort())
	{
		DWORD dwOptionFlags;
		DWORD dwBuffLen = sizeof(dwOptionFlags);

		InternetQueryOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS,
			(LPVOID)&dwOptionFlags, &dwBuffLen);

		dwOptionFlags |= (SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_CN_INVALID);
		InternetSetOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS,
			&dwOptionFlags, sizeof (dwOptionFlags) );

	}

	NEED_STOP;
	
	HttpAddRequestHeaders(m_hInetFile, _T("Content-Type: application/x-www-form-urlencoded\r\n"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE);
	HttpAddRequestHeaders(m_hInetFile, _T("User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E)\r\n"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 
	HttpAddRequestHeaders(m_hInetFile, _T("Accept-Language: zh-CN"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 

	TCHAR szHeaders[1024];
	
	_stprintf_s(szHeaders, _countof(szHeaders), _T("Moneyhubuid: %s\r\n"), m_strHWID.c_str());
	HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 

	BOOL bSend = ::HttpSendRequest(m_hInetFile, NULL, 0, (LPVOID)m_strSendData.c_str (), m_dwPostDataLength);
	if (!bSend)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTSENDREQ,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpSendRequest异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTSENDREQ;
	}

	NEED_STOP;
	
	TCHAR szStatusCode[32];
	DWORD dwInfoSize = sizeof(szStatusCode);
	if (!HttpQueryInfo(m_hInetFile, HTTP_QUERY_STATUS_CODE, szStatusCode, &dwInfoSize, NULL))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTQUREYINFO,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpQueryInfo异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTQUREYINFO;
	}
	else
	{
		long nStatusCode = _ttol(szStatusCode);
		if (nStatusCode != HTTP_STATUS_OK)
		{
			CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTFILENOTFOUND,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpQueryInfo异常!LastErrCode = %d", GetLastError()));
			//OutputDebugString(strErr);
			
			CloseHandles();
			return ERR_INTFILENOTFOUND;
		}
	}

	NEED_STOP;
	
	if (bWithFile)
	{
		m_hSaveFile = CreateFile(m_strSaveFile.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (m_hSaveFile == INVALID_HANDLE_VALUE)
		{
			CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_CREATEFILE,
				CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的CreateFile异常!LastErrCode = %d", GetLastError()));
			//OutputDebugString(strErr);
			CloseHandles();
			return ERR_CREATEFILE;
		}
	}
	
	NEED_STOP;

	LPBYTE lpszData = NULL;
	DWORD dwSize = 0;
	
	while (true)   
	{   
		NEED_STOP;

		if (!InternetQueryDataAvailable(m_hInetFile, &dwSize, 0, 0))
		{
			CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTQUERYDATAAVAILABLE,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetQueryDataAvailable异常!LastErrCode = %d", GetLastError()));
			//OutputDebugString(strErr);
			// ERR_INTQUERYDATAAVAILABLE
			break;
		}

		
		lpszData = new BYTE[dwSize];
		

		DWORD dwDownloaded = 0;

		if (!InternetReadFile(m_hInetFile, (LPVOID)lpszData, dwSize, &dwDownloaded))   
		{   
			CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTREADFILE,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetReadFile异常!LastErrCode = %d", GetLastError()));
			//OutputDebugString(strErr);
			delete []lpszData;
			CloseHandles();
			return ERR_INTREADFILE;  
		}   
		else   
		{   
			if (bWithFile) // 用文件
			{
				DWORD dwBytesWritten = 0;
				if (!WriteFile(m_hSaveFile, lpszData, dwDownloaded, &dwBytesWritten, NULL))
				{
					CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_WRITEFILE,
						CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的WriteFile异常!LastErrCode = %d", GetLastError()));
					delete []lpszData;
					CloseHandles();
					return ERR_WRITEFILE;
				}
			}
			else
			{
				if (m_nLength < (*m_pReadLength) + dwDownloaded)
				{
					delete []lpszData;
					CloseHandles();
					return ERR_WRITEFILE;	
				}

				memcpy(m_pRead + (*m_pReadLength), lpszData, dwDownloaded);
				*m_pReadLength += dwDownloaded;
			}

			delete []lpszData;   

			if (dwDownloaded == 0)   
				break;   
		}   
	}

	CloseHandles();
	
	return ERR_SUCCESS;
}
Exemplo n.º 25
0
HRESULT protocol_read(Protocol *protocol, void *buf, ULONG size, ULONG *read_ret)
{
    ULONG read = 0;
    BOOL res;
    HRESULT hres = S_FALSE;

    if(protocol->flags & FLAG_ALL_DATA_READ) {
        *read_ret = 0;
        return S_FALSE;
    }

    if(!(protocol->flags & FLAG_SYNC_READ) && (!(protocol->flags & FLAG_REQUEST_COMPLETE) || !protocol->available_bytes)) {
        *read_ret = 0;
        return E_PENDING;
    }

    while(read < size && protocol->available_bytes) {
        ULONG len;

        res = InternetReadFile(protocol->request, ((BYTE *)buf)+read,
                protocol->available_bytes > size-read ? size-read : protocol->available_bytes, &len);
        if(!res) {
            WARN("InternetReadFile failed: %d\n", GetLastError());
            hres = INET_E_DOWNLOAD_FAILURE;
            report_result(protocol, hres);
            break;
        }

        if(!len) {
            all_data_read(protocol);
            break;
        }

        read += len;
        protocol->current_position += len;
        protocol->available_bytes -= len;

        TRACE("current_position %d, available_bytes %d\n", protocol->current_position, protocol->available_bytes);

        if(!protocol->available_bytes) {
            /* InternetQueryDataAvailable may immediately fork and perform its asynchronous
             * read, so clear the flag _before_ calling so it does not incorrectly get cleared
             * after the status callback is called */
            protocol->flags &= ~FLAG_REQUEST_COMPLETE;
            res = InternetQueryDataAvailable(protocol->request, &protocol->query_available, 0, 0);
            if(!res) {
                if (GetLastError() == ERROR_IO_PENDING) {
                    hres = E_PENDING;
                }else {
                    WARN("InternetQueryDataAvailable failed: %d\n", GetLastError());
                    hres = INET_E_DATA_NOT_AVAILABLE;
                    report_result(protocol, hres);
                }
                break;
            }

            if(!protocol->query_available) {
                all_data_read(protocol);
                break;
            }

            protocol->available_bytes = protocol->query_available;
        }
    }

    *read_ret = read;

    if (hres != E_PENDING)
        protocol->flags |= FLAG_REQUEST_COMPLETE;
    if(FAILED(hres))
        return hres;

    return read ? S_OK : S_FALSE;
}
Exemplo n.º 26
0
int WINAPI get_url_into_file(WCHAR *uri, char *path, int *cancelled)
{
	int success = FALSE;
	*cancelled = FALSE;

	HINTERNET hinet, hdownload;
	char data[BUFSIZE];		/* Flawfinder: ignore */
	unsigned long bytes_read;

#if _DEBUG
	fprintf(logfile,"Opening '%s'\n",path);
	fflush(logfile);
#endif	

	FILE* fp = fopen(path, "wb");		/* Flawfinder: ignore */

	if (!fp)
	{
#if _DEBUG
		fprintf(logfile,"Failed to open '%s'\n",path);
		fflush(logfile);
#endif	
		return success;
	}
	
#if _DEBUG
	fprintf(logfile,"Calling InternetOpen\n");
	fflush(logfile);
#endif	
	// Init wininet subsystem
	hinet = InternetOpen(L"LindenUpdater", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (hinet == NULL)
	{
		return success;
	}

#if _DEBUG
	fprintf(logfile,"Calling InternetOpenUrl: %s\n",wchars_to_utf8chars(uri));
	fflush(logfile);
#endif	
	hdownload = InternetOpenUrl(hinet, uri, NULL, 0, INTERNET_FLAG_NEED_FILE, NULL);
	if (hdownload == NULL)
	{
#if _DEBUG
		DWORD err = GetLastError();
		fprintf(logfile,"InternetOpenUrl Failed: %d\n",err);
		fflush(logfile);
#endif	
		return success;
	}

	DWORD sizeof_total_bytes = sizeof(gTotalBytes);
	HttpQueryInfo(hdownload, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &gTotalBytes, &sizeof_total_bytes, NULL);
	
	DWORD total_bytes = 0;
	success = InternetQueryDataAvailable(hdownload, &total_bytes, 0, 0);
	if (success == FALSE)
	{
#if _DEBUG
		DWORD err = GetLastError();
		fprintf(logfile,"InternetQueryDataAvailable Failed: %d bytes Err:%d\n",total_bytes,err);
		fflush(logfile);
#endif	
 		return success;
	}

	success = FALSE;
	while(!success && !(*cancelled))
	{
		MSG msg;

#if _DEBUG
		fprintf(logfile,"Calling InternetReadFile\n");
		fflush(logfile);
#endif	
		if (!InternetReadFile(hdownload, data, BUFSIZE, &bytes_read))
		{
#if _DEBUG
			fprintf(logfile,"InternetReadFile Failed.\n");
			fflush(logfile);
#endif
			// ...an error occurred
			return FALSE;
		}

#if _DEBUG
		if (!bytes_read)
		{
			fprintf(logfile,"InternetReadFile Read 0 bytes.\n");
			fflush(logfile);
		}
#endif

#if _DEBUG
		fprintf(logfile,"Reading Data, bytes_read = %d\n",bytes_read);
		fflush(logfile);
#endif	
		
		if (bytes_read == 0)
		{
			// If InternetFileRead returns TRUE AND bytes_read == 0
			// we've successfully downloaded the entire file
			wsprintf(gProgress, L"Download complete.");
			success = TRUE;
		}
		else
		{
			// write what we've got, then continue
			fwrite(data, sizeof(char), bytes_read, fp);

			gTotalBytesRead += int(bytes_read);

			if (gTotalBytes != -1)
				wsprintf(gProgress, L"Downloaded: %d%%", 100 * gTotalBytesRead / gTotalBytes);
			else
				wsprintf(gProgress, L"Downloaded: %dK", gTotalBytesRead / 1024);

		}

#if _DEBUG
		fprintf(logfile,"Calling InvalidateRect\n");
		fflush(logfile);
#endif	
		
		// Mark the window as needing redraw (of the whole thing)
		InvalidateRect(gWindow, NULL, TRUE);

		// Do the redraw
#if _DEBUG
		fprintf(logfile,"Calling UpdateWindow\n");
		fflush(logfile);
#endif	
		UpdateWindow(gWindow);

#if _DEBUG
		fprintf(logfile,"Calling PeekMessage\n");
		fflush(logfile);
#endif	
		while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);

			if (msg.message == WM_QUIT)
			{
				// bail out, user cancelled
				*cancelled = TRUE;
			}
		}
	}

#if _DEBUG
	fprintf(logfile,"Calling InternetCloseHandle\n");
	fclose(logfile);
#endif
	
	fclose(fp);
	InternetCloseHandle(hdownload);
	InternetCloseHandle(hinet);

	return success;
}
Exemplo n.º 27
0
bool
CHttp::ReadResponse(char ** pbuffer, DWORD * pbuffersize, bool * stop )
{
    char*	buffer = 0; 	    // Partial chunks returned by InternerReadFile
	char*	finalbuffer = 0;	// The entire stream
    char*	tempbuffer = 0;		// For lpFinalBuffer reallocation

	// store the sizes of the above buffers
	DWORD	buffersize = 0, finalbuffersize = 0, tempbuffersize = 0;
	DWORD	downloaded = 0;	// size of data downloaded by InternetReadFile
	
	*pbuffer = 0;
    *pbuffersize = 0;
    
    // Loop to Read data
	do
	{		
		// Get the no. of bytes of data that are available to be read immediately
		// by a subsequent call to InternetReadFile			

		if (!InternetQueryDataAvailable (m_HttpOpenRequest, &buffersize, 0, 0 )) {

            if (finalbuffer )
				free(finalbuffer);
                //delete[] finalbuffer;
			return false;

        } else {

				if (buffersize == 0 )
					break;				

				// Allocate a buffer of the size returned by InternetQueryDataAvailable
				//buffer = new char[buffersize];
				buffer = (char*)calloc(buffersize, sizeof(char));
				
				/* check if the user has asked to stop the result bringing */
				if (stop && *stop ) {
					//delete[] buffer;
					free(buffer);

				if (finalbuffer )
					//delete[] finalbuffer;
					free(finalbuffer);

				return NULL;
			}

			// Read the data from the HttOpenRequest Handle
            if (!yog_InternetReadFile(m_HttpOpenRequest, buffer, buffersize, &downloaded)) {

                //delete[] buffer;
				free(buffer);

                if (finalbuffer )
                    //delete[] finalbuffer;
					free(finalbuffer);

                *pbuffer = 0;

				return false;
                    
            } else 	{

                // Downloaded with return 0 if the entire stream has been read				
				if (downloaded == 0) break;
				
				// For finalbuffer reallocation, store the final buffer address and size
				tempbuffer = finalbuffer;
				tempbuffersize = finalbuffersize;

				// Calculate the new size and reallocate final buffer 
				finalbuffersize = buffersize + tempbuffersize;
				
                //finalbuffer = new char[finalbuffersize+1];
				finalbuffer = (char*)calloc(finalbuffersize+1, sizeof(char));
					
				// Copy the contents of the temp buffer into final buffer
				if (tempbuffer ) memcpy (finalbuffer, tempbuffer, tempbuffersize );

				// Finally copy the current buffer received into final buffer
				memcpy (finalbuffer + tempbuffersize, buffer, buffersize );

				// clear
                if (tempbuffer ) {
                    //delete[] tempbuffer;
					free(tempbuffer);
                    tempbuffer = NULL;
                }
				
                if (buffer ) {
                    //delete[] buffer;
					free(buffer);
                    buffer = NULL;
                }
			}
		}
	}
	while(true);

	/* sometimes PHP might echo 0 zero bytes */
	if (!finalbuffersize )	{

		//*pbuffer = new char[1];
		*pbuffer = (char*)calloc(1, sizeof(char));
		*pbuffer[0] = 0;
		*pbuffersize = 0;
		return true;
	}
    
	finalbuffer[finalbuffersize] = NULL;
	*pbuffer = finalbuffer;
	*pbuffersize = finalbuffersize;

	return true;	
}
Exemplo n.º 28
0
static char *IoLayer_Post(IOLAYER *hPIO, char *pszURL, char *pszPostFields, unsigned int cbPostFields, unsigned int *pdwLength)
{
	IOLAYER_INST *hIO = (IOLAYER_INST*)hPIO;
	URL_COMPONENTS urlInfo = {0};
	HINTERNET hUrl;
	DWORD dwFlags = 0, cbFlags = sizeof(dwFlags), dwRemaining = 0;
	char szHostName[INTERNET_MAX_HOST_NAME_LENGTH],
		szURLPath[INTERNET_MAX_URL_LENGTH], *p;

//OutputDebugString(pszPostFields);
	urlInfo.dwStructSize = sizeof (URL_COMPONENTS);
	urlInfo.lpszHostName = szHostName;
	urlInfo.dwHostNameLength = sizeof(szHostName);
	urlInfo.lpszUrlPath = szURLPath;
	urlInfo.dwUrlPathLength = sizeof(szURLPath);
	if (!InternetCrackUrl(pszURL, strlen(pszURL), 0, &urlInfo)) return NULL;
	/*
	if (!pszPostFields)
	{
		if (pszPostFields=strchr (pszURL, '?'))
			cbPostFields = strlen(pszPostFields);
	}
	*/

	if (!(hUrl = InternetConnect (hIO->hInet, szHostName, 
		INTERNET_DEFAULT_HTTPS_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0)))
	{
		FetchLastError (hIO);
		return NULL;
	}
	
	hIO->hRequest = HttpOpenRequest (hUrl, pszPostFields?"POST":"GET", szURLPath, NULL, NULL, NULL, 
		INET_FLAGS, 0);
	if (!hIO->hRequest)
	{
		FetchLastError (hIO);
		InternetCloseHandle (hUrl);
		return NULL;
	}
	
	InternetQueryOption (hIO->hRequest, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&dwFlags, &cbFlags); 
	dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;
	InternetSetOption (hIO->hRequest, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, sizeof (dwFlags));

	/*
	{
		char szCookies[4096];
		DWORD cbCookies, dwIndex=0;

		OutputDebugString ("Sending headers:\n");
		do
		{
			cbCookies=sizeof(szCookies);
			HttpQueryInfo (hIO->hRequest, HTTP_QUERY_FLAG_REQUEST_HEADERS|HTTP_QUERY_RAW_HEADERS_CRLF, szCookies, &cbCookies, &dwIndex);
			OutputDebugString (szCookies);
		} while (GetLastError() == ERROR_SUCCESS);
	}
	*/

	if (!(HttpSendRequest (hIO->hRequest, "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n"
		"X-Requested-With: XMLHttpRequest", -1,
		pszPostFields, cbPostFields)))
	{
		FetchLastError (hIO);
		InternetCloseHandle (hIO->hRequest);
		hIO->hRequest = NULL;
		InternetCloseHandle (hUrl);
		return NULL;
	}

	/*
	{
		char szCookies[4096];
		DWORD cbCookies, dwIndex=0;

		OutputDebugString ("Received headers:\n");
		do
		{
			cbCookies=sizeof(szCookies);
			HttpQueryInfo (hIO->hRequest, HTTP_QUERY_FLAG_REQUEST_HEADERS|HTTP_QUERY_RAW_HEADERS_CRLF, szCookies, &cbCookies, &dwIndex);
			OutputDebugString (szCookies);
		} while (GetLastError() == ERROR_SUCCESS);
	}
	*/


	while (InternetQueryDataAvailable (hIO->hRequest, &dwRemaining, 0, 0) && dwRemaining > 0)
	{
		if (p = Fifo_AllocBuffer (hIO->hResult, dwRemaining))
			InternetReadFile (hIO->hRequest, p, dwRemaining, &dwRemaining);
	}
	if (!pdwLength)
	{
		// Get string
		Fifo_Add (hIO->hResult, "", 1);
		p = Fifo_Get (hIO->hResult, NULL);
	}
	else
	{
		// Get binary, return size of buffer
		*pdwLength = (unsigned int)-1;
		p = Fifo_Get (hIO->hResult, pdwLength);
	}
	InternetCloseHandle (hIO->hRequest);
	hIO->hRequest = NULL;
	InternetCloseHandle (hUrl);
OutputDebugString(p);
OutputDebugString("\n");
	return p;
}
Exemplo n.º 29
0
BOOL baidu_download(CString dfile, CString token, CString fname,DWORD *process)
{
	if (dfile == L"")
	{
		MessageBox(NULL,L"Îļþ·¾¶²»ÄÜΪ¿Õ", 0, 0);
		return FALSE;
	}
	if (token == L"")
	{
		MessageBox(NULL, L"token²»ÄÜΪ¿Õ", 0, 0);
		return FALSE;
	}
	if (fname == L"")
	{
		MessageBox(NULL, L"ÎļþÃû²»ÄÜΪ¿Õ", 0, 0);
		return FALSE;
	}
	CString url(L"/rest/2.0/pcs/file?method=download&path=%2Fapps%2Fhitdisk%2F" + fname + L"&access_token=" + token);


	DWORD headlength;
	DWORD FileLength;//Îļþ³¤¶È
	TCHAR* szBuff;//»º³åÇø
	DWORD bfsize = 1024 * 64;//»º³åÇø´óС
	TCHAR* FileBuff;//½âÎöÎļþ³¤¶ÈÖ¸Õë

	BOOL bResult = TRUE;
	HINTERNET hRequest = NULL;
	HINTERNET hConnect = NULL;
	HINTERNET hnet = InternetOpen(TEXT("Test"), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);

	hConnect = InternetConnect(hnet, TEXT("pcs.baidu.com"), 443, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
	hRequest = HttpOpenRequest(hConnect, TEXT("GET"), url, NULL, NULL, NULL, INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP | INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_NO_UI | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_RELOAD, 0);

	bResult = HttpSendRequest(hRequest, NULL, 0, NULL, 0);

	//½âÎöÎļþ³¤¶È
	DWORD i;
	szBuff = new TCHAR[bfsize];
	headlength = bfsize;
	bResult = HttpQueryInfo(hRequest, HTTP_QUERY_RAW_HEADERS_CRLF, szBuff, &headlength, NULL);
	FileBuff = wcsstr(szBuff, L"Content-Length");
	FileBuff += 16;
	for (i = 0;; i++)
	{
		if (FileBuff[i] == '\r')
			break;
	}
	FileLength = CharToDword(FileBuff, i);

	CFile cfile(dfile, CFile::modeWrite | CFile::modeCreate);

	DWORD wbfclength = 0;//»º³åÇøµ±Ç°Êý¾Ý³¤¶È
	DWORD wbfsize = 1024 * 1024;//»º³åÇø´óС
	char *WriteBuffer = new char[wbfsize];//ÎļþдÈ뻺³åÇø

	CString show_process;
	DWORD dwBytesAvailable;
	DWORD FileReceived = 0;
	BOOL error = TRUE;
	BOOL cmp = 0;
	while (InternetQueryDataAvailable(hRequest, &dwBytesAvailable, 0, 0))
	{
		DWORD dwBytesRead;
		if (dwBytesAvailable <= bfsize)
		{
			bResult = InternetReadFile(hRequest, szBuff, dwBytesAvailable, &dwBytesRead);
		}
		else
		{
			bResult = InternetReadFile(hRequest, szBuff, bfsize, &dwBytesRead);
		}
		FileReceived += dwBytesRead;

		CopyMemory(WriteBuffer + wbfclength, szBuff, dwBytesRead);
		if (error)
		{
			szBuff[13] = '\0';
			cmp = _strnicmp((char *)szBuff,"{\"error_code\"" , 13);
			if (cmp == 0)
			{
				*process = 100;
				InternetCloseHandle(hRequest);
				InternetCloseHandle(hConnect);
				InternetCloseHandle(hnet);
				cfile.Close();
				cfile.Remove(dfile);
				delete[] szBuff;
				delete[] WriteBuffer;
				return FALSE;
			}
		}
		wbfclength += dwBytesRead;
		if (wbfclength > wbfsize - bfsize)
		{
			cfile.Write(WriteBuffer, wbfclength);
			wbfclength = 0;
		}
		*process = (DWORD)(100 * (double)FileReceived / FileLength);
		if (dwBytesRead == 0)
			break;  // End of File.
	}

	if (wbfclength)
		cfile.Write(WriteBuffer, wbfclength);

	InternetCloseHandle(hRequest);
	InternetCloseHandle(hConnect);
	InternetCloseHandle(hnet);
	cfile.Close();
	delete[] szBuff;
	delete[] WriteBuffer;

	return TRUE;
}
Exemplo n.º 30
0
BOOL CNetFile::DoThread(LPVOID pData)
{_STT();
	if ( !m_bUpload )
	{
		m_dwTransferStatus = NETFILE_DS_DOWNLOADING;

		// Post callback
		DoCallback( (WPARAM)m_dwTransferStatus, (LPARAM)this );

		DWORD ready = 0;

		// Get available data
		if ( !InternetQueryDataAvailable( m_hFile, &ready, 0, 0 ) )
		{	m_dwTransferError = GetLastError();
			return FALSE;
		} // end if

		// Quit if no more data
		if ( ready == 0 ) return FALSE;

		// Get total length if needed
		if ( m_bGetTotalLength )
		{	m_bGetTotalLength = FALSE;

			// Send the query command
			char bufQuery[ 32 ] = "0";
			DWORD dwLengthBufQuery = sizeof( bufQuery );
			DWORD dwHeaderIndex = 0;
			HttpQueryInfo( m_hFile, HTTP_QUERY_CONTENT_LENGTH,
							bufQuery, &dwLengthBufQuery, &dwHeaderIndex );

			// Did we find the header?
			if ( dwHeaderIndex != ERROR_HTTP_HEADER_NOT_FOUND )

				// Convert length from ASCII string to a DWORD.
				m_dwTotalLength = (DWORD)atol( bufQuery );

		} // end if

		while ( ready )
		{
			// Don't byte of more than this computer can chew
			DWORD size = ( ready < m_dwBlockSize ) ? ready : m_dwBlockSize;

			// Allocate a buffer to save new data
			LPBYTE buf = new BYTE[ size + 1 ];
			if ( buf == NULL )
			{
				m_dwTransferError = ERROR_NOT_ENOUGH_MEMORY;
				return FALSE;
			} // end if

			// Attempt to read new data
			DWORD	read = 0;
			if ( !InternetReadFile( m_hFile, buf, size, &read ) )
			{			   
				delete [] buf;
				m_dwTransferError = GetLastError();
				return FALSE;
			} // end if

			// Check for end of file
			if ( read == 0 )
			{
				m_dwTransferStatus = NETFILE_DS_DONE;
				return FALSE;
			} // end if

			if ( m_bMem )
			{
				if ( m_pMem != NULL )
				{
					LPBYTE temp = new BYTE[ m_dwDataRead + size + 1 ];
					if ( temp == NULL )
					{
						m_dwTransferError = ERROR_NOT_ENOUGH_MEMORY;
						return FALSE;
					} // end if
					memcpy( temp, m_pMem, m_dwDataRead );
					memcpy( &temp[ m_dwDataRead ], buf, size );
					temp[ m_dwDataRead + size ] = NULL;
					delete [] m_pMem;
					m_pMem = temp;
				} // end if
				else
				{
					m_pMem = new BYTE[ size + 1 ];
					if ( m_pMem == NULL )
					{
						m_dwTransferError = ERROR_NOT_ENOUGH_MEMORY;
						return FALSE;
					} // end if
					memcpy( m_pMem, buf, size );
					m_pMem[ size ] = NULL;
				} // end else
			} // end if

			// Write the data to the file
			else if ( !m_local.Write( buf, read ) )
			{
				delete [] buf;
				m_dwTransferError = GetLastError();
				return FALSE;
			} // end if

			// Delete buffer
			delete [] buf;

			// Add this to data received
			m_dwDataRead += size;

			// Read the next block
			ready -= size;

		} // end while

	}

	else
	{		
		// Do we have any memory
		if ( m_pMem == NULL || m_dwMemSize == 0 )
		{	m_dwTransferStatus = NETFILE_DS_ERROR;
			return FALSE;
		} // end if

		m_dwTransferStatus = NETFILE_DS_UPLOADING;

		// Post callback
		DoCallback( (WPARAM)m_dwTransferStatus, (LPARAM)this );

		// Don't byte of more than this computer can chew
		DWORD left = m_dwMemSize - m_dwDataWritten;
		DWORD write = ( left < m_dwBlockSize ) ? left : m_dwBlockSize;
		DWORD written = 0;
		
		// Attempt to write some data
		if ( !InternetWriteFile( m_hFile, &m_pMem[ m_dwDataWritten ], write, &written ) )
		{
			m_dwTransferStatus = NETFILE_DS_ERROR;
			m_dwTransferError = GetLastError();
			return FALSE;
		} // end if

		// Count this data
		m_dwDataWritten += written;

		// Have we written all the data?
		if ( m_dwDataWritten == m_dwMemSize )
		{
			m_dwTransferStatus = NETFILE_DS_DONE;
			return FALSE;
		} // end if

	} // end else

	// Wait a bit
	Sleep( 15 );

	// Keep going
	return TRUE; 
}