Exemplo n.º 1
0
bool
CHttp::PostData (char * encodeddata, DWORD encodelen )
{
    INTERNET_BUFFERS	bufferin;
	DWORD				flags = IGNORE_CERT, flaglen = 0, byteswritten=0, lasterr = 0;
   
	memset (&bufferin, 0, sizeof(INTERNET_BUFFERS));
    
    bufferin.dwStructSize	= sizeof(INTERNET_BUFFERS ); 
    bufferin.dwBufferTotal	= encodelen;

retry:

	if (!yog_HttpSendRequestEx (m_HttpOpenRequest, &bufferin, NULL, HSR_INITIATE, 0) )
	{
        lasterr = GetLastError();


        if (lasterr == ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED ) {

            // Return ERROR_SUCCESS regardless of clicking on OK or Cancel
            if(InternetErrorDlg(GetDesktopWindow(), 
                                    m_HttpOpenRequest,
                                    ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED,
                                    FLAGS_ERROR_UI_FILTER_FOR_ERRORS       |
                                    FLAGS_ERROR_UI_FLAGS_GENERATE_DATA     |
                                    FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, 
                                    NULL) != ERROR_SUCCESS )
                return false;
            else
                goto retry;

        } else if (lasterr == ERROR_INTERNET_CANNOT_CONNECT ) {
			return false;

		} else if ((lasterr == ERROR_INTERNET_INVALID_CA ) || 
					(lasterr ==  ERROR_INTERNET_SEC_CERT_CN_INVALID ) ||
					(lasterr == ERROR_INTERNET_SEC_CERT_DATE_INVALID )	
				) {
			
				InternetQueryOption (m_HttpOpenRequest, INTERNET_OPTION_SECURITY_FLAGS,
					 (LPVOID)&flags, &flaglen);

            flags |= IGNORE_CERT;
            InternetSetOption (m_HttpOpenRequest, INTERNET_OPTION_SECURITY_FLAGS, &flags, sizeof(flags));
            
			goto retry;

        } else {
			return false;
        }
    }	

	if (!yog_InternetWriteFile(m_HttpOpenRequest, encodeddata, encodelen, &byteswritten ) )
		return false;

	return true;
}
Exemplo n.º 2
0
static BOOL
wininet_resolve_send_error(
    HINTERNET   a_hHttpRequest,
    DWORD       a_dwErrorCode )
{
    DWORD dwResult = InternetErrorDlg(
        GetDesktopWindow(),
        a_hHttpRequest,
        a_dwErrorCode,
        FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
        FLAGS_ERROR_UI_FLAGS_GENERATE_DATA |
        FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS,
        NULL );
    BOOL bRetVal = (a_dwErrorCode == ERROR_INTERNET_INCORRECT_PASSWORD) ?
        (dwResult == ERROR_INTERNET_FORCE_RETRY) :
        (dwResult == ERROR_SUCCESS);
    /* If appropriate for your application, it is possible to ignore
       errors in future once they have been handled or ignored once.
       For example, to ignore invalid SSL certificate dates on this
       connection once the client has indicated to ignore them this
       time, uncomment this code.
    */
    /*
    if (bRetVal)
    {
        switch (a_dwErrorCode)
        {
        case ERROR_INTERNET_SEC_CERT_CN_INVALID:
            wininet_flag_set_option(a_hHttpRequest,
                INTERNET_OPTION_SECURITY_FLAGS,
                SECURITY_FLAG_IGNORE_CERT_CN_INVALID );
            break;
        }
    }
    */
    return bRetVal;

}
Exemplo n.º 3
0
void main(int argc, char *argv[])
{

    if(argc<2)
    {
        printf("USAGE: %s [webserver]\n", argv[0]);
        return;
    }

    // Open Internet session.
    HINTERNET hSession = InternetOpen(
                            "Wininet Client App",
                            PRE_CONFIG_INTERNET_ACCESS,
                            NULL, 
                            INTERNET_INVALID_PORT_NUMBER,
                            0) ;

    // Connect to server\website.
    // NOTE: There must be a client authentication certificate
    // available that corresponds to the name of the server or 
    // website that you are connecting to.
    // For instance, if I am running WebServer on machine davemo1,
    // then I can specify "davemo1" as the webserver. I must have a
    // client authentication certificate available 
    HINTERNET hConnect = InternetConnect(
                            hSession,
                            argv[1],
                            INTERNET_DEFAULT_HTTPS_PORT,
                            "",
                            "",
                            INTERNET_SERVICE_HTTP,
                            0,
                            0) ;



    // Request the file default.htm from the server.
    HINTERNET hHttpFile = HttpOpenRequest(
                            hConnect,
                            "GET",
                            "default.htm",
                            HTTP_VERSION,
                            "",
                            NULL,
                            INTERNET_FLAG_SECURE,
                            0) ;

    //
    // Send the request and check for success
    //
    while(!HttpSendRequest(hHttpFile, NULL, 0, 0, 0))
    {

        // If the server requires a client certificate I'll invoke
        // this nifty dialogue to select a certificate and
        // reset the options for the request.

        printf("HttpSendRequest error : (%lu)\n", GetLastError());

        InternetErrorDlg (
            GetDesktopWindow(),
            hHttpFile,
            ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED,
            FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
            FLAGS_ERROR_UI_FLAGS_GENERATE_DATA |
            FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS,
            NULL);


    }

    // Get the length of the file.            
    char bufQuery[32] ;

    DWORD dwLengthBufQuery;
    dwLengthBufQuery = sizeof(bufQuery);

    DWORD dwIndex;
    dwIndex=0;

    BOOL bQuery;
    
    bQuery = HttpQueryInfo(
                hHttpFile,
                HTTP_QUERY_CONTENT_LENGTH, 
                bufQuery, 
                &dwLengthBufQuery,
                &dwIndex) ;

    if(!bQuery)
        printf("HttpQueryInfo error : <%lu>\n", GetLastError());


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

    // Allocate a buffer for the file.   
    char* buffer;
    
    buffer = new char[dwFileSize+1] ;

    printf("Trying to read %lu bytes from the server\n", dwFileSize);

    // Read the file into the buffer. 
    DWORD dwBytesRead ;
    BOOL bRead;
    
    bRead = InternetReadFile(
                hHttpFile,
                buffer,
                dwFileSize+1, 
                &dwBytesRead);

    if(!bRead)
    {
        printf("InternetReadFile error : <%lu>\n", GetLastError());
    }
    else
    {
        // Put a zero on the end of the buffer.
        buffer[dwBytesRead] = 0 ;

        // Print the buffer contents.
        printf("Retrieved %lu data bytes: %s\n", dwBytesRead, buffer) ;
    }

    // Close all of the Internet handles.
    InternetCloseHandle(hHttpFile); 
    InternetCloseHandle(hConnect) ;
    InternetCloseHandle(hSession) ;


}
Exemplo n.º 4
0
STDMETHODIMP HttpRequest::Send(IHttpResponse** pVal)
{
    
	HRESULT hr=S_OK;
    
	ATLASSERT(pVal);
	(*pVal)=NULL;
	if(!this->m_szUrl || _tcslen(this->m_szUrl)==0) {
		InfoMsgBox(_T("请先指定请求的目标URL地址!"));
		return hr;
	}
    
	//显示进度
	rcContext.hOpen=this->m_hOpen;
	rcContext.dwPostFileLength=0;
	rcContext.dwPostedLength=0;
	rcContext.dwContentLength=0;
	rcContext.dwReceivedLength=0;
	if (this->m_blShowRequestProgress){
		ZeroMemory(rcContext.szMemo,sizeof(rcContext.szMemo));//STRLEN_DEFAULT);
		_tcscpy_s(rcContext.szMemo,_T("请稍候,正在准备连接..."));
		rcContext.hThread=CreateThread(NULL, 0,(LPTHREAD_START_ROUTINE)ProgressDialog,0,0,&(rcContext.dwThreadID));
	}

	//请求方法
	TCHAR szUrl[STRLEN_4K]={0};
	_tcscpy_s(szUrl,m_szUrl);
	TCHAR szMethod[STRLEN_SMALL]=_T("POST");
	if(this->m_szMethod && _tcslen(this->m_szMethod)>0){
		ZeroMemory(szMethod,sizeof(szMethod));
		_tcscpy_s(szMethod,m_szMethod);
	}

	//±äÁ¿¶¨Òå
	DWORD dwError=0;
	DWORD dwFlags=0;
	HINTERNET hConnect=0;			//Internetȇȡ
	HINTERNET hRequest=0;			//InternetÁ¬½Ó
	INTERNET_PORT dwPort;

	BOOL postFileFlag=FALSE;	//ÊÇ·ñÓÐÓÐЧµÄÌá½»Îļþ¡£
	HANDLE hPostFile=0;
	DWORD dwPostFileSize=0;

	BOOL sendRequestSucceeded=TRUE;	//·¢ËÍÇëÇóÊÇ·ñ³É¹¦

	DWORD dwSize=0;

	DWORD dwStatusCode=0;	//httpÇëÇóÏìÓ¦´úÂë
	DWORD dwContentLength=0;	//httpÇëÇóÏìÓ¦ÄÚÈݳ¤¶È
	DWORD dwErrorCode=0;	//httpÇëÇóÏìÓ¦´íÎóÂë
	TCHAR szContentType[STRLEN_DEFAULT]={0};	//httpÇëÇóÏìÓ¦ÄÚÈÝÀàÐÍ
	CComBSTR szResText(L"");				//httpÇëÇóÏìÓ¦·µ»Ø½á¹ûÎı¾
	TCHAR* szHeader=NULL;	//httpÇëÇóÏìӦͷÐÅÏ¢

	BOOL getHeanderSucceeded=TRUE;	//»ñÈ¡httpÇëÇóÏìӦͷÐÅÏ¢ÊÇ·ñ³É¹¦

	char readBuffer[STRLEN_1K]={0};	//ÿ´Î¶ÁÈ¡µÄÏìÓ¦ÄÚÈÝ
	DWORD dwCalcLength=0;	//ͨ¹ýÄÚÈݼÆËã³öÀ´µÄContentLength
	
	BOOL responseFileFlag=FALSE;	//ÊÇ·ñÓÐÓÐЧµÄÏìÓ¦ÄÚÈݱ¾µØ±£´æÎļþ
	HANDLE hResponseFile=0;	//ÇëÇóÏìÓ¦ÄÚÈݱ£´æµ½±¾µØÎļþµÄÎļþ¾ä±ú

	int requestCount=1;	//ÇëÇó´ÎÊý
	
	TCHAR szAccept[] = _T("*/*");
	LPTSTR AcceptTypes[2]={0};
	AcceptTypes[0]=szAccept;
	AcceptTypes[1]=NULL;

	
	CComPtr<IHttpResponse> response;	//ÇëÇóÏìÓ¦¶ÔÏó

	//Á¬½Ó
	dwPort=this->m_usUrlPort;	//¶Ë¿ÚºÅ
	dwFlags= INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD |INTERNET_FLAG_KEEP_CONNECTION;
	if (this->m_blUrlIsSSL) dwFlags |= INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;
	
	//´ò¿ªÁ¬½Ó
	if ( !(hConnect = InternetConnect(this->m_hOpen,this->m_szUrlHost , dwPort, _T(""),  _T(""), INTERNET_SERVICE_HTTP, 0, (DWORD)&rcContext))){
		dwError=GetLastError();
		ErrorMsgBox(dwError,_T("Internet连接错误:%s"));
		goto clean;
	}
	
reconnect:
	//´ò¿ªÇëÇó
	if ( !(hRequest = HttpOpenRequest(hConnect,this->m_szMethod,this->m_szUrlFile, _T("HTTP/1.1"), _T(""),(LPCTSTR*)AcceptTypes, dwFlags ,(DWORD)&rcContext))){
		dwError=GetLastError();
		ErrorMsgBox(dwError,_T("Internet打开请求错误:%s"));
		goto clean;
	}
	
	//ÓÐÖ¸¶¨Ìá½»Îļþ
	if (this->m_szPostFile && _tcslen(this->m_szPostFile)) {
		postFileFlag=PathFileExists(this->m_szPostFile);
	}
	
	//Èç¹ûÓÐÌá½»µÄÎļþ
	if(postFileFlag) {
		if ((hPostFile = CreateFile(this->m_szPostFile,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,(HANDLE)NULL)) == (HANDLE)(-1))
		{
			dwError=GetLastError();
			ErrorMsgBox(dwError,_T("提交的文件不存在或者无法打开:%s"));			
			goto clean;
		}        
		dwPostFileSize=GetFileSize(hPostFile,NULL);
		rcContext.dwPostFileLength=dwPostFileSize;
		TCHAR szPostFileSize[STRLEN_SMALL]={0};
		_stprintf_s(szPostFileSize,_T("%d"),dwPostFileSize);
		this->AddHeader(T2BSTR(_T("Content-Length")),T2BSTR(szPostFileSize));
	}
	
	//ÉèÖÃÇëÇóÍ·
	if (this->m_szHeader && _tcslen(this->m_szHeader)) {
		if (!HttpAddRequestHeaders(hRequest,this->m_szHeader,-1L,HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD)){
			dwError=GetLastError();
			ErrorMsgBox(dwError,_T("设置请求头错误:%s"));
			goto clean;
		}
	}
	/*
	InternetSetOption(FhRequest,     
                  INTERNET_OPTION_CLIENT_CERT_CONTEXT,   
                  (LPVOID)pdDesiredCert,     
                  sizeof(CERT_CONTEXT));   
 INTERNET_FLAG_KEEP_CONNECTION£¬INTERNET_FLAG_EXISTING_CONNECT
	*/
	//´¦Àí¶îÍâÉèÖ㨺öÂÔһЩ´íÎó£©
	dwFlags=0;
	dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA|SECURITY_FLAG_IGNORE_REVOCATION|SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP|SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS|SECURITY_FLAG_IGNORE_CERT_DATE_INVALID|SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
	if (!InternetSetOption (hRequest, INTERNET_OPTION_SECURITY_FLAGS,&dwFlags,sizeof(dwFlags))){
		dwError=GetLastError();
		ErrorMsgBox(dwError,_T("设置请求选项错误:%s"));
		goto clean;
	}
	
	//·¢ËÍÇëÇó
again:
	if(postFileFlag){	//ÓÐÌá½»ÎļþÄÚÈÝ
		INTERNET_BUFFERS BufferIn = {0};
		DWORD dwBytesWritten;
		BYTE bts[STRLEN_1K]={0};
		DWORD dwBtsRead=0;
		DWORD dwTotalBytes=0;

		BufferIn.dwStructSize = sizeof(INTERNET_BUFFERS);
		BufferIn.Next=NULL;
		BufferIn.dwBufferTotal=dwPostFileSize;

		sendRequestSucceeded=HttpSendRequestEx(hRequest, &BufferIn, NULL, HSR_INITIATE,(DWORD)&rcContext);
		
		while(ReadFile(hPostFile, bts, STRLEN_1K, &dwBtsRead, NULL) && dwBtsRead>0 && dwTotalBytes<=dwPostFileSize){
			if (!InternetWriteFile(hRequest, bts,dwBtsRead, &dwBytesWritten))
			{
				dwError=GetLastError();
				ErrorMsgBox(dwError,_T("发送文件内容错误:%s"));
				goto clean;
			}
			dwTotalBytes+=dwBtsRead;
			rcContext.dwPostedLength=dwTotalBytes;
		}
		
		if(!HttpEndRequest(hRequest, NULL, 0, 0))
		{
			dwError=GetLastError();
			ErrorMsgBox(dwError,_T("关闭HTTP连接时错误:%s"));
			goto clean;
		}
	}//if end
	else{	//ûÓÐÌá½»ÎļþÄÚÈÝ
		sendRequestSucceeded=HttpSendRequest(hRequest, NULL, 0, NULL, 0);
	}	//else end

	//²é¿´ÊÇ·ñÇëÇó·¢Ëͳɹ¦
	if (!sendRequestSucceeded){
		dwError=GetLastError();
		switch(dwError){
			case ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED:
				if(InternetErrorDlg(GetDesktopWindow(),hRequest,ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED,FLAGS_ERROR_UI_FILTER_FOR_ERRORS|FLAGS_ERROR_UI_FLAGS_GENERATE_DATA|FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS,NULL)!=ERROR_SUCCESS)
				{
					requestCount++;
					if (requestCount>2) {
						InfoMsgBox(_T("已经尝试发送请求操作2次仍无法成功,请联系系统管理员!"));
						goto clean;
					}	//Èç¹ûÑ­»·ÇëÇó´ÎÊý¶àÓÚÁ½´Î£¬ÄÇô²»ÔÙÑ­»·
					else goto again;
				}
				break;
			case ERROR_SUCCESS:
				break;
			default:
				ErrorMsgBox(dwError,_T("发送请求错误:%s"));
				goto clean;
		}//switch end
	}//if end

	//È¡ÏìӦ״̬ÏûÏ¢
	dwSize= sizeof(DWORD);
	if (!HttpQueryInfo(hRequest,HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwStatusCode, &dwSize, NULL))
	{
		dwError=GetLastError();
		ErrorMsgBox(dwError,_T("获取响应代码错误:%s"));
		goto clean;
	}

	switch(dwStatusCode){
		case HTTP_STATUS_DENIED:	//ÐèÒªµÇ¼
		case HTTP_STATUS_PROXY_AUTH_REQ:
			InfoMsgBox(_T("请求的地址需要登录,请您先登录后再发送请求!"));
			goto clean;
		case HTTP_STATUS_REDIRECT:	//Öض¨Ïò
		case HTTP_STATUS_MOVED:
			{
				TCHAR szRedirect[4096]={0};
				DWORD dwRedirect=sizeof(szRedirect);
				if (!HttpQueryInfo(hRequest,HTTP_QUERY_LOCATION,(LPVOID)szRedirect,&dwRedirect,NULL)){
					dwError=GetLastError();
					ErrorMsgBox(hr,_T("获取重定向地址错误:%s"));
					goto clean;
				}
				this->put_Url(szRedirect);
				//ÏȹرÕÁ¬½ÓºÍÇëÇó£¬È»ºóÖØÐÂÁ¬½Ó
				if (!InternetCloseHandle(hRequest))
				{
					dwError=GetLastError();
					ErrorMsgBox(dwError,_T("关闭HTTP请求错误:%s"));
					goto clean;
				}
				//if (!InternetCloseHandle(hConnect))
				//{
				//	dwError=GetLastError();
				//	ErrorMsgBox(dwError,_T("关闭HTTP连接错误:%s"));
				//	goto clean;
				//}
				//MessageBox(0,szRedirect,_T("重定向"),0);
				goto reconnect;
			}
		case HTTP_STATUS_OK:
		default:
			break;
	}

	//¹¹ÔìÇëÇóÏìÓ¦¡£
	response.p=NULL;
	hr=response.CoCreateInstance(_T("YRExchange.HttpResponse"));
	if (FAILED(hr)) {
		ErrorMsgBox(hr,_T("创建HttpResponse错误:%s"));
		goto clean;
	}
	response->put_StatusCode(dwStatusCode);
	response->put_ErrorCode(dwError);

	//ÏìÓ¦ÄÚÈÝ´óС
	dwSize=sizeof(dwContentLength);
	if (HttpQueryInfo(hRequest,HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER ,&dwContentLength,&dwSize,NULL)){
		//dwError=GetLastError();	
		//ErrorMsgBox(dwError,_T("获取请求响应内容长度错误:%s"));
		//goto clean;
		if (dwContentLength>0) {
			response->put_ContentLength(dwContentLength);
			rcContext.dwContentLength=dwContentLength;
		}
	}

	//ÏìÓ¦ÄÚÈÝÀàÐÍ 
	dwSize=sizeof(szContentType);
	if (HttpQueryInfo(hRequest,HTTP_QUERY_CONTENT_TYPE ,(LPVOID)szContentType,&dwSize,NULL)){
		//dwError=GetLastError();	
		//ErrorMsgBox(dwError,_T("获取请求响应内容类型错误:%s"));
		//goto clean;
		if (_tcslen(szContentType)>0) response->put_ContentType(T2BSTR(szContentType));
	}
	
	//ËùÓÐÏìӦͷÐÅÏ¢
	szHeader=new TCHAR[STRLEN_8K];
	dwSize=STRLEN_8K*sizeof(TCHAR);
getheader:
	getHeanderSucceeded=HttpQueryInfo(hRequest,HTTP_QUERY_RAW_HEADERS_CRLF ,(LPVOID)szHeader,&dwSize,NULL);
	if(!getHeanderSucceeded){
		dwError=GetLastError();
		if (dwError==ERROR_INSUFFICIENT_BUFFER){
			TCHAR szXX[100]={0};
			_stprintf_s(szXX,_T("dwError=%d,dwSize=%d"),dwError,dwSize);
			InfoMsgBox(szXX);
			SAFE_FREE_STRING_PTR(szHeader);
			szHeader=new TCHAR[dwSize+2];
			dwSize+=2;
			dwSize=dwSize*sizeof(TCHAR);
			goto getheader;
		}
		else if (dwError!=ERROR_SUCCESS){
			ErrorMsgBox(dwError,_T("获取请求响应头信息错误:%s"));
			goto clean;
		}
	}
	if(szHeader) response->put_Header(T2BSTR(szHeader));
	//ÏìÓ¦ÄÚÈÝ´¦Àí
	if (this->m_blSaveResponseToFile && this->m_szResponseFile && _tcslen(this->m_szResponseFile)>0 && dwStatusCode != 201){	//°ÑÏìÓ¦ÄÚÈݱ£´æµ½Îļþ
		//´´½¨Îļþ 
		hResponseFile = CreateFile(this->m_szResponseFile,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
		if (hResponseFile == INVALID_HANDLE_VALUE) 
		{ 
			dwError=GetLastError();
			ErrorMsgBox(dwError,_T("打开响应内容本地保存文件错误:%s"));
			goto clean;
		}
		responseFileFlag=TRUE;
	}
	do{
		ZeroMemory(readBuffer,STRLEN_1K);
		dwSize=0;
		if (!InternetReadFile(hRequest,(LPVOID)readBuffer,sizeof(readBuffer),&dwSize)){
			dwError=GetLastError();
			ErrorMsgBox(dwError,_T("读取请求响应内容错误:%s"));
			goto clean;
		}
		if (dwSize!=0){
			dwCalcLength+=dwSize;
			if (responseFileFlag){	//дÎļþ
				DWORD dwWritten=0;
				if (!WriteFile(hResponseFile,readBuffer,dwSize,&dwWritten,NULL)){
					dwError=GetLastError();
					ErrorMsgBox(dwError,_T("写入响应内容本地保存文件错误:%s"));
					goto clean;
				}
			}
			else{	//×·¼Óµ½ÏàÓ¦Îı¾
				char buffer[STRLEN_1K+2]={0};
				strncpy_s(buffer,readBuffer,dwSize);
				if (szResText) szResText.Append(buffer);
			}
			if (dwCalcLength==dwContentLength) break;
			rcContext.dwReceivedLength=dwCalcLength;
		}//if end
	}while(dwSize!=0);
	
	//°ÑÏìÓ¦ÄÚÈݱ£´æµ½ÏìÓ¦Îı¾
	if (!responseFileFlag){
		response->put_ContentText(szResText.Detach());
	}//
	//×ÊÔ´»ØÊÕ
clean:
	//¹Ø±ÕÎļþ
	if(hPostFile) CloseHandle(hPostFile);
	if(hResponseFile) {
		FlushFileBuffers(hResponseFile);
		CloseHandle(hResponseFile);
	}

	//»ØÊÕhttpÁ¬½ÓºÍÇëÇó¾ä±ú
	if (hRequest) InternetCloseHandle(hRequest);
	if (hConnect) InternetCloseHandle(hConnect);

	//¹Ø±Õ״̬¿ò
	//if (this->m_blShowRequestProgress) WaitForMultipleObjects(1,&rcContext.hThread,TRUE,INFINITE); 
	if (this->m_blShowRequestProgress) EndDialog(rcContext.hProgressWnd,0);

	SAFE_FREE_STRING_PTR(szHeader);

	response.CopyTo(pVal);

	return S_OK;
}
Exemplo n.º 5
0
UINT APIENTRY CXMLHttpRequest::SendThread(void *pParm)
{
	ATLTRACE(_T("CXMLHttpRequest::SendThread\n"));

	CXMLHttpRequest *pCtx = reinterpret_cast<CXMLHttpRequest *> (pParm);
	if (NULL == pCtx)
		return 0;

	HINTERNET hOpen    = NULL;
	HINTERNET hConnect = NULL; 
	HINTERNET hRequest = NULL; 

	hOpen = InternetOpen(_T("XMLHTTP/1.0"),INTERNET_OPEN_TYPE_PRECONFIG,
										NULL,NULL,0);
	if (NULL == hOpen) {
		DWORD res = GetLastError();
		pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
		pCtx->m_bSuccess = false;
	}

	if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
		if (INTERNET_INVALID_STATUS_CALLBACK == InternetSetStatusCallback(hOpen,
				CXMLHttpRequest::InternetStatusCallback)) {
			pCtx->m_Error = _T("Invalid Internet Status Callback function.");
			pCtx->m_bSuccess = false;
		}
	}

	bool bPromptForAuthentication = true;
	if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
		LPTSTR lpszUserName = NULL;
		LPTSTR lpszPassword = NULL;
		if (pCtx->m_User.length() > 0) {
			bPromptForAuthentication = false;
			lpszUserName = pCtx->m_User; 
			if (pCtx->m_Password.length() > 0) 
				lpszPassword = pCtx->m_Password;
		}    
		hConnect = InternetConnect(hOpen,pCtx->m_HostName,pCtx->m_Port,lpszUserName,lpszPassword,
										INTERNET_SERVICE_HTTP,0,reinterpret_cast<DWORD> (pCtx));
		if (NULL == hConnect) {
			DWORD res = GetLastError();
			pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
			pCtx->m_bSuccess = false;
		}
	}

	if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
		DWORD dwFlags = (443 == pCtx->m_Port) ? INTERNET_FLAG_SECURE : 0;
		dwFlags |= INTERNET_FLAG_NO_CACHE_WRITE;
		hRequest = HttpOpenRequest(hConnect,pCtx->m_Method,
						pCtx->m_URLPath,NULL,NULL,NULL,
						dwFlags,reinterpret_cast<DWORD> (pCtx));
		if (NULL == hRequest) {
			DWORD res = GetLastError();
			pCtx->m_bSuccess = false;
			pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
		}
	}

	BOOL rc = TRUE;

	if (!pCtx->m_bAbort && pCtx->m_bSuccess && pCtx->m_RequestHeaderMap.GetSize() > 0) {
		_bstr_t requestHeaders;
		for (int i = 0 ; i < pCtx->m_RequestHeaderMap.GetSize(); ++i) {
			requestHeaders += pCtx->m_RequestHeaderMap.GetKeyAt(i);
			requestHeaders += _T(": ");
			requestHeaders += pCtx->m_RequestHeaderMap.GetValueAt(i);
			requestHeaders += _T("\r\n");
		}
		rc = HttpAddRequestHeaders(hRequest,requestHeaders,-1,HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE);
		if (!rc) {	
			DWORD res = GetLastError();
			pCtx->m_bSuccess = false;
			pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
		}
	}
	
	DWORD dwLen = 0;
	DWORD dwError = ERROR_SUCCESS; 
	do {
		if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
			rc = HttpSendRequest(hRequest,NULL,0,pCtx->m_pBody,pCtx->m_lBodyLength);
			if (!rc) {	
				DWORD res = GetLastError();
				pCtx->m_bSuccess = false;
				pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
				break;
			}
		}
		if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
			dwLen = sizeof(DWORD);
			rc = HttpQueryInfo(hRequest,
							   HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
							   &pCtx->m_dwStatus,&dwLen,NULL);
			if (!rc) {
				DWORD res = GetLastError();
				pCtx->m_bSuccess = false;
				pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
				break;
			}
		}
		if (!pCtx->m_bAbort && pCtx->m_bSuccess &&
			bPromptForAuthentication &&
			(HTTP_STATUS_PROXY_AUTH_REQ == pCtx->m_dwStatus ||
			 HTTP_STATUS_DENIED		    == pCtx->m_dwStatus)) 
   			dwError = InternetErrorDlg(pCtx->m_HwndParent,
									   hRequest,
									   ERROR_INTERNET_INCORRECT_PASSWORD,
									   FLAGS_ERROR_UI_FILTER_FOR_ERRORS	   |
									   FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS |
									   FLAGS_ERROR_UI_FLAGS_GENERATE_DATA,				
									   NULL);
		else
			break;
	
	} while (ERROR_INTERNET_FORCE_RETRY == dwError &&
			 !pCtx->m_bAbort && pCtx->m_bSuccess); 		
	
	if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
		dwLen = 1024;
		TCHAR *pBuff = new TCHAR[dwLen];
		rc = HttpQueryInfo(hRequest,HTTP_QUERY_RAW_HEADERS_CRLF,pBuff,&dwLen,NULL);
		if (!rc) {
			DWORD res = GetLastError();
			if (ERROR_INSUFFICIENT_BUFFER == res) {
				delete [] pBuff;
				pBuff = new TCHAR[dwLen];
				rc = HttpQueryInfo(hRequest,HTTP_QUERY_RAW_HEADERS_CRLF,pBuff,&dwLen,NULL);
				if (!rc) {
					res = GetLastError();
					pCtx->m_bSuccess = false;
					pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
				}
			}
			else {
				pCtx->m_bSuccess = false;
				pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
			}
		}
		if (rc)
			 pCtx->m_ResponseHeaders = pBuff;

		delete [] pBuff;
	}

	if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
		dwLen = 1024;
		TCHAR *pBuff = new TCHAR[dwLen];
		rc = HttpQueryInfo(hRequest,HTTP_QUERY_STATUS_TEXT,pBuff,&dwLen,NULL);
		if (!rc) {
			DWORD res = GetLastError();
			if (ERROR_INSUFFICIENT_BUFFER == res) {
				delete [] pBuff;
				pBuff = new TCHAR[dwLen];
				rc = HttpQueryInfo(hRequest,HTTP_QUERY_STATUS_TEXT,pBuff,&dwLen,NULL);
				if (!rc) 
					_tcscpy(pBuff,_T("Unknown"));
			}
			else 
				_tcscpy(pBuff,_T("Unknown"));
		}
		pCtx->m_StatusText = pBuff; 
		delete [] pBuff;
	
		if (HTTP_STATUS_OK != pCtx->m_dwStatus) {
			TCHAR errBuff[MAX_PATH] = _T("");
			wsprintf(errBuff,_T("HTTP Status Code: %d, Reason: "),pCtx->m_dwStatus);
			pCtx->m_Error = errBuff;
			pCtx->m_Error += pCtx->m_StatusText;
			pCtx->m_bSuccess = false;
		}
	}

	if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
		PBYTE buffer[255];
		DWORD dwRead = 0;
		delete [] pCtx->m_pResponseBody;
		pCtx->m_pResponseBody = NULL;
		pCtx->m_lResponseBodyLength = 0;
		while (rc = InternetReadFile(hRequest,buffer,255,&dwRead)) {
			if (!rc || pCtx->m_bAbort || 0 == dwRead) 
				break;
					
			PBYTE tmp = new BYTE[pCtx->m_lResponseBodyLength + dwRead];
			if (pCtx->m_pResponseBody) {
				memcpy(tmp,pCtx->m_pResponseBody,pCtx->m_lResponseBodyLength);
				delete [] pCtx->m_pResponseBody;
			}

			memcpy(tmp+pCtx->m_lResponseBodyLength,buffer,dwRead);
			pCtx->m_pResponseBody = tmp;
			pCtx->m_lResponseBodyLength += dwRead;
		}
		if (!rc) {
			DWORD res = GetLastError();
			pCtx->m_Error = _T("Error reading response: ") + CXMLHttpRequest::GetErrorMsg(res);
			pCtx->m_bSuccess = false;
		}
	}

	if (hRequest != NULL)
		InternetCloseHandle(hRequest);
	
	if (hConnect != NULL) 
		InternetCloseHandle(hConnect);

	if (hOpen)
		InternetCloseHandle(hOpen);
	
	if (!pCtx->m_bAbort && pCtx->m_bAsync)
		::PostMessage(pCtx->m_hWnd,MSG_READY_STATE_CHANGE,4,0); 
  
	return 0;
}
Exemplo n.º 6
0
bool
CHttp::Authorize (unsigned long *num)
{
    INT						count=0;
    DWORD					numsize = sizeof(DWORD);
	DWORD					lasterr=0;
	DWORD					flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_KEEP_CONNECTION;
	HINTERNET				authrequest = NULL;

	/* set the flags for internet connection  and check if SSL required */
	if (wcsicmp (m_Protocol, L"https" ) == 0 )
		flags |= INTERNET_FLAG_SECURE;

	/* create a temporary internet request for proxy handling */
	authrequest = HttpOpenRequest(m_InternetConnect, L"POST", m_FileName, NULL, NULL, NULL, flags, 0L );
	if (!authrequest )
		return false;

retry:

    /* post a dummy request to check for auth */
	if (!yog_HttpSendRequest(&lasterr, authrequest, NULL, 0, NULL, 0) ) {

        if (lasterr == ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED ) {

            // Return ERROR_SUCCESS regardless of clicking on OK or Cancel
            if(lasterr = InternetErrorDlg(GetDesktopWindow(), 
                                    authrequest,
                                    ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED,
                                    FLAGS_ERROR_UI_FILTER_FOR_ERRORS       |
                                    FLAGS_ERROR_UI_FLAGS_GENERATE_DATA     |
                                    FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, 
                                    NULL) != ERROR_SUCCESS )
            {
                goto cleanup;
            } else
			{
                goto retry;
			}
        }
		if ((lasterr == ERROR_INTERNET_INVALID_CA) ||
            (lasterr == ERROR_INTERNET_SEC_CERT_CN_INVALID) || 
            (lasterr == ERROR_INTERNET_SEC_CERT_DATE_INVALID )) {

                DWORD flags;
                DWORD flaglen = sizeof(flags);
			
			/*  this means the HTTP site is not authorised by a valid certification so we ignore it and
				move ahead */	
            InternetQueryOption (authrequest, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&flags, &flaglen);
			flags |= IGNORE_CERT;
            if (!InternetSetOption (authrequest, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&flags, sizeof (flags) ) )
				goto cleanup;
			else 
			{
				goto retry;
			}
        }
    }

    if ( !HttpQueryInfo ( authrequest, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,  (LPVOID)num, &numsize, NULL))
        goto cleanup;

	if ( *num == HTTP_STATUS_DENIED || *num == HTTP_STATUS_PROXY_AUTH_REQ )
	{
        count++;

        if (count > 3 )
            goto cleanup;

        if (SetAuthDetails ( authrequest, *num ))
		{
            goto retry;
		}
        else
            goto cleanup;
    }

    InternetCloseHandle (authrequest );
    // We don't want to descard the output

	return true;

cleanup:
	InternetCloseHandle (authrequest );
	return false;
}
Exemplo n.º 7
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.º 8
0
Arquivo: http.c Projeto: ccpgames/wine
static HRESULT handle_http_error(HttpProtocol *This, DWORD error)
{
    IServiceProvider *serv_prov;
    IWindowForBindingUI *wfb_ui;
    IHttpSecurity *http_security;
    BOOL security_problem;
    DWORD dlg_flags;
    HWND hwnd;
    DWORD res;
    HRESULT hres;

    TRACE("(%p %u)\n", This, error);

    switch(error) {
    case ERROR_INTERNET_SEC_CERT_DATE_INVALID:
    case ERROR_INTERNET_SEC_CERT_CN_INVALID:
    case ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR:
    case ERROR_INTERNET_HTTPS_TO_HTTP_ON_REDIR:
    case ERROR_INTERNET_INVALID_CA:
    case ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED:
    case ERROR_INTERNET_SEC_INVALID_CERT:
    case ERROR_INTERNET_SEC_CERT_ERRORS:
    case ERROR_INTERNET_SEC_CERT_REV_FAILED:
    case ERROR_INTERNET_SEC_CERT_NO_REV:
    case ERROR_INTERNET_SEC_CERT_REVOKED:
    case ERROR_HTTP_REDIRECT_NEEDS_CONFIRMATION:
        security_problem = TRUE;
        break;
    default:
        security_problem = FALSE;
    }

    hres = IInternetProtocolSink_QueryInterface(This->base.protocol_sink, &IID_IServiceProvider,
                                                (void**)&serv_prov);
    if(FAILED(hres)) {
        ERR("Failed to get IServiceProvider.\n");
        return E_ABORT;
    }

    if(security_problem) {
        hres = IServiceProvider_QueryService(serv_prov, &IID_IHttpSecurity, &IID_IHttpSecurity,
                                             (void**)&http_security);
        if(SUCCEEDED(hres)) {
            hres = IHttpSecurity_OnSecurityProblem(http_security, error);
            IHttpSecurity_Release(http_security);

            TRACE("OnSecurityProblem returned %08x\n", hres);

            if(hres != S_FALSE)
            {
                BOOL res = FALSE;

                IServiceProvider_Release(serv_prov);

                if(hres == S_OK) {
                    if(error == ERROR_INTERNET_SEC_CERT_DATE_INVALID)
                        res = set_security_flag(This, SECURITY_FLAG_IGNORE_CERT_DATE_INVALID);
                    else if(error == ERROR_INTERNET_SEC_CERT_CN_INVALID)
                        res = set_security_flag(This, SECURITY_FLAG_IGNORE_CERT_CN_INVALID);
                    else if(error == ERROR_INTERNET_INVALID_CA)
                        res = set_security_flag(This, SECURITY_FLAG_IGNORE_UNKNOWN_CA);

                    if(res)
                        return RPC_E_RETRY;

                    FIXME("Don't know how to ignore error %d\n", error);
                    return E_ABORT;
                }

                if(hres == E_ABORT)
                    return E_ABORT;
                if(hres == RPC_E_RETRY)
                    return RPC_E_RETRY;

                return internet_error_to_hres(error);
            }
        }
    }

    switch(error) {
    case ERROR_INTERNET_SEC_CERT_REV_FAILED:
        if(hres != S_FALSE) {
            /* Silently ignore the error. We will get more detailed error from wininet anyway. */
            set_security_flag(This, SECURITY_FLAG_IGNORE_REVOCATION);
            hres = RPC_E_RETRY;
            break;
        }
        /* fallthrough */
    default:
        hres = IServiceProvider_QueryService(serv_prov, &IID_IWindowForBindingUI, &IID_IWindowForBindingUI, (void**)&wfb_ui);
        if(SUCCEEDED(hres)) {
            const IID *iid_reason;

            if(security_problem)
                iid_reason = &IID_IHttpSecurity;
            else if(error == ERROR_INTERNET_INCORRECT_PASSWORD)
                iid_reason = &IID_IAuthenticate;
            else
                iid_reason = &IID_IWindowForBindingUI;

            hres = IWindowForBindingUI_GetWindow(wfb_ui, iid_reason, &hwnd);
            IWindowForBindingUI_Release(wfb_ui);
        }

        if(FAILED(hres)) hwnd = NULL;

        dlg_flags = FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA;
        if(This->base.bindf & BINDF_NO_UI)
            dlg_flags |= FLAGS_ERROR_UI_FLAGS_NO_UI;

        res = InternetErrorDlg(hwnd, This->base.request, error, dlg_flags, NULL);
        hres = res == ERROR_INTERNET_FORCE_RETRY || res == ERROR_SUCCESS ? RPC_E_RETRY : internet_error_to_hres(error);
    }

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

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

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

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

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

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

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

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

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

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

cleanup:

    GT_free(resp);
    GT_free(http_msg);
    if (req != NULL) {
        InternetCloseHandle(req);
    }
    if (cnx != NULL) {
        InternetCloseHandle(cnx);
    }
    GT_free(query);
    GT_free(host);
    return res;
}
Exemplo n.º 10
0
int64_t Downloader::downloadWin(Job* job, const Request& request,
        Downloader::Response* response)
{
    QUrl url = request.url;
    QString verb = request.httpMethod;
    QFile* file = request.file;
    QString* mime = &response->mimeType;
    QString* contentDisposition = &response->contentDisposition;
    HWND parentWindow = defaultPasswordWindow;
    QString* sha1 = &response->hashSum;
    bool useCache = request.useCache;
    QCryptographicHash::Algorithm alg = request.alg;
    bool keepConnection = request.keepConnection;
    int timeout = request.timeout;
    bool interactive = request.interactive;

    QString initialTitle = job->getTitle();

    job->setTitle(initialTitle + " / " + QObject::tr("Connecting"));

    if (sha1)
        sha1->clear();

    QString server = url.host();
    QString resource = url.path();
    QString encQuery = url.query(QUrl::FullyEncoded);
    if (!encQuery.isEmpty())
        resource.append('?').append(encQuery);

    QString agent("Npackd/");
    agent.append(NPACKD_VERSION);

    agent += " (compatible; MSIE 9.0)";

    HINTERNET internet = InternetOpenW((WCHAR*) agent.utf16(),
            INTERNET_OPEN_TYPE_PRECONFIG,
            0, 0, 0);

    if (internet == 0) {
        QString errMsg;
        WPMUtils::formatMessage(GetLastError(), &errMsg);
        job->setErrorMessage(errMsg);
    }

    if (job->shouldProceed()) {
        // change the timeout to 5 minutes
        DWORD rec_timeout = timeout * 1000;
        InternetSetOption(internet, INTERNET_OPTION_RECEIVE_TIMEOUT,
                &rec_timeout, sizeof(rec_timeout));

        // enable automatic gzip decoding
        const DWORD INTERNET_OPTION_HTTP_DECODING = 65;
        BOOL b = TRUE;
        InternetSetOption(internet, INTERNET_OPTION_HTTP_DECODING,
                &b, sizeof(b));

        job->setProgress(0.01);
    }

    HINTERNET hConnectHandle = 0;
    if (job->shouldProceed()) {
        INTERNET_PORT port = url.port(url.scheme() == "https" ?
                INTERNET_DEFAULT_HTTPS_PORT: INTERNET_DEFAULT_HTTP_PORT);
        hConnectHandle = InternetConnectW(internet,
                (WCHAR*) server.utf16(), port, 0, 0, INTERNET_SERVICE_HTTP, 0, 0);

        if (hConnectHandle == 0) {
            QString errMsg;
            WPMUtils::formatMessage(GetLastError(), &errMsg);
            job->setErrorMessage(errMsg);
        }
    }


    // flags: http://msdn.microsoft.com/en-us/library/aa383661(v=vs.85).aspx
    // We support accepting any mime file type since this is a simple download
    // of a file
    HINTERNET hResourceHandle = 0;
    if (job->shouldProceed()) {
        LPCTSTR ppszAcceptTypes[2];
        ppszAcceptTypes[0] = L"*/*";
        ppszAcceptTypes[1] = NULL;
        DWORD flags = (url.scheme() == "https" ? INTERNET_FLAG_SECURE : 0);
        if (keepConnection)
            flags |= INTERNET_FLAG_KEEP_CONNECTION;
        flags |= INTERNET_FLAG_RESYNCHRONIZE;
        if (!useCache)
            flags |= INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_PRAGMA_NOCACHE |
                    INTERNET_FLAG_RELOAD;
        hResourceHandle = HttpOpenRequestW(hConnectHandle,
                reinterpret_cast<LPCWSTR>(verb.utf16()),
                (WCHAR*) resource.utf16(),
                0, 0, ppszAcceptTypes,
                flags, 0);
        if (hResourceHandle == 0) {
            QString errMsg;
            WPMUtils::formatMessage(GetLastError(), &errMsg);
            job->setErrorMessage(errMsg);
        }
    }

    if (job->shouldProceed()) {
        job->checkOSCall(HttpAddRequestHeadersW(hResourceHandle,
                L"Accept-Encoding: gzip, deflate", -1,
                HTTP_ADDREQ_FLAG_ADD));
    }

    DWORD dwStatus, dwStatusSize = sizeof(dwStatus);

    // qDebug() << "download.5";
    int callNumber = 0;
    while (job->shouldProceed()) {
        // qDebug() << "download.5.1";

        DWORD sendRequestError = 0;
        if (!HttpSendRequestW(hResourceHandle,
                reinterpret_cast<LPCWSTR>(request.headers.utf16()), -1,
                const_cast<char*>(request.postData.data()),
                request.postData.length())) {
            sendRequestError = GetLastError();
        }

        // http://msdn.microsoft.com/en-us/library/aa384220(v=vs.85).aspx
        if (!HttpQueryInfo(hResourceHandle, HTTP_QUERY_FLAG_NUMBER |
                HTTP_QUERY_STATUS_CODE, &dwStatus, &dwStatusSize, NULL)) {
            QString errMsg;
            WPMUtils::formatMessage(GetLastError(), &errMsg);
            job->setErrorMessage(errMsg);
            break;
        }

        /*
        qDebug() << callNumber <<
                sendRequestError << dwStatus << request.httpMethod <<
                request.url.toString();
        */

        // 2XX
        if (sendRequestError == 0) {
            DWORD hundreds = dwStatus / 100;
            if (hundreds == 2 || hundreds == 5)
                break;
        }

        // the InternetErrorDlg calls below can either handle
        // sendRequestError <> 0 or HTTP error code <> 2xx

        void* p = 0;

        // both calls to InternetErrorDlg should be enclosed by one
        // mutex, so that only one dialog will be shown
        loginDialogMutex.lock();

        DWORD r;

        if (callNumber == 0) {
            r = InternetErrorDlg(0,
                   hResourceHandle, sendRequestError,
                    FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
                    FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS |
                    FLAGS_ERROR_UI_FLAGS_GENERATE_DATA |
                    FLAGS_ERROR_UI_FLAGS_NO_UI, &p);
            if (r == ERROR_SUCCESS && interactive)
                r = ERROR_INTERNET_FORCE_RETRY;
        } else if (interactive) {
            if (parentWindow) {
                r = InternetErrorDlg(parentWindow,
                        hResourceHandle, sendRequestError,
                        FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
                        FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS |
                        FLAGS_ERROR_UI_FLAGS_GENERATE_DATA, &p);
            } else {
                QString e = inputPassword(hConnectHandle, dwStatus);

                //qDebug() << "inputPassword: "******"HTTP status code %1")).arg(dwStatus));
            }
        } else if (r == ERROR_INTERNET_FORCE_RETRY) {
            // nothing
        } else if (r == ERROR_CANCELLED) {
            job->setErrorMessage(QObject::tr("Cancelled by the user"));
        } else if (r == ERROR_INVALID_HANDLE) {
            job->setErrorMessage(QObject::tr("Invalid handle"));
        } else {
            job->setErrorMessage(QString(
                    QObject::tr("Unknown error %1 from InternetErrorDlg")).arg(r));
        }

        loginDialogMutex.unlock();

        if (!job->shouldProceed())
            break;

        // read all the data before re-sending the request
        char smallBuffer[4 * 1024];
        while (true) {
            DWORD read;
            if (!InternetReadFile(hResourceHandle, &smallBuffer,
                    sizeof(smallBuffer), &read)) {
                QString errMsg;
                WPMUtils::formatMessage(GetLastError(), &errMsg);
                job->setErrorMessage(errMsg);
                goto out;
            }

            // qDebug() << "read some bytes " << read;
            if (read == 0)
                break;
        }

        callNumber++;
    }; // while (job->shouldProceed())

out:
    if (job->shouldProceed()) {
        // http://msdn.microsoft.com/en-us/library/aa384220(v=vs.85).aspx
        if (!HttpQueryInfo(hResourceHandle, HTTP_QUERY_FLAG_NUMBER |
                HTTP_QUERY_STATUS_CODE, &dwStatus, &dwStatusSize, NULL)) {
            QString errMsg;
            WPMUtils::formatMessage(GetLastError(), &errMsg);
            job->setErrorMessage(errMsg);
        } else {
            // 2XX
            if (dwStatus / 100 != 2) {
                job->setErrorMessage(QString(
                        QObject::tr("HTTP status code %1")).arg(dwStatus));
            }
        }
    }

    if (job->shouldProceed()) {
        job->setProgress(0.03);
        job->setTitle(initialTitle + " / " + QObject::tr("Downloading"));
    }

    // MIME type
    if (job->shouldProceed()) {
        if (mime) {
            WCHAR mimeBuffer[1024];
            DWORD bufferLength = sizeof(mimeBuffer);
            DWORD index = 0;
            if (!HttpQueryInfoW(hResourceHandle, HTTP_QUERY_CONTENT_TYPE,
                    &mimeBuffer, &bufferLength, &index)) {
                QString errMsg;
                WPMUtils::formatMessage(GetLastError(), &errMsg);
                job->setErrorMessage(errMsg);
            } else {
                mime->setUtf16((ushort*) mimeBuffer, bufferLength / 2);
            }
        }
    }

    bool gzip = false;

    // Content-Encoding
    if (job->shouldProceed()) {
        WCHAR contentEncodingBuffer[1024];
        DWORD bufferLength = sizeof(contentEncodingBuffer);
        DWORD index = 0;
        if (HttpQueryInfoW(hResourceHandle, HTTP_QUERY_CONTENT_ENCODING,
                &contentEncodingBuffer, &bufferLength, &index)) {
            QString contentEncoding;
            contentEncoding.setUtf16((ushort*) contentEncodingBuffer,
                    bufferLength / 2);
            gzip = contentEncoding == "gzip" || contentEncoding == "deflate";
        }

        job->setProgress(0.04);
    }

    // Content-Disposition
    if (job->shouldProceed()) {
        if (contentDisposition) {
            WCHAR cdBuffer[1024];
            wcscpy(cdBuffer, L"Content-Disposition");
            DWORD bufferLength = sizeof(cdBuffer);
            DWORD index = 0;
            if (HttpQueryInfoW(hResourceHandle, HTTP_QUERY_CUSTOM,
                    &cdBuffer, &bufferLength, &index)) {
                contentDisposition->setUtf16((ushort*) cdBuffer,
                        bufferLength / 2);
            }
        }
    }

    int64_t contentLength = -1;

    // content length
    if (job->shouldProceed()) {
        WCHAR contentLengthBuffer[100];
        DWORD bufferLength = sizeof(contentLengthBuffer);
        DWORD index = 0;
        if (HttpQueryInfoW(hResourceHandle, HTTP_QUERY_CONTENT_LENGTH,
                contentLengthBuffer, &bufferLength, &index)) {
            QString s;
            s.setUtf16((ushort*) contentLengthBuffer, bufferLength / 2);
            bool ok;
            contentLength = s.toLongLong(&ok, 10);
            if (!ok)
                contentLength = 0;
        }

        job->setProgress(0.05);
    }

    if (job->shouldProceed()) {
        Job* sub = job->newSubJob(0.95, QObject::tr("Reading the data"));
        readData(sub, hResourceHandle, file, sha1, gzip, contentLength, alg);
        if (!sub->getErrorMessage().isEmpty())
            job->setErrorMessage(sub->getErrorMessage());
    }

    if (hResourceHandle)
        InternetCloseHandle(hResourceHandle);
    if (hConnectHandle)
        InternetCloseHandle(hConnectHandle);
    if (internet)
        InternetCloseHandle(internet);

    if (job->shouldProceed())
        job->setProgress(1);

    job->setTitle(initialTitle);

    job->complete();

    return contentLength;
}
Exemplo n.º 11
0
HRESULT CHttpDownloader::ConnectToServer(_bstr_t &strBuffer)
{
	BOOL bResult;
	DWORD dwStatus;
	DWORD nTimeoutCounter;
	_bstr_t strMethod;
	_bstr_t strUrl = m_request.url;

	LPCTSTR szProxyName = NULL;
	if(m_ProxyType == INTERNET_OPEN_TYPE_PROXY)
		szProxyName = m_ProxyName;
	
//// InternetOpen \\\\	
	if(!m_hInternet)
		m_hInternet = InternetOpen(_T("McHttpDownloader"), m_ProxyType, szProxyName, NULL, INTERNET_FLAG_ASYNC);
	if(!m_hInternet)
	{
		strBuffer = _T("InternetOpen failed");
		return E_FAIL;
	}

	
	InternetSetStatusCallback(m_hInternet, (INTERNET_STATUS_CALLBACK)CallbackFunc);
//// InternetOpen ////	
	
	if(m_longAbort > 0)
		return E_ABORT;

//// InternetConnect \\\\	
	if(!m_hConnect)
	{
		m_hConnect = InternetConnect(m_hInternet, m_request.server, (short)m_request.port, NULL, NULL, INTERNET_SERVICE_HTTP, NULL, (DWORD)&m_context);
	}
	if(m_hConnect == NULL)
	{
		strBuffer = _T("InternetConnect failed");
		return INET_E_CANNOT_CONNECT;
	}
//// InternetConnect ////	
	
	nTimeoutCounter = 0;

NewConnect:

	strMethod = _T("GET");
	strBuffer = _T("");

//// OpenRequest \\\\	
	if(m_hRequest)
	{
		::InternetCloseHandle(m_hRequest);
		m_hRequest = NULL;
	}
	
	if(m_longAbort > 0)
		return E_ABORT;

	DWORD dwFlags = 
		INTERNET_FLAG_KEEP_CONNECTION	|
		INTERNET_FLAG_NO_CACHE_WRITE	|
		INTERNET_FLAG_RELOAD			|
		INTERNET_FLAG_PRAGMA_NOCACHE	|
		INTERNET_FLAG_NO_UI			|
		INTERNET_FLAG_NO_COOKIES		|
		INTERNET_FLAG_IGNORE_CERT_CN_INVALID  |
		INTERNET_FLAG_NO_AUTO_REDIRECT  | 
		INTERNET_FLAG_HYPERLINK |
		(m_request.bUseSSL ?
							(INTERNET_FLAG_SECURE/*|
							INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS|
							INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP*/)
							:
							0);
		
	m_context.op = HTTP_DOWNLOADER_OP_OPEN_REQUEST;
	m_hRequest = HttpOpenRequest(m_hConnect, strMethod, strUrl, _T("HTTP/1.1"), NULL, NULL, dwFlags, (DWORD)&m_context);
	if(m_hRequest == NULL)
	{
		strBuffer = _T("HttpOpenRequest failed");
		return E_FAIL;
	}

	if(m_ProxyType == INTERNET_OPEN_TYPE_PROXY)
	{
		if(GetOptionInt(IDS_NETOPTIONS,IDS_USEFIREWALL,0))
		{
			CString fireWallUser =  GetOptionString(IDS_NETOPTIONS, IDS_FIREWALLUSER, _T(""));
			CString fireWallPass = GetOptionString(IDS_NETOPTIONS, IDS_FIREWALLPASS, _T(""));

			//////////////////////////////////////////////////////////////////////////

			int HeaderLen = ATL::ProxyAuthorizationStringGetRequiredLength(fireWallUser, fireWallPass);
			LPTSTR strHeader = new TCHAR[HeaderLen+1];
			ZeroMemory(strHeader,HeaderLen+1);

			HRESULT hr = ATL::ProxyAuthorizationString(fireWallUser, fireWallPass, strHeader, &HeaderLen);

			ASSERT(hr==S_OK);

			HttpAddRequestHeaders(m_hRequest, strHeader, HeaderLen, HTTP_ADDREQ_FLAG_ADD );

			delete []strHeader;
			//////////////////////////////////////////////////////////////////////////
		}
	}
	
//// OpenRequest ////	
	
NewRequest:

	if(m_longAbort > 0)
		return E_ABORT;

	m_context.op = HTTP_DOWNLOADER_OP_SEND_REQUEST;
	bResult = HttpSendRequest(m_hRequest, NULL , 0, (LPVOID)(BYTE*)(LPCTSTR)strBuffer, lstrlen(strBuffer));
	if(!bResult && 997 == GetLastError())		// Overlapped I/O operation is in progress.
		bResult = WaitForComplete(m_dwTimeout); // Resolve host name, connect, send request, receive response.
	if(!bResult)
	{
		DWORD dwErrCode = GetLastError();
//		ATLTRACE("Send Request error = %d \r\n",dwErrCode);
		
		if(dwErrCode == 6)		// The handle is invalid.
			goto NewConnect;
		
		if(dwErrCode == ERROR_INTERNET_TIMEOUT)	// timeout
		{
			if(++nTimeoutCounter < m_dwConnectRetryCount)
				goto NewConnect;
			else
			{
				strBuffer = _T("Timeout");
				return E_FAIL;//INET_E_CONNECTION_TIMEOUT;
			}
		}

		strBuffer = _T("SendRequest failed");
		return E_FAIL;
	}
	
	dwStatus = GetHttpStatus();

	if(dwStatus == 401 || dwStatus == 407) // Denied or Proxy asks password
	{
		if(ERROR_INTERNET_FORCE_RETRY == 
		   InternetErrorDlg(GetDesktopWindow(), m_hRequest,
				ERROR_INTERNET_INCORRECT_PASSWORD,
				FLAGS_ERROR_UI_FILTER_FOR_ERRORS | 
				FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS |
				FLAGS_ERROR_UI_FLAGS_GENERATE_DATA,
				NULL))
			{
				goto NewRequest;
			}
					
	}

	if(dwStatus != 200) // Not OK
	{		
		strBuffer = _T("SendRequest returned with error");
		return INET_E_CANNOT_CONNECT;
	} 

	return S_OK;
}