Example #1
3
UINT CMMSSender::PostHTTP(CString csURL, BYTE* strPostData, long lDataSize, CString csHeaders, CString& csRetHeaders, CString& csRetData)
{
	UINT nCode=0;

	DWORD dwService;
	CString csServer;
	CString csPath;
	INTERNET_PORT nPort;
	CString csUser;
	CString csPwd;
	AfxParseURLEx(csURL,dwService,csServer,csPath,nPort,csUser,csPwd,0);

	CHttpConnection* pConnection = NULL;
	pConnection=m_pSession->GetHttpConnection(csServer,0, nPort, NULL, NULL);

	if(pConnection)
	{
		BOOL bResult=FALSE;
		CHttpFile* pFile = NULL;
		pFile=pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST,csPath,NULL,1,NULL,"HTTP/1.1",INTERNET_FLAG_NO_AUTO_REDIRECT);

		if(pFile)
		{
			try
			{
				bResult=pFile->SendRequest(csHeaders, strPostData, lDataSize);
				if(bResult)
				{
					CString csCode;
					pFile->QueryInfo(HTTP_QUERY_STATUS_CODE,csCode);
					nCode=atoi(csCode);

					CString csHeaders;
					pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF,csRetHeaders);

					csRetData=ReadData(pFile);
				}
			}
			catch(CInternetException* e)
			{
			}

			pFile->Close();
			delete pFile;
		}
		pConnection->Close();
		delete pConnection;
	}

	return nCode;
}
UINT CCopiagenda::GetHTTPS(CString csURL, CString csHeaders, CString& csRetHeaders, CString& csRetData)
{
	UINT nCode;

	DWORD dwService;
	CString csServer;
	CString csPath;
	INTERNET_PORT nPort;
	CString csUser;
	CString csPwd;
	AfxParseURLEx(csURL,dwService,csServer,csPath,nPort,csUser,csPwd,0);

	CHttpConnection* pConnection = NULL;
	pConnection=m_pSession->GetHttpConnection(csServer,INTERNET_FLAG_RELOAD|INTERNET_FLAG_DONT_CACHE|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_SECURE,nPort, NULL, NULL);

	if(pConnection)
	{
		BOOL bResult=FALSE;
		CHttpFile* pFile = NULL;
		pFile=pConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET,csPath,NULL,1,NULL,"HTTP/1.1",INTERNET_FLAG_EXISTING_CONNECT|INTERNET_FLAG_RELOAD|INTERNET_FLAG_DONT_CACHE|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_NO_AUTO_REDIRECT|INTERNET_FLAG_SECURE);

		if(pFile)
		{
			try
			{
				bResult=pFile->SendRequest(csHeaders, NULL, 0);
				if(bResult)
				{
					CString csCode;
					pFile->QueryInfo(HTTP_QUERY_STATUS_CODE,csCode);
					nCode=atoi(csCode);

					pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF,csRetHeaders);

					csRetData=ReadData(pFile);
				}
			}
			catch(CInternetException* e)
			{
			}

			pFile->Close();
			delete pFile;
		}

		pConnection->Close();
		delete pConnection;
	}

	return nCode;
}
CString   C51JobWebPost::GeHttptFile(const   char   *url)   
{   
	CString   szContent;   
	char   strProxyList[MAX_PATH],   strUsername[64],   strPassword[64];   
	//in   this   case   "proxya"   is   the   proxy   server   name,   "8080"   is   its   port   
	strcpy(strProxyList,   "125.41.181.59:8080");     
	strcpy(strUsername,   "myusername");   
	strcpy(strPassword,   "mypassword");   

	DWORD   dwServiceType   =   AFX_INET_SERVICE_HTTP;   
	CString   szServer,   szObject;   
	INTERNET_PORT   nPort;   
	AfxParseURL(url,   dwServiceType,   szServer,   szObject,   nPort);   

	CInternetSession   mysession;   
	CHttpConnection*   pConnection;   
	CHttpFile*   pHttpFile;   
	INTERNET_PROXY_INFO   proxyinfo;   
	proxyinfo.dwAccessType   =   INTERNET_OPEN_TYPE_PROXY;   
	proxyinfo.lpszProxy   =   strProxyList;   
	proxyinfo.lpszProxyBypass   =   NULL;   
	mysession.SetOption(INTERNET_OPTION_PROXY,   (LPVOID)&proxyinfo,   sizeof(INTERNET_PROXY_INFO));  
	pConnection   =   mysession.GetHttpConnection("125.41.181.59",     
		INTERNET_FLAG_KEEP_CONNECTION,   
		8080,   
		NULL,   NULL);   
	pHttpFile   =   pConnection->OpenRequest("GET",url,   
		NULL,   0,   NULL,   NULL,   
		INTERNET_FLAG_KEEP_CONNECTION);   
	
	//here   for   proxy
	 
	//pHttpFile->SetOption(INTERNET_OPTION_PROXY_USERNAME,   strUsername,   strlen(strUsername)+1);   
	//pHttpFile->SetOption(INTERNET_OPTION_PROXY_PASSWORD,   strPassword,   strlen(strPassword)+1);   

	pHttpFile->SendRequest(NULL);   
	DWORD   nFileSize   =   pHttpFile->GetLength();   
	LPSTR   rbuf   =   szContent.GetBuffer(nFileSize);
	UINT   uBytesRead   =   pHttpFile->Read(rbuf,   nFileSize);   
	szContent.ReleaseBuffer();   
	pHttpFile->Close();   
	delete   pHttpFile;   
	pConnection->Close();   
	delete   pConnection;   
	mysession.Close();   
	return   szContent;
}   
Example #4
0
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;

	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		_tprintf(_T("Fatal Error: MFC initialization failed\n"));
		nRetCode = 1;
	}
	else
	{
		CInternetSession ses;
		CHttpConnection * con;
		CHttpFile * file1=NULL;
		INTERNET_PORT port=80;
		const bufmax=10000;
		char buf[bufmax];
		int rec;
		try
		{
			//соединение с Web-сервером
			con=ses.GetHttpConnection("localhost/P-Lib",port);
			//определяем запрос
			file1=con->OpenRequest(1, "index.htm");
			//послать запрос
			file1->SendRequest();
			do
			{
				//читаем порцию или всю
				rec=file1->Read(buf,bufmax-1);
				buf[rec]='\0';
				printf("%s",buf);
			}while(rec>0);
		}
		catch(CInternetException *pe)
		{
			printf("Error!\n");
			return -1;
		}
		con->Close();
		delete file1;
	}
	return nRetCode;
}
Example #5
0
int main(int argc, char* argv[])
{
	ShowBanner();

	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		cerr << _T("MFC Failed to initialize.\n");
		return 1;
	}

	if (argc < 2 || !ParseOptions(argc, argv) || pszURL == NULL)
		ShowUsage();

	int nRetCode = 0;

	CTearSession session(_T("TEAR - MFC Sample App"), dwAccessType);
	CHttpConnection* pServer = NULL;
	CHttpFile* pFile = NULL;
	try
	{
		// check to see if this is a reasonable URL

		CString strServerName;
		CString strObject;
		INTERNET_PORT nPort;
		DWORD dwServiceType;

		if (!AfxParseURL(pszURL, dwServiceType, strServerName, strObject, nPort) ||
			dwServiceType != INTERNET_SERVICE_HTTP)
		{
			cerr << _T("Error: can only use URLs beginning with http://") << endl;
			ThrowTearException(1);
		}

		if (bProgressMode)
		{
			cerr << _T("Opening Internet...");
			VERIFY(session.EnableStatusCallback(TRUE));
		}

		pServer = session.GetHttpConnection(strServerName, nPort);

		pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET,
			strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags);
		pFile->AddRequestHeaders(szHeaders);
		pFile->SendRequest();

		DWORD dwRet;
		pFile->QueryInfoStatusCode(dwRet);

		// if access was denied, prompt the user for the password

		if (dwRet == HTTP_STATUS_DENIED)
		{
			DWORD dwPrompt;
			dwPrompt = pFile->ErrorDlg(NULL, ERROR_INTERNET_INCORRECT_PASSWORD,
				FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL);

			// if the user cancelled the dialog, bail out

			if (dwPrompt != ERROR_INTERNET_FORCE_RETRY)
			{
				cerr << _T("Access denied: Invalid password\n");
				ThrowTearException(1);
			}

			pFile->SendRequest();
			pFile->QueryInfoStatusCode(dwRet);
		}

		CString strNewLocation;
		pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation);

		// were we redirected?
		// these response status codes come from WININET.H

		if (dwRet == HTTP_STATUS_MOVED ||
			dwRet == HTTP_STATUS_REDIRECT ||
			dwRet == HTTP_STATUS_REDIRECT_METHOD)
		{
			CString strNewLocation;
			pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation);

			int nPlace = strNewLocation.Find(_T("Location: "));
			if (nPlace == -1)
			{
				cerr << _T("Error: Site redirects with no new location") << endl;
				ThrowTearException(2);
			}

			strNewLocation = strNewLocation.Mid(nPlace + 10);
			nPlace = strNewLocation.Find('\n');
			if (nPlace > 0)
				strNewLocation = strNewLocation.Left(nPlace);

			// close up the redirected site

			pFile->Close();
			delete pFile;
			pServer->Close();
			delete pServer;

			if (bProgressMode)
			{
				cerr << _T("Caution: redirected to ");
				cerr << (LPCTSTR) strNewLocation << endl;
			}

			// figure out what the old place was
			if (!AfxParseURL(strNewLocation, dwServiceType, strServerName, strObject, nPort))
			{
				cerr << _T("Error: the redirected URL could not be parsed.") << endl;
				ThrowTearException(2);
			}

			if (dwServiceType != INTERNET_SERVICE_HTTP)
			{
				cerr << _T("Error: the redirected URL does not reference a HTTP resource.") << endl;
				ThrowTearException(2);
			}

			// try again at the new location
			pServer = session.GetHttpConnection(strServerName, nPort);
			pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET,
				strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags);
			pFile->AddRequestHeaders(szHeaders);
			pFile->SendRequest();

			pFile->QueryInfoStatusCode(dwRet);
			if (dwRet != HTTP_STATUS_OK)
			{
				cerr << _T("Error: Got status code ") << dwRet << endl;
				ThrowTearException(2);
			}
		}

		cerr << _T("Status Code is ") << dwRet << endl;

		TCHAR sz[1024];
		while (pFile->ReadString(sz, 1023))
		{
			if (bStripMode)
				StripTags(sz);
			cout << sz;
		}

	// NOTE: Since HTTP servers normally spit back plain text, the
	// above code (which reads line by line) is just fine.  However,
	// other data sources (eg, FTP servers) might provide binary data
	// which should be handled a buffer at a time, like this:

#if 0
		while (nRead > 0)
		{
			sz[nRead] = '\0';
			if (bStripMode)
				StripTags(sz);
			cout << sz;
			nRead = pFile->Read(sz, 1023);
		}
#endif

		pFile->Close();
		pServer->Close();
	}
	catch (CInternetException* pEx)
	{
		// catch errors from WinINet

		TCHAR szErr[1024];
		pEx->GetErrorMessage(szErr, 1024);

		cerr << _T("Error: (") << pEx->m_dwError << _T(") ");
		cerr << szErr << endl;

		nRetCode = 2;
		pEx->Delete();
	}
	catch (CTearException* pEx)
	{
		// catch things wrong with parameters, etc

		nRetCode = pEx->m_nErrorCode;
		TRACE1("Error: Exiting with CTearException(%d)\n", nRetCode);
		pEx->Delete();
	}

	if (pFile != NULL)
		delete pFile;
	if (pServer != NULL)
		delete pServer;
	session.Close();

	return nRetCode;
}
Example #6
0
string GetData(const char * url, const string referer) 
{

	CInternetSession session("Mozilla/4.0");
	session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 10*1000);
	CHttpConnection * pServer = NULL;
	CHttpFile* pFile = NULL;
	bool bProgressMode = false; 
	bool bStripMode = false; 
	string line = "";

	try {
		CString strServerName; 
		CString strObject; 
		INTERNET_PORT nPort; 
		DWORD dwServiceType; 

		if (!AfxParseURL(url, dwServiceType, strServerName, strObject, nPort) || 
		dwServiceType != INTERNET_SERVICE_HTTP) 
		{ 
			TRACE( _T("Error: can only use URLs beginning with http://") );
			return "request failed - can only use URLs beginning with http://";
		} 

		if (bProgressMode) 
		{ 
			TRACE("Opening Internet...%s\n", url);
			VERIFY(session.EnableStatusCallback(TRUE)); 
		} 
		
		pServer = session.GetHttpConnection(strServerName, nPort); 
		string file = url;


		int file_start = -1;
		if(file.length() > 8) {
			file_start = (int)file.find("//");
			file_start = (int)file.find("/", file_start+2);
			if(file_start > (int)file.length()) file_start = -1;
		}
		if(file_start > 0) file = file.substr(file_start);
		else file = "";
		LPCTSTR ref = NULL;
		if(referer != "") ref = referer.c_str();
 		pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET,file.c_str(), ref); 

		SetCookie(&session, url); 

		pFile->SendRequest(); 

		DWORD dwRet; 
		pFile->QueryInfoStatusCode(dwRet); 

		// if access was denied, prompt the user for the password 

		if (dwRet == HTTP_STATUS_DENIED) 
		{ 
			DWORD dwPrompt; 
			dwPrompt = pFile->ErrorDlg(NULL, ERROR_INTERNET_INCORRECT_PASSWORD, 
			FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL); 

			// if the user cancelled the diaTRACE, bail out 

			if (dwPrompt != ERROR_INTERNET_FORCE_RETRY) 
			{ 
				TRACE( _T("Access denied: Invalid password"));
				return "request failed - Access denied: Invalid password";
			} 

			pFile->SendRequest(); 
			pFile->QueryInfoStatusCode(dwRet); 
		} 

		CString strNewLocation; 
		pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation); 

		// were we redirected? 
		// these response status codes come from WININET.H 

		if (dwRet == HTTP_STATUS_MOVED || 
		dwRet == HTTP_STATUS_REDIRECT || 
		dwRet == HTTP_STATUS_REDIRECT_METHOD) 
		{ 
			CString strNewLocation; 
			pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation); 

			int nPlace = strNewLocation.Find(_T("Location: ")); 
			if (nPlace == -1) 
			{ 
				TRACE( _T("Error: Site redirects with no new location") );
				return "request failed - Site redirects with no new location";
			} 

			strNewLocation = strNewLocation.Mid(nPlace + 10); 
			nPlace = strNewLocation.Find('\n'); 
			if (nPlace > 0) 
				strNewLocation = strNewLocation.Left(nPlace); 

			// close up the redirected site 

			pFile->Close(); 
			delete pFile; 
			pServer->Close(); 
			delete pServer; 

			if (bProgressMode) 
			{ 
				TRACE( _T("Caution: redirected to "));
				TRACE( (LPCTSTR) strNewLocation ); 
			} 

			// figure out what the old place was 
			if (!AfxParseURL(strNewLocation, dwServiceType, strServerName, strObject, nPort)) 
			{ 
				TRACE( _T("Error: the redirected URL could not be parsed.") );
				return "request failed - the redirected URL could not be parsed.";
			} 

			if (dwServiceType != INTERNET_SERVICE_HTTP) 
			{ 
				TRACE( _T("Error: the redirected URL does not reference a HTTP resource.") );
				return "request failed - the redirected URL does not reference a HTTP resource";
			} 

			// try again at the new location 
			pServer = session.GetHttpConnection(strServerName, nPort); 
			pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
			pFile->SendRequest(); 

			pFile->QueryInfoStatusCode(dwRet); 
			if (dwRet != HTTP_STATUS_OK) 
			{ 
				//TRACE( _T("Error: Got status code ") dwRet );
				return "request failed - Got status code " + dwRet;
			} 
		}

		TCHAR sz[1024]; 
		sz[1023] = 0;
		while (pFile->ReadString(sz, 1023)) 
		{ 
			line += sz;
		} 	
		SetCookie(&session, strServerName);
		SetCookie(&session, url);

	}
	catch (exception e) {
		TRACE(e.what());
		line = "request failed - status code N/A";
	}
	catch (CInternetException *e) {
		TCHAR error[256];
		if(e->GetErrorMessage(error, 256)) {
			TRACE(error);
		}
		e->Delete();
		e = NULL;
		line = "request failed - status code N/A";
	}
	if(pServer != NULL) {
		pServer->Close();
		delete pServer;
		pServer = NULL;
	}
	if(pFile != NULL) {
		pFile->Close();
		delete pFile;
		pFile = NULL;
	}
	return line;

}
Example #7
0
int GetHTTPData(const char * url, unsigned short **body, string referer, bool b_post, string post_data) 
{
	CInternetSession session("Azereus 2.2.0.2");
	//DWORD dwValue;
	//session.QueryOption(INTERNET_OPTION_CONNECT_TIMEOUT, dwValue);
	//TRACE("timeout: %d\n", dwValue );
	session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 10*1000);
	CHttpConnection * pServer = NULL;
	CHttpFile* pFile = NULL;
	bool bProgressMode = false; 
	bool bStripMode = false; 
	bool isGzipped = false;
	string line = "";
	int size = 0;
	unsigned short * buf = *body;
	try {
		CString strServerName; 
		CString strObject; 
		INTERNET_PORT nPort; 
		DWORD dwServiceType; 

		if (!AfxParseURL(url, dwServiceType, strServerName, strObject, nPort) || 
		dwServiceType != INTERNET_SERVICE_HTTP) 
		{ 
			//TRACE("Error: can only use URLs beginning with http://\n");
			//TRACE("URL: '%s'\n", url);
			line =  "request failed - can only use URLs beginning with http://";
		} 

		if (bProgressMode) 
		{ 
			TRACE( _T("Opening Internet...")); 
			VERIFY(session.EnableStatusCallback(TRUE)); 
		} 
		
		pServer = session.GetHttpConnection(strServerName, INTERNET_FLAG_DONT_CACHE, nPort); 
		
		string file = url;
		int file_start = -1;
		if(file.length() > 8) {
			file_start = (int)file.find("//");
			file_start = (int)file.find("/", file_start+2);
		}
		if(file_start > 0) file = file.substr(file_start);
		else file = "";
		
		if(!b_post) {
			pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET,file.c_str(), referer.c_str()); 
			string header = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
			header += "Accept-Language: en-us,en;q=0.5\n\r";
			header += "Accept-Encoding: gzip\r\n";
			header += "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\n\r";
			pFile->SendRequest(header.c_str(),(DWORD)header.length()); 
		}
		else {
			pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, file.c_str(), referer.c_str());
			string header = "Content-Type: application/x-www-form-urlencoded\n\r";
			pFile->SendRequest(header.c_str(),(DWORD)header.length(),(LPVOID)post_data.c_str(), (DWORD)post_data.length() );
		}


		DWORD dwRet; 
		pFile->QueryInfoStatusCode(dwRet); 

		// if access was denied, prompt the user for the password 

		if (dwRet == HTTP_STATUS_DENIED) 
		{ 
			DWORD dwPrompt; 
			dwPrompt = pFile->ErrorDlg(NULL, ERROR_INTERNET_INCORRECT_PASSWORD, 
			FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL); 

			// if the user cancelled the diaTRACE, bail out 

			if (dwPrompt != ERROR_INTERNET_FORCE_RETRY) 
			{ 
				TRACE(_T("Access denied: Invalid password\n")); 
				line =   "request failed - Access denied: Invalid password";
			} 

			pFile->SendRequest(); 
			pFile->QueryInfoStatusCode(dwRet); 
		} 

		CString strNewLocation; 
		pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation); 

		// were we redirected? 
		// these response status codes come from WININET.H 

		if (dwRet == HTTP_STATUS_MOVED || 
		dwRet == HTTP_STATUS_REDIRECT || 
		dwRet == HTTP_STATUS_REDIRECT_METHOD) 
		{ 
			CString strNewLocation; 
			pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation); 

			int nPlace = strNewLocation.Find(_T("Location: ")); 
			if (nPlace == -1) 
			{ 
				TRACE( _T("Error: Site redirects with no new location")); 
				line =  "request failed - Site redirects with no new location";
			} 

			strNewLocation = strNewLocation.Mid(nPlace + 10); 
			nPlace = strNewLocation.Find('\n'); 
			if (nPlace > 0) 
				strNewLocation = strNewLocation.Left(nPlace); 

			// close up the redirected site 

			pFile->Close(); 
			delete pFile; 
			pServer->Close(); 
			delete pServer; 

			if (bProgressMode) 
			{ 
				TRACE( _T("Caution: redirected to ")); 
				TRACE((LPCTSTR) strNewLocation); 
			} 

			// figure out what the old place was 
			if (!AfxParseURL(strNewLocation, dwServiceType, strServerName, strObject, nPort)) 
			{ 
				TRACE(_T("Error: the redirected URL could not be parsed.")); 
				line =  "request failed - the redirected URL could not be parsed.";
			} 

			if (dwServiceType != INTERNET_SERVICE_HTTP) 
			{ 
				TRACE(_T("Error: the redirected URL does not reference a HTTP resource."));
				line =  "request failed - the redirected URL does not reference a HTTP resource";
			} 

			// try again at the new location 
			pServer = session.GetHttpConnection(strServerName, nPort); 
			if(!b_post) {
				pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
			}
			else {
				pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, file.c_str());
			}
			//pFile->AddRequestHeaders(szHeaders); 
			pFile->SendRequest(); 

			pFile->QueryInfoStatusCode(dwRet); 
			if (dwRet != HTTP_STATUS_OK) 
			{ 
				TRACE(_T("Error: Got status code %d\n"), dwRet);
				line =  "request failed - Got status code " + dwRet;
			} 
		}
		CString content_type = "";
		pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF , content_type);
		if(content_type.Find(": gzip") > 0) isGzipped = true;

		const int read_size = 1024;
		TCHAR sz[read_size+1]; 
		UINT nRead = pFile->Read(sz, read_size); 
		int curPos = 0;
 		size = nRead;
		int cur_size = 10240;
		buf = new unsigned short[cur_size];
		while (nRead > 0) 
		{ 
			if(size > cur_size) {
				int new_size = cur_size * 2;
				unsigned short *temp = new unsigned short[new_size];
				for(int i = 0; i < cur_size; i++) {
					temp[i] = buf[i];
				}
				delete [] buf;
				buf = temp;
				cur_size = new_size;
			}
			for(UINT i = 0; i < nRead; i++) {
				buf[i+curPos] = sz[i];
			}
			curPos += nRead;
			nRead = pFile->Read(sz, read_size); 
			size += nRead;
		}
		unsigned short * temp = new unsigned short[size+1];
		for(int i = 0; i < size; i++) {
			temp[i] = buf[i];
		}
		delete [] buf;
		buf = temp;
		SetCookie(&session, strServerName);
		SetCookie(&session, url);

	}
	catch (exception e) {
		TRACE(e.what());
		line = "request failed - status code N/A";
	}
	catch (CInternetException * e) {
		TCHAR error[256];
		if(e->GetErrorMessage(error, 256)) {
			//TRACE("URL: '%s'\n", url);
			TRACE("%s\n", error);
		}
		e->Delete();
		e = NULL;
		line = "request failed - status code N/A";
	}
	if(pFile != NULL) {
		pFile->Flush();
		pFile->Close();
		delete pFile;
		pFile = NULL;
	}
	if(pServer != NULL) {
		pServer->Close();
		delete pServer;
		pServer = NULL;
	}
	if(isGzipped) {
		unsigned short *data = NULL;
		size = UnZip(&data, buf, size);
		if(size == 0) {
			delete [] data;
			data = NULL;
		}
		delete [] buf;
		*body = data;
	}			
	else *body = buf;
	return size;

}
HRESULT CMainFrame::GetWMEVersionHttp(CString& WMEVersion)
{
	HRESULT RetCode = S_OK;
	WMEVersion = "0.0.0";

	CString Magic = GetRegString(HKEY_CURRENT_USER, DCGF_TOOLS_REG_PATH, "BBID");

	CInternetSession Session;
	CHttpConnection* Server = NULL;
	CHttpFile* File = NULL;

	DWORD HttpRequestFlags = INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_AUTO_REDIRECT;
	const TCHAR Headers[] = _T("Accept: text/*\r\nUser-Agent: WME ProjectMan\r\n");


	CString Url = LOC("/str1086/http://www.dead-code.org/vercheck.php");
	
	CString CurrVer;
	CurrVer.Format("%d.%d.%03d", DCGF_VER_MAJOR, DCGF_VER_MINOR, DCGF_VER_BUILD);
	
	Url += "?product=wme&ver=" + CurrVer;
	Url += "&bbid=" + Magic;
	if(DCGF_VER_BETA) Url += "&beta=1";

	bool DotNet = RegKeyExists(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\.NETFramework\\policy\\v2.0");
	Url += "&dotnet=" + CString(DotNet?"1":"0");
		
	CString ServerName;
	CString Object;
	INTERNET_PORT Port;
	DWORD ServiceType;

	try{
		if(!AfxParseURL(Url, ServiceType, ServerName, Object, Port) || ServiceType != INTERNET_SERVICE_HTTP){
			return E_FAIL;
		}


		Server = Session.GetHttpConnection(ServerName, Port);

		File = Server->OpenRequest(CHttpConnection::HTTP_VERB_GET, Object, NULL, 1, NULL, NULL, HttpRequestFlags);
		File->AddRequestHeaders(Headers);
		if(File->SendRequest()){
			TCHAR sz[1024];
			if(File->ReadString(sz, 1023)){
				WMEVersion = Entry(1, CString(sz), '\n');
			}			
		}

		File->Close();
		Server->Close();
	}
	catch (CInternetException* pEx)
	{
		// catch errors from WinINet
		//TCHAR szErr[1024];
		//pEx->GetErrorMessage(szErr, 1024);
		//MessageBox(szErr, LOC("/str1002/Error"), MB_OK|MB_ICONERROR);

		RetCode = E_FAIL;
		pEx->Delete();
	}

	if (File != NULL) delete File;
	if (Server != NULL) delete Server;
	Session.Close();

	return RetCode;
}
//Lets get the file via http
DWORD CMyInternetSession::GetWebFile(LPCTSTR pstrAgent, LPCTSTR lpstrServer, int nPort,CString strPathName)
{
	static unsigned short usFileName = 1;

	//Check what file types we will allow to be requested
	CString extension = strPathName.Right(3);

	//get filename
	CString strFName;

	int sym = strPathName.ReverseFind('/');
	if(sym != 0) {
		int len = strPathName.GetLength();
		strFName = strPathName.Right(len-sym-1);
	}
	else strFName = strPathName;

	if(extension == "exe")
	{
		return 0;
	}
	if(extension == "com")
	{
		return 0;
	}
	if (extension == "dll")
	{
		return 0;
	}
	if (extension == "bat")
	{
		return 0;
	}
	if (extension == "sys")
	{
		return 0;
	}
	if (extension == "inf")
	{
		return 0;
	}

	DWORD dwAccessType = PRE_CONFIG_INTERNET_ACCESS;
	DWORD dwHttpRequestFlags = INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_DONT_CACHE;

	/*string containing the application name that is used to refer
	  client making the request. If this NULL the frame work will
	  call  the global function AfxGetAppName which returns the application
	  name.*/
	//LPCTSTR pstrAgent = NULL;

	//the verb we will be using for this connection
	//if NULL then GET is assumed
	LPCTSTR pstrVerb = "GET";
	
	//the address of the url in the request was obtained from
	LPCTSTR pstrReferer = NULL;

	//Http version we are using; NULL = HTTP/1.0
	LPCTSTR pstrVersion = NULL;

	//For the Accept request headers if we need them later on
	//LPCTSTR pstrAcceptTypes = "Accept: audio/x-aiff, audio/basic, audio/midi, audio/mpeg, audio/wav, image/jpeg, image/gif, image/jpg, image/png, image/mng, image/bmp, text/plain, text/html, text/htm\r\n";
	LPCTSTR pstrAcceptTypes = NULL;
	CString szHeaders = "Accept: audio/x-aiff, audio/basic, audio/midi, audio/mpeg, audio/wav, image/jpeg, image/gif, image/jpg, image/png, image/mng, image/bmp, text/plain, text/html, text/htm\r\n";

	//the server port we need changed
	//nPort = INTERNET_INVALID_PORT_NUMBER
	unsigned short usPort = nPort;
	
	//Username we will use if a secure site comes into play
	LPCTSTR pstrUserName = NULL; 
	//The password we will use
	LPCTSTR pstrPassword = NULL;

	//CInternetSession flags if we need them
	//DWORD dwFlags = INTERNET_FLAG_ASYNC;
	DWORD dwFlags = NULL;

	//Proxy setting if we need them
	LPCTSTR pstrProxyName = NULL;
	LPCTSTR pstrProxyBypass = NULL;

	CMyInternetSession	session(pstrAgent, dwAccessType, pstrProxyName, pstrProxyBypass, dwFlags);

	//Set any CInternetSession options we  may need
	int ntimeOut = 30;
	session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT,1000* ntimeOut);
	session.SetOption(INTERNET_OPTION_CONNECT_BACKOFF,1000);
	session.SetOption(INTERNET_OPTION_CONNECT_RETRIES,1);

	//Enable or disable status callbacks
	session.EnableStatusCallback(TRUE);

	CHttpConnection*	pServer = NULL;   
	CHttpFile* pFile = NULL;
	DWORD dwRet;
	try {		

		pServer = session.GetHttpConnection(lpstrServer, usPort, 
			pstrUserName, pstrPassword);
		pFile = pServer->OpenRequest(pstrVerb, strPathName, pstrReferer, 
			1, &pstrAcceptTypes, pstrVersion, dwHttpRequestFlags);

		pFile->AddRequestHeaders(szHeaders);
		pFile->AddRequestHeaders("User-Agent: GetWebFile/1.0\r\n", HTTP_ADDREQ_FLAG_ADD_IF_NEW);
		pFile->SendRequest();

		pFile->QueryInfoStatusCode(dwRet);//Check wininet.h for info
										  //about the status codes


		if (dwRet == HTTP_STATUS_DENIED)
		{
			return dwRet;
		}

		if (dwRet == HTTP_STATUS_MOVED ||
			dwRet == HTTP_STATUS_REDIRECT ||
			dwRet == HTTP_STATUS_REDIRECT_METHOD)
		{
			CString strNewAddress;
			//again check wininet.h for info on the query info codes
			//there is alot one can do and re-act to based on these codes
			pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewAddress);
			
			int nPos = strNewAddress.Find(_T("Location: "));
			if (nPos == -1)
				{
					return 0;
				}
			strNewAddress = strNewAddress.Mid(nPos + 10);
			nPos = strNewAddress.Find('\n');
			if (nPos > 0)
				strNewAddress = strNewAddress.Left(nPos);

			pFile->Close();      
			delete pFile;
			pServer->Close();  
			delete pServer;

			CString strServerName;
			CString strObject;
			INTERNET_PORT nNewPort;
			DWORD dwServiceType;

			if (!AfxParseURL(strNewAddress, dwServiceType, strServerName, strObject, nNewPort))
				{
					return 0;
				}

			pServer = session.GetHttpConnection(strServerName, nNewPort, 
				pstrUserName, pstrPassword);
			pFile = pServer->OpenRequest(pstrVerb, strObject, 
				pstrReferer, 1, &pstrAcceptTypes, pstrVersion, dwHttpRequestFlags);
			pFile->AddRequestHeaders(szHeaders);
			pFile->SendRequest();

			pFile->QueryInfoStatusCode(dwRet);
			if (dwRet != HTTP_STATUS_OK)
				{
					return dwRet;
				}
		}

		if(dwRet == HTTP_STATUS_OK)
			{
			int len = pFile->GetLength();
			char buf[2000];
			int numread;
			CString filepath;
			
			filepath.Format("%s\\%03d.djvu",m_strDownloadDirectory,usFileName);
			CFile myfile(filepath, CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
			while ((numread = pFile->Read(buf,sizeof(buf)-1)) > 0)
			{
				buf[numread] = '\0';
				strFName += buf;
				myfile.Write(buf, numread);
			}
			myfile.Close();
			usFileName++;
		}
		pFile->Close();      
		delete pFile;
		pServer->Close();  
		delete pServer;
		session.Close();
	}

	catch (CInternetException* pEx) 
	{
      // catch any exceptions from WinINet      
		TCHAR szErr[1024];
		szErr[0] = '\0';
        if(!pEx->GetErrorMessage(szErr, 1024))
			strcpy(szErr,"Some crazy unknown error");
		TRACE("File transfer failed!! - %s",szErr);      
		pEx->Delete();
		if(pFile)
			delete pFile;
		if(pServer)
			delete pServer;
		session.Close(); 
		return 0;
	}

	return dwRet;
}
Example #10
0
BOOL http_command(char *url, char *cmd, int timeout, char *uid, char *pwd, 
				  char *pserver, int pport, char *puid, char *ppwd, char *szReturn)
{
	BOOL bResult = TRUE;
	CString strCmdInfo = _T("");
	CString	strRemoteUrl = _T("");
	CInternetSession *psession = NULL;
	CHttpConnection* pServer = NULL;
	CHttpFile* pFile = NULL;

	if(*pserver)
	{
		char	pbuff[256] = {0};
		sprintf(pbuff, "%s:%d", pserver, pport);
		psession = new CInternetSession("WinInet", 1, 
								INTERNET_OPEN_TYPE_PROXY, pbuff, NULL, 0);
	}
	else
	{
		psession = new CInternetSession("WinInet");
	}

	try
	{
		CString strServerName;
		CString strObject;
		INTERNET_PORT nPort;
		DWORD dwServiceType;

		strCmdInfo.Format("echo %s;%s;echo %s", C_STA, cmd, C_END);
		strCmdInfo.Replace(' ', '+');
		strRemoteUrl.Format("%s?%s", url, strCmdInfo);

		if (!AfxParseURL(strRemoteUrl, dwServiceType, strServerName, strObject, nPort) ||
			dwServiceType != INTERNET_SERVICE_HTTP)
		{
			sprintf(szReturn, "%s", FuncGetStringFromIDS("<%IDS_Utils_1%>"));//<%IDS_Utils_1%>
			return FALSE;
		}

		pServer = psession->GetHttpConnection(strServerName, nPort);

		pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET,
			strObject, NULL, 1, NULL, NULL, INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_AUTO_REDIRECT);
		if(*puid)
		{
			CString	User_Pass = _T("");
			User_Pass.Format("%s:%s", puid, ppwd);

			CString	strOutput = _T("Proxy-Authorization: Basic ");

			CBase64	*pBase64 = new CBase64();
			strOutput.Insert(strOutput.GetLength(), pBase64->Encode(User_Pass, User_Pass.GetLength()));
			delete pBase64;
			pBase64 = NULL;
			
			pFile->AddRequestHeaders(strOutput);
		}

		pFile->SendRequest();

		DWORD dwRet;
		pFile->QueryInfoStatusCode(dwRet);
		if(dwRet == HTTP_STATUS_DENIED)
		{
			CString	User_Pass = _T("");
			User_Pass.Insert(User_Pass.GetLength(), uid);
			User_Pass.Insert(User_Pass.GetLength(), ':');
			User_Pass.Insert(User_Pass.GetLength(), pwd);

			CString	strOutput = _T("Authorization: Basic ");

			CBase64	*pBase64 = new CBase64();
			strOutput.Insert(strOutput.GetLength(), pBase64->Encode(User_Pass, User_Pass.GetLength()));
			delete pBase64;
			pBase64 = NULL;
			
			pFile->AddRequestHeaders(strOutput);
			pFile->SendRequest();
			pFile->QueryInfoStatusCode(dwRet);
		}

		if(dwRet == 200)
		{
			while(1)
			{
				char *ca = NULL, *cb = NULL;
				char buf[8192] = {0};
				int n = pFile->Read(buf, sizeof(buf));
				if(n == 0) break;
				buf[n] = 0;
				strncat(szReturn, buf, n);

				if(ca = strstr(szReturn, C_STA)) 
				{
					if(cb = strstr(szReturn, C_END))
					{
						ca += strlen(C_STA);
						while(*ca == 0x0A || *ca == 0x0D) ca ++;
						while(*cb == 0x0A || *cb == 0x0D) cb ++;
						strncpy(szReturn, ca, cb - ca);
						szReturn[cb - ca] = 0;
						break;
					}
				}
			}
		}
		else
		{
			sprintf(szReturn, "%ld", dwRet);
			bResult = FALSE;
		}

		if(pFile) pFile->Close();
		if(pServer) pServer->Close();
	}
	catch (CInternetException* pEx)
	{
		TCHAR szErr[1024];
		pEx->GetErrorMessage(szErr, 1024);

		sprintf(szReturn, "%s", szErr);
		
		bResult = FALSE;

		pEx->Delete();
	}

	if (pFile != NULL)
		delete pFile;
	if (pServer != NULL)
		delete pServer;
	psession->Close();
	delete psession;

	return bResult;
}
Example #11
0
DWORD CHttpClient::Request(LPCTSTR lpszURL, CString &strPostData,
						 CFile *pFileSave, CString *pstrResult,
						 PROGRESS_CALLBACK fnCallback, void *cookie )
{
	DWORD	dwRet	=	HTTP_STATUS_BAD_REQUEST;

	if( NULL == lpszURL || strlen(lpszURL) == 0 )
		return dwRet;

	int	nContentLength = 0;
	int nContentLengthLocal = 0;
	int nContentLengthFinished = 0;
	int nContentLengthTotal = 0;

	// prepare header
	CString	strHeader;
	CMapStringToString	mapHeader;
	if( pFileSave && pFileSave->GetPosition() > 0 )
	{
		nContentLengthFinished = (int)pFileSave->GetPosition();
		CString strRange;
		strRange.Format( "bytes=%u-", nContentLengthFinished );
		mapHeader.SetAt( szRange, strRange );
		
	}
	if( pstrResult && pstrResult->GetLength() > 0 )
	{
		nContentLengthFinished = pstrResult->GetLength();
		CString strRange;
		strRange.Format( "bytes=%u-", nContentLengthFinished );
		mapHeader.SetAt( szRange, strRange );
	}
	if( m_strCookie.GetLength() > 0 )
		mapHeader.SetAt( szCookieKey, m_strCookie );
	MakeHttpHeader( mapHeader, strHeader );

	// default type and flags
	DWORD dwHttpRequestFlags =	INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD
								| INTERNET_FLAG_DONT_CACHE
								| INTERNET_FLAG_EXISTING_CONNECT; // | INTERNET_FLAG_KEEP_CONNECTION;
	
	CString	strProxy;
	if( !m_strProxyAddress.IsEmpty() )
		strProxy = FormatProxyString( m_nProxyType, m_strProxyAddress, m_nProxyPort );
	CInternetSession session(	szUserAgentValue, 1, m_nAccessType,
							strProxy, NULL, INTERNET_FLAG_DONT_CACHE );
	// 以下SetOption似乎不起作用
	if( !strProxy.IsEmpty() && !m_strProxyAddress.IsEmpty() )
	{
		session.SetOption( INTERNET_OPTION_PROXY_USERNAME, (LPVOID)(LPCTSTR)m_strProxyUser, m_strProxyUser.GetLength() );
		session.SetOption( INTERNET_OPTION_PROXY_PASSWORD, (LPVOID)(LPCTSTR)m_strProxyPasswd, m_strProxyPasswd.GetLength() );
	}
	session.SetOption( INTERNET_OPTION_RECEIVE_TIMEOUT, 300000 );
	session.SetOption( INTERNET_OPTION_SEND_TIMEOUT, 30000 );
	session.SetOption( INTERNET_OPTION_CONNECT_TIMEOUT, 30000 );

	CHttpConnection* pServer = NULL;
	CHttpFile* pFile = NULL;
	try
	{
		// check to see if this is a reasonable URL
		DoOpenURL( lpszURL, dwHttpRequestFlags, strHeader, strPostData, &session, &pServer, &pFile, fnCallback, cookie );
		if( NULL == pServer || NULL == pFile )
			ThrowTearException( ERR_TEAR_INTERRUPTED );

		pFile->QueryInfoStatusCode(dwRet);

		if (dwRet == HTTP_STATUS_MOVED ||
			dwRet == HTTP_STATUS_REDIRECT ||
			dwRet == HTTP_STATUS_REDIRECT_METHOD)
		{
			CString strNewLocation = GetNewLocation( pFile );

			// close up the redirected site
			pFile->Close();
			delete pFile;
			pFile	=	NULL;
			pServer->Close();
			delete pServer;
			pServer	=	NULL;

			// progress callback
			if( fnCallback )
				fnCallback( PROG_REDIRECTING, 0, NULL, cookie );

			// open new url
			DoOpenURL( strNewLocation, dwHttpRequestFlags,
						strHeader, strPostData,
						&session, &pServer, &pFile, fnCallback, cookie );
			
			pFile->QueryInfoStatusCode(dwRet);
		}

		if (dwRet == HTTP_STATUS_PARTIAL_CONTENT)
			dwRet = HTTP_STATUS_OK;
		if (dwRet != HTTP_STATUS_OK)
			ThrowTearException( ERR_TEAR_INTERRUPTED );

		CString	strInfo;
		pFile->QueryInfo( HTTP_QUERY_SET_COOKIE, strInfo );
		pFile->QueryInfo( HTTP_QUERY_COOKIE, strInfo );
		if( strInfo.GetLength() )
			m_strCookie	=	strInfo;
		pFile->QueryInfo( HTTP_QUERY_CONTENT_LENGTH, strInfo );
		nContentLength	=	atol( strInfo );
		nContentLengthTotal = nContentLength + nContentLengthFinished;
		if( pstrResult && nContentLengthTotal > 0 )
			pstrResult->GetBuffer( nContentLengthTotal+5 );

		DWORD	dwCheckSum	=	0;
		BOOL	bHasCheckSum	=	FALSE;
		CString	strCheckSum;
		pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strCheckSum);
		int nPlace = strCheckSum.Find( szCheckSumKeySuffix );
		if ( -1 != nPlace )
		{
			strCheckSum = strCheckSum.Mid( nPlace+strlen(szCheckSumKeySuffix) );
			nPlace = strCheckSum.Find( '\n' );
			if( nPlace > 0 )
			{
				dwCheckSum = atol( strCheckSum.Left( nPlace ) );
				bHasCheckSum	=	TRUE;
			}
		}

		if( fnCallback )
			fnCallback( PROG_TRANSFERRING, 0, NULL, cookie );

		DWORD	dwCheckSumLocal	=	0;
		TCHAR sz[1028];
		int nRead = pFile->Read(sz+4, 1023);
		while (nRead > 0)
		{
			sz[4+nRead] = '\0';
			if( NULL != pFileSave )
				pFileSave->Write( sz+4, nRead );
			if( NULL != pstrResult )
				*pstrResult	+=	(TCHAR *)(sz+4);
			nContentLengthLocal	+=	nRead;

			if( fnCallback && nContentLengthTotal > 0 )
				fnCallback( PROG_PROGRESS, DWORD(STKLIB_MAXF_PROGRESS*(nContentLengthFinished+nContentLengthLocal)/nContentLengthTotal), NULL, cookie );

			if( bHasCheckSum )
			{
				*((DWORD *)sz)	=	dwCheckSumLocal;
				dwCheckSumLocal = CRC32( sz, nRead );
			}

			nRead = pFile->Read(sz+4, 1023);
		}

		if( pstrResult && nContentLengthTotal > 0 )
			pstrResult->ReleaseBuffer();

		if( (nContentLength > 0 && nContentLengthLocal != nContentLength)
				|| (bHasCheckSum && dwCheckSum != dwCheckSumLocal) )
			ThrowTearException( ERR_TEAR_DATATRANSFER );

		if( fnCallback )
			fnCallback( PROG_PROGRESS, STKLIB_MAX_PROGRESS, NULL, cookie );
	}
	catch (CInternetException* pEx)
	{
		// catch errors from WinINet
		if (HTTP_STATUS_OK == dwRet)
			dwRet	=	HTTP_STATUS_PARTIAL;
		TCHAR szErr[1024];
		pEx->GetErrorMessage(szErr, 1024);
		m_strLastErrorMessage	=	szErr;
		pEx->Delete();
	}
	catch (CTearException* pEx)
	{
		TCHAR szErr[1024];
		pEx->GetErrorMessage(szErr, 1024);
		m_strLastErrorMessage	=	szErr;
		pEx->Delete();
	}
	catch( CException * pEx )
	{
		TCHAR szErr[1024];
		pEx->GetErrorMessage(szErr, 1024);
		m_strLastErrorMessage	=	szErr;
		pEx->Delete();
	}

	if (pFile != NULL)
	{
		pFile->Close();
		delete pFile;
	}
	if (pServer != NULL)
	{
		pServer->Close();
		delete pServer;
	}
	session.Close();

	if(nContentLength > 0 && nContentLengthLocal != nContentLength)
		return Request( lpszURL, strPostData, pFileSave, pstrResult, fnCallback, cookie );

	return dwRet;
}
Example #12
0
void CHttpClient::DoOpenURL( LPCTSTR lpszURL, DWORD dwHttpRequestFlags,
							CString &strHeader, CString &strPostData,
							CInternetSession *pSession,
							CHttpConnection **ppServer, CHttpFile **ppFile,
							PROGRESS_CALLBACK fnCallback, void * cookie )
{
	CString strServerName;
	CString strObject;
	INTERNET_PORT nPort;
	DWORD dwServiceType;
	
	int nVerb = (strPostData.GetLength()>0 ? CHttpConnection::HTTP_VERB_POST : CHttpConnection::HTTP_VERB_GET);

	if (!AfxParseURL(lpszURL, dwServiceType, strServerName, strObject, nPort) ||
		dwServiceType != INTERNET_SERVICE_HTTP)
	{
		ThrowTearException( ERR_TEAR_URLFORMAT );
	}

	if( fnCallback )
		fnCallback( PROG_HTTPCONNECTTING, 0, NULL, cookie );

	CHttpConnection *pServer = pSession->GetHttpConnection(strServerName, dwHttpRequestFlags, nPort, m_strProxyUser, m_strProxyPasswd );
	CHttpFile	* pFile = pServer->OpenRequest(nVerb, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags);
	pFile->AddRequestHeaders(strHeader, HTTP_ADDREQ_FLAG_COALESCE);
	if( strPostData.GetLength() > 0 ) // post
	{
		try
		{
			pFile->SendRequestEx( DWORD(strPostData.GetLength()) );
			pFile->WriteString(strPostData);
			pFile->EndRequest();
		}
		catch( CInternetException *pp )	// HTTP_STATUS_BAD_METHOD
		{
			pp->Delete();

			// close up the redirected site
			pFile->Close();
			delete pFile;
			pFile	=	NULL;
			pServer->Close();
			delete pServer;
			pServer	=	NULL;

			pServer = pSession->GetHttpConnection(strServerName, dwHttpRequestFlags, nPort, m_strProxyUser, m_strProxyPasswd );
			pFile = pServer->OpenRequest(nVerb, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags);
			pFile->AddRequestHeaders(strHeader, HTTP_ADDREQ_FLAG_COALESCE);
			pFile->SendRequestEx( DWORD(strPostData.GetLength()) );
			pFile->WriteString(strPostData);
			pFile->EndRequest();
		}
	}
	else
	{
		pFile->SendRequest();
	}

	if( fnCallback )
		fnCallback( PROG_REQUESTSENT, 0, NULL, cookie );

	// Bad Post method
	DWORD dwRet	=	0;
	pFile->QueryInfoStatusCode( dwRet );

	// if access was denied, prompt the user for the password
	if (dwRet == HTTP_STATUS_DENIED
		|| dwRet == HTTP_STATUS_PROXY_AUTH_REQ )
	{
		DWORD dwPrompt;
		dwPrompt = pFile->ErrorDlg(NULL, ERROR_INTERNET_INCORRECT_PASSWORD,
			FLAGS_ERROR_UI_FILTER_FOR_ERRORS | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA
			| FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL);

		// if the user cancelled the dialog, bail out
		if (dwPrompt != ERROR_INTERNET_FORCE_RETRY)
			ThrowTearException( ERR_TEAR_CANCEL );
		if( strPostData.GetLength() > 0 ) // post
		{
			try{
				pFile->SendRequestEx( DWORD(strPostData.GetLength()) );
				pFile->WriteString(strPostData);
				pFile->EndRequest();
			}
			catch( CInternetException *pp ) // HTTP_STATUS_BAD_METHOD
			{
				pp->Delete();

				pFile->SendRequestEx( DWORD(strPostData.GetLength()) );
				pFile->WriteString(strPostData);
				pFile->EndRequest();
			}
		}
		else
		{
			pFile->SendRequest();
		}
		pFile->QueryInfoStatusCode(dwRet);
	}

	if( dwRet == HTTP_STATUS_BAD_METHOD )
	{
		// close up the redirected site
		pFile->Close();
		delete pFile;
		pFile	=	NULL;
		pServer->Close();
		delete pServer;
		pServer	=	NULL;

		pServer = pSession->GetHttpConnection(strServerName, dwHttpRequestFlags, nPort, m_strProxyUser, m_strProxyPasswd );
		pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags);
		pFile->AddRequestHeaders(strHeader, HTTP_ADDREQ_FLAG_COALESCE);
		if( strPostData.GetLength() > 0 ) // post
		{
			pFile->SendRequestEx( DWORD(strPostData.GetLength()) );
			pFile->WriteString(strPostData);
			pFile->EndRequest();
		}
		else
		{
			pFile->SendRequest();
		}
	}

	*ppServer	=	pServer;
	*ppFile	=	pFile;
}
Example #13
0
BOOL  CDlgView::Download(const CString& strFileURLInServer, //待下载文件的URL
                         const CString & strFileLocalFullPath)//存放到本地的路径
{
    ASSERT(strFileURLInServer != "");
    ASSERT(strFileLocalFullPath != "");
    CInternetSession session(_T("test"));
    CHttpConnection* pHttpConnection = NULL;
    CHttpFile* pHttpFile = NULL;
    CString strServer, strObject;
    INTERNET_PORT wPort;

    DWORD dwType;
    const int nTimeOut = 2000;
    session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, nTimeOut); //重试之间的等待延时
    session.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1);   //重试次数
    char* pszBuffer = NULL;

    try
    {
        AfxParseURL(strFileURLInServer, dwType, strServer, strObject, wPort);
        pHttpConnection = session.GetHttpConnection(strServer, wPort);
        pHttpFile = pHttpConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject,NULL,1,NULL,NULL,INTERNET_FLAG_TRANSFER_ASCII|INTERNET_FLAG_RELOAD);
        if(pHttpFile->SendRequest() == FALSE)
            return false;
        DWORD dwStateCode;

        pHttpFile->QueryInfoStatusCode(dwStateCode);
        if(dwStateCode == HTTP_STATUS_OK)
        {
            HANDLE hFile = CreateFile(strFileLocalFullPath, GENERIC_WRITE,
                                      FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
                                      NULL);  //创建本地文件
            if(hFile == INVALID_HANDLE_VALUE)
            {
                pHttpFile->Close();
                pHttpConnection->Close();
                session.Close();
                return false;
            }

            char szInfoBuffer[1000];  //返回消息
            DWORD dwFileSize = 0;   //文件长度
            DWORD dwInfoBufferSize = sizeof(szInfoBuffer);
            BOOL bResult = FALSE;
            bResult = pHttpFile->QueryInfo(HTTP_QUERY_CONTENT_LENGTH,
                                           (void*)szInfoBuffer,&dwInfoBufferSize,NULL);

            dwFileSize = atoi(szInfoBuffer);
            const int BUFFER_LENGTH = 1024 * 10;
            pszBuffer = new char[BUFFER_LENGTH];  //读取文件的缓冲
            DWORD dwWrite, dwTotalWrite;
            dwWrite = dwTotalWrite = 0;
            UINT nRead = pHttpFile->Read(pszBuffer, BUFFER_LENGTH); //读取服务器上数据

            while(nRead > 0)
            {
                WriteFile(hFile, pszBuffer, nRead, &dwWrite, NULL);  //写到本地文件
                dwTotalWrite += dwWrite;
                nRead = pHttpFile->Read(pszBuffer, BUFFER_LENGTH);
            }

            delete[]pszBuffer;
            pszBuffer = NULL;
            CloseHandle(hFile);
        }
        else
        {
            delete[]pszBuffer;
            pszBuffer = NULL;
            if(pHttpFile != NULL)
            {
                pHttpFile->Close();
                delete pHttpFile;
                pHttpFile = NULL;
            }
            if(pHttpConnection != NULL)
            {
                pHttpConnection->Close();
                delete pHttpConnection;
                pHttpConnection = NULL;
            }
            session.Close();
            return false;
        }
    }
    catch(...)
    {
        delete[]pszBuffer;
        pszBuffer = NULL;
        if(pHttpFile != NULL)
        {
            pHttpFile->Close();
            delete pHttpFile;
            pHttpFile = NULL;
        }
        if(pHttpConnection != NULL)
        {
            pHttpConnection->Close();
            delete pHttpConnection;
            pHttpConnection = NULL;
        }
        session.Close();
        return false;
    }

    if(pHttpFile != NULL)
        pHttpFile->Close();
    if(pHttpConnection != NULL)
        pHttpConnection->Close();
    session.Close();
    return true;
}
Example #14
0
//负责接收上传操作的页面的URL ,待上传的本地文件路径
int  CWebBase::UploadFile(LPCTSTR strURL, LPCTSTR strLocalFileName)
{
	ASSERT(strURL != NULL && strLocalFileName != NULL);

	BOOL bResult = FALSE;
	DWORD dwType = 0;
	CString strServer;
	CString strObject;
	INTERNET_PORT wPort = 0;
	DWORD dwFileLength = 0;
	char * pFileBuff = NULL;

	CHttpConnection * pHC = NULL;
	CHttpFile * pHF = NULL;
	CInternetSession cis;

	bResult =  AfxParseURL(strURL, dwType, strServer, strObject, wPort);
	if(!bResult)
	{
		return FALSE;
	}
	CFile file;
	try
	{
		if(!file.Open(strLocalFileName, CFile::shareDenyNone | CFile::modeRead))
			return FALSE;
		dwFileLength = file.GetLength();
		if(dwFileLength <= 0)
			return FALSE;
		pFileBuff = new char[dwFileLength];
		memset(pFileBuff, 0, sizeof(char) * dwFileLength);
		file.Read(pFileBuff, dwFileLength);

		const int nTimeOut = 5000;
		cis.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, nTimeOut); //联接超时设置
		cis.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1);  //重试1次
		pHC = cis.GetHttpConnection(strServer, wPort);  //取得一个Http联接

		pHF = pHC->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject);
		if(!pHF->SendRequest(NULL, 0, pFileBuff, dwFileLength))
		{
			delete[]pFileBuff;
			pFileBuff = NULL;
			pHF->Close();
			pHC->Close();
			cis.Close();
			return FALSE;
		}
		DWORD dwStateCode = 0;
		pHF->QueryInfoStatusCode(dwStateCode);

		if(dwStateCode == HTTP_STATUS_OK)
			bResult = TRUE;
	}

	catch(CInternetException * pEx)
	{
		char sz[256] = "";
		pEx->GetErrorMessage(sz, 25);
		CString str;
		str.Format("InternetException occur!\r\n%s", sz);
		AfxMessageBox(str);
	}
	catch(...)
	{
		DWORD dwError = GetLastError();
		CString str;
		str.Format("Unknow Exception occur!\r\n%d", dwError);
		AfxMessageBox(str);
	}

	delete[]pFileBuff;
	pFileBuff = NULL;
	file.Close();
	pHF->Close();
	pHC->Close();
	cis.Close();
	return bResult;
}
CString CHttpRequest::Download (CString strURL, int nMethod, CString strHeaders, CString strData,
	CString strFilename,
	bool* pbCancelDownload, DWORD dwDownloadId, int& nError, int nApproxContentLength,									   
	HWND hwndProgress, HWND hwndStatus, CString strMsg)
{
	gl_stkDownloads.push_back (dwDownloadId);

	bool bUseFile = !strFilename.IsEmpty ();
	strStatusMsg = bUseFile ? strFilename : strMsg;

	// show the UI controls
	if (dwDownloadId == gl_stkDownloads.back ())
	{
		if (hwndProgress != NULL)
		{
			::PostMessage (hwndProgress, PBM_SETPOS, 0, 0);
			::ShowWindow (hwndProgress, SW_SHOW);
		}

		if (hwndStatus != NULL)
			::PostMessage (hwndStatus, SB_SETTEXT, 1, (LPARAM) strStatusMsg.GetBuffer (0));
	}

	/*
	CString strDisplayFilename, strDisplay;
	if (!strFilename.IsEmpty () && (pStatus != NULL))
	{
		strcpy (strDisplayFilename.GetBuffer (strFilename.GetLength () + 1), strFilename.GetBuffer (0));
		strDisplayFilename.ReleaseBuffer ();

		// needs ellipsis?
		CRect r;
		pStatus->GetWindowRect (&r);
		r.right -= 300;
		HDC hdc = ::GetWindowDC (pStatus->GetSafeHwnd ());
		::DrawText (hdc, strDisplayFilename, -1, &r, DT_PATH_ELLIPSIS | DT_MODIFYSTRING);
		::ReleaseDC (pStatus->GetSafeHwnd (), hdc);
	}*/

	CHttpConnection* pHttpConnection = NULL;
	CHttpFile* pHttpFile = NULL;
	LPVOID lpvoid = NULL;

	DWORD dwServiceType;
	CString strServer, strObject;
	INTERNET_PORT nPort;
	AfxParseURL (strURL, dwServiceType, strServer, strObject, nPort);

	// declare CMyInternetSession object
	CInternetSession InternetSession (NULL,
		//"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; (R1 1.3))",
		1, INTERNET_OPEN_TYPE_PRECONFIG);

	CString strRetData;

	try
	{
		// establish the HTTP connection
		pHttpConnection = InternetSession.GetHttpConnection (strServer, nPort, "", "");

		// open the HTTP request
		pHttpFile = pHttpConnection->OpenRequest (nMethod, strObject, NULL, 1, NULL,
			NULL, INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_AUTO_REDIRECT | INTERNET_FLAG_TRANSFER_BINARY);

		if (pHttpFile->SendRequest (strHeaders, strHeaders.GetLength (),
			static_cast<void*>(strData.GetBuffer (0)), strData.GetLength ()))
		{
			DWORD dwRet;
			// query the HTTP status code
			pHttpFile->QueryInfoStatusCode (dwRet);
			if (dwRet >= 400)
			{
				nError = dwRet;
				gl_stkDownloads.remove (dwDownloadId);
				return "";
			}
			
			CString strContentLen;
			LPSTR lpszResult = NULL;
			UINT nRead = 0, nTotalRead = 0;

			lpvoid = malloc (HTTPFILE_BUFFLEN);
			// memory error
			if (!lpvoid)
			{
				AfxMessageBox("Error allocating memory");
				if (pHttpConnection)
				{
					pHttpConnection->Close();
					delete pHttpConnection;
				}
				if (pHttpFile)
				{
					pHttpFile->Close();
					delete pHttpFile;
				}
				nError = -1;
				gl_stkDownloads.remove (dwDownloadId);
				return "";
			}

			CFile f1;

			DWORD dwSize;
			if (!pHttpFile->QueryInfo (HTTP_QUERY_CONTENT_LENGTH, dwSize))
				dwSize = nApproxContentLength;
			if ((dwDownloadId == gl_stkDownloads.back ()) && (hwndProgress != NULL))
				::PostMessage (hwndProgress, PBM_SETRANGE32, 0, dwSize);

			if (bUseFile)
				if (!f1.Open (strFilename, CFile::modeCreate | CFile::modeWrite))
				{
					nError = -1;
					gl_stkDownloads.remove (dwDownloadId);
					return "";
				}

			DWORD dwStart = GetTickCount ();

			// read the HTTP response
			while (nRead = pHttpFile->Read ((byte*) lpvoid + (bUseFile ? 0 : nTotalRead), HTTPFILE_BUFFLEN))
			{
				if (pbCancelDownload != NULL)
					if (*pbCancelDownload)
					{
						// download cancelled
						if (pHttpConnection)
						{
							pHttpConnection->Close();
							delete pHttpConnection;
						}
						if (pHttpFile)
						{
							pHttpFile->Close();
							delete pHttpFile;
						}

						// delete the file
						if (bUseFile)
						{
							f1.Close ();
							CFile::Remove (strFilename);
						}

						nError = -1;
						gl_stkDownloads.remove (dwDownloadId);
						return "";
					}

				nTotalRead += nRead;

				// store the data
				if (bUseFile)
					f1.Write (lpvoid, nRead);
				else
				{
					lpvoid = realloc (lpvoid, nTotalRead + HTTPFILE_BUFFLEN);
					if (!lpvoid)
					{
						AfxMessageBox ("Error allocating memory");
						if (pHttpConnection)
						{
							pHttpConnection->Close();
							delete pHttpConnection;
						}
						if (pHttpFile)
						{
							pHttpFile->Close();
							delete pHttpFile;
						}

						nError = -1;
						gl_stkDownloads.remove (dwDownloadId);
						return "";
					}
				}

				// UI Feedback
				if (dwDownloadId == gl_stkDownloads.back ())
				{
					// update progress control
					if (hwndProgress != NULL)
						::PostMessage (hwndProgress, PBM_SETPOS, nTotalRead, 0);

					if (hwndStatus != NULL)
					{
						strKB.Format (IDS_DOWNLOADSTATUS_KB,
							nTotalRead / 1024,			// KBs read
							dwSize / 1024);				// Total size (KBs)
						::PostMessage (hwndStatus, SB_SETTEXT, 2, (LPARAM) strKB.GetBuffer (0));

						// percentage
						if (dwSize != 0)
						{
							strPercent.Format (IDS_DOWNLOADSTATUS_PERCENT, nTotalRead * 100 / dwSize);
							::PostMessage (hwndStatus, SB_SETTEXT, 3, (LPARAM) strPercent.GetBuffer (0));
						}

						// KB/s
						strKBs.Format (IDS_DOWNLOADSTATUS_KBS, (double) nTotalRead / 1024.0 / ((GetTickCount () - dwStart) / 1000.0 + 1));
						::PostMessage (hwndStatus, SB_SETTEXT, 4, (LPARAM) strKBs.GetBuffer (0));
					}
				}
			}
					
			if (bUseFile)
				f1.Close();
			else
			{
				// get response headers
				LPSTR lpszBuf = strRetData.GetBuffer (nTotalRead + HTTPFILE_BUFFLEN);
				DWORD dwBufLen = HTTPFILE_BUFFLEN;
				pHttpFile->QueryInfo (HTTP_QUERY_RAW_HEADERS_CRLF, lpszBuf, &dwBufLen);

				// copy contents
				*((LPSTR) lpvoid + nTotalRead) = 0;
				strcpy (lpszBuf + dwBufLen - 1, (LPSTR) lpvoid);

				strRetData.ReleaseBuffer ();
			}
		}
	}
	catch(CInternetException *e)
	{
		//e->ReportError();
		char szError[1001];
		e->GetErrorMessage (szError, 1000);
		CString strMsg;
		strMsg.Format (IDS_ERROR_HTTPREQUEST, strURL.GetBuffer (-1), szError);
		AfxMessageBox (strMsg, MB_ICONEXCLAMATION);

		e->Delete();
	}

	// cleanup
	if (lpvoid)
		free (lpvoid);

	if (pHttpFile)
	{
		pHttpFile->Close();
		delete pHttpFile;
	}
	if (pHttpConnection)
	{
		pHttpConnection->Close();
		delete pHttpConnection;
	}

	// hide UI controls
	if (dwDownloadId == gl_stkDownloads.back ())
	{
		if (hwndProgress != NULL)
			::ShowWindow (hwndProgress, SW_HIDE);
		if (bUseFile)
			if (hwndStatus != NULL)
				for (int i = 1; i <= 4; i++)
					::PostMessage (hwndStatus, SB_SETTEXT, i, (LPARAM) "");
	}

	gl_stkDownloads.remove (dwDownloadId);
	return strRetData;
}
Example #16
0
int CHttpRequest::ConnectUrl(TCHAR *sUrl, TCHAR *sReturn, long *lVersion, int *Count)
{
	ODS(_T("XFILTER.EXE: GetFromUrl Begin... \n"));
	
	if(sUrl == NULL)
		return XERR_INVALID_PARAMETER;

	CString			strServerName;
	CString			strObject;
	INTERNET_PORT	nPort;
	DWORD			dwServiceType;

	if (!AfxParseURL(sUrl, dwServiceType, strServerName, strObject, nPort) ||
		dwServiceType != INTERNET_SERVICE_HTTP)
	{
		ODS(_T("XFILTER.EXE: Internet Invalid Url ..."));
		return XERR_INTERNET_URL_ERROR;
	}

	CInternetSession	session(GUI_APP_CLASS_NAME);
	CHttpConnection		*pServer	= NULL;
	CHttpFile			*pFile		= NULL;
	int					iRet		= XERR_SUCCESS;

	m_IsConnecting = TRUE;

	try
	{
		pServer = session.GetHttpConnection(strServerName, nPort);
		pFile	= pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);

		pFile->AddRequestHeaders(szHeaders);
		pFile->SendRequest();

		DWORD	dwRet;
		pFile->QueryInfoStatusCode(dwRet);

		if (dwRet >= 400 && dwRet <= 499)
		{
			ODS(_T("XFILTER.EXE: Internet Request Error ..."));
			iRet = XERR_INTERNET_REQUEST_ERROR;
		}
		else if(dwRet >= 500 && dwRet <= 599)
		{
			ODS(_T("XFILTER.EXE: Internet Server Error ..."));
			iRet = XERR_INTERNET_SERVER_ERROR;
		}
		else if(sReturn != NULL)
		{
			pFile->ReadString(sReturn, MAX_NET_COMMAND_LENTH - 1);
			ODS(sReturn);

			CString tmpStr	= sReturn;
			long lVer		= atol(tmpStr.Left(MAX_NET_COMMAND_VERSION_LENTH));

			if(lVer > *lVersion)
			{
				*lVersion = lVer;
				int		i = 1;

				while (i < MAX_NET_COMMAND
					&& pFile->ReadString((sReturn + MAX_NET_COMMAND_LENTH * i), MAX_NET_COMMAND_LENTH - 1))
				{
					ODS(sReturn + i * MAX_NET_COMMAND_LENTH);
					i ++;
				}
				*Count = i;
			}
			else
			{
				*Count = 1;
			}
		}
		else
		{
			CString sRet;
			pFile->ReadString(sRet);
			if(sRet.GetAt(0) != '1')
				iRet = XERR_INTERNET_REG_ERROR;

			ODS2(_T("XFILTER.EXE: Internet User Register Return Value "),sRet);
		}

		pFile->Close();
		pServer->Close();
	}
	catch(CInternetException* pEx)
	{
		pEx->Delete();
		iRet = XERR_INTERNET_CONNECT_ERROR;
		ODS(_T("XFILTER.EXE: GetFromUrl XERR_INTERNET_CONNECT_ERROR... "));
	}

	if (pFile != NULL)
		delete pFile;
	if (pServer != NULL)
		delete pServer;
	session.Close();

	m_IsConnecting = FALSE;

	ODS(_T("XFILTER.EXE: GetFromUrl End... "));
	return iRet;
}
Example #17
0
BOOL CUpdateThread::Download( LPCTSTR lpszUrl, LPCTSTR lpszSavePath, ULONG uSize)
{
	DWORD dwServiceType;
	CString strServer;
	CString strObject;
	INTERNET_PORT nPort;
	BOOL bResult = FALSE;
	if (AfxParseURL(lpszUrl, dwServiceType, strServer, strObject, nPort))
	{
		CHttpConnection *conn = NULL;
		CHttpFile *file = NULL;
		UpdateSubProgress(0);
		try
		{
			int flags = INTERNET_FLAG_EXISTING_CONNECT;
			if (dwServiceType == AFX_INET_SERVICE_HTTPS) 
			{
				flags |= INTERNET_FLAG_SECURE | 
					INTERNET_FLAG_IGNORE_CERT_CN_INVALID |
					INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;
			}
			conn = m_Session.GetHttpConnection(strServer, nPort);
			file = conn->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, flags);
			file->SendRequest();
			UpdateSubProgress(10);
			DWORD dwStatus = 0;
			file->QueryInfoStatusCode(dwStatus);
			if (dwStatus == 200)
			{
				CFile localFile(lpszSavePath, CFile::modeReadWrite | CFile::shareExclusive | CFile::modeCreate);
				char buf[512];
				UINT nCount = 0;
				ULONG uTotal = 0;
				while ((nCount = file->Read(buf, 1)) > 0)
				{
					localFile.Write(buf, nCount);
					uTotal += nCount;
					if (uSize > 0)
						UpdateSubProgress(10 + 90.0 * uTotal / uSize);
				}
				localFile.Close();
				bResult = TRUE;
			}
		}
		catch (CException *e)
		{
			e->ReportError();
			e->Delete();
		}
		if (file)
		{
			file->Close();
			delete file;
		}
		if (conn)
		{
			conn->Close();
			delete conn;
		}
		UpdateSubProgress(100);
	};
	return bResult;
}