Exemplo n.º 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;
}
Exemplo n.º 2
0
BOOL CProxyIP::GetFirstGoalUrl(const TCHAR* pSrcUrl, TCHAR* pGoalUrl)
{
    BOOL bRet = FALSE;
    CHttpFile* pHttpFile = (CHttpFile *)m_pSession->OpenURL(pSrcUrl);
    DWORD dwStatusCode = 0;
    pHttpFile->QueryInfoStatusCode(dwStatusCode);
    if (dwStatusCode == HTTP_STATUS_OK)
    {
        CString strData;
        wstring subStr = _T("国内网页http代理ip地址服务器");
        while(pHttpFile->ReadString(strData))
        {
            TCHAR mainStr[MAX_STR_LEN] = {0};
            ConvertMultiByteToWideChar((char *)strData.GetBuffer(), mainStr, MAX_STR_LEN);
            wstring wMainStr = mainStr;
            if (wMainStr.find(subStr) < wMainStr.length())
            {
                int startLoc = wMainStr.find(_T("href"));
                int endLoc = wMainStr.find(_T("title"));
                endLoc -= 2;
                startLoc += 6;
                wstring wTempUrl = wMainStr.substr(startLoc, endLoc-startLoc).c_str();
                wmemcpy(pGoalUrl, wTempUrl.c_str(), wcslen(wTempUrl.c_str())+1);
                bRet = TRUE;
                break;
            }
        }
    }
    pHttpFile->Close();
    delete pHttpFile;
    return bRet;
}
Exemplo n.º 3
0
std::string urlGet(const char* pUrl)
{
	CInternetSession session(__argv[0]);
	CHttpFile *file = NULL; 	
	CString strHtml = "";   //存放网页数据
	char* headers = "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;)" ;
	try
	{
		file = (CHttpFile*)session.OpenURL(pUrl , 1 , INTERNET_FLAG_TRANSFER_ASCII , headers , strlen(headers)) ;	
	}
	catch(CInternetException * m_pException){
		file = NULL;
		m_pException->Delete();
		session.Close();	
		return "" ;
	}

	CString strLine;
	
	if(file != NULL)
	{
		while(file->ReadString(strLine) != NULL)
		{	
			strHtml += strLine;	
			//strHtml +="\n" ;
		}
		file->Close();
		delete file;
		file = NULL;
	}
	
	session.Close();
	return std::string(strHtml) ;
}
Exemplo n.º 4
0
int CXCCRA2MapUpdaterApp::download_update(string link, string fname)
{
	int error = 0;
	CInternetSession is;
	CHttpFile* f = reinterpret_cast<CHttpFile*>(is.OpenURL(link.c_str(), INTERNET_FLAG_TRANSFER_BINARY));
	if (!f)
		error = 1;
	else 
	{
		Cvirtual_file h;
		DWORD status;
		if (!f->QueryInfoStatusCode(status))
			error = 2;
		else if (status != 200)
			error = 3;
		else
		{
			int total_size = f->Seek(0, CFile::end);
			f->Seek(0, CFile::begin);
			Cdownload_dlg dlg;
			dlg.set(link, fname, total_size);
			dlg.Create(Cdownload_dlg::IDD, NULL);
			dlg.EnableWindow(false);
			Cvirtual_binary t;
			while (!error)
			{
				int cb_p = min<int>(f->GetLength(), 1 << 10);
				if (!cb_p)
					break;
				f->Read(t.write_start(cb_p), cb_p);
				h.write(t);
				dlg.set_size(h.size());
				dlg.UpdateWindow();
			}
			h.compact();
			Cxif_key k;
			if (k.load_key(h.data(), h.size()))
				error = 5;
			else
			{
				for (t_xif_key_map::const_iterator ki = k.m_keys.begin(); ki != k.m_keys.end(); ki++)
				{
					if (error)
						break;
					const Cxif_key& l = ki->second;
					string fext = boost::to_lower_copy(Cfname(l.get_value_string(vi_fname)).get_fext());
					if (fext != ".mmx"
						&& (fext != ".yro") || !Cfname(xcc_dirs::get_exe(game_ra2_yr)).exists())
						continue;
					if (file32_write(Cfname(fname).get_path() + l.get_value_string(vi_fname), l.get_value(vi_fdata).get_data(), l.get_value(vi_fdata).get_size()))
						error = 6;
				}
			}
			dlg.DestroyWindow();
		}
		f->Close();
	}
	return error;
}
Exemplo n.º 5
0
void C51JobWebPost::TestProxy()
{
	CInternetSession session;

	CHttpFile *file = NULL;   



	INTERNET_PROXY_INFO proxyinfo;

	proxyinfo.dwAccessType = INTERNET_OPEN_TYPE_PROXY;

	proxyinfo.lpszProxy ="122.205.95.14:80";

	proxyinfo.lpszProxyBypass = NULL;

	
	session.SetOption(INTERNET_OPTION_PROXY,(LPVOID)&proxyinfo,
		sizeof(INTERNET_PROXY_INFO));
	
	try{

		file = (CHttpFile*)session.OpenURL("http://www.ip138.com/ip2city.asp",1,
			INTERNET_FLAG_TRANSFER_ASCII|INTERNET_FLAG_RELOAD|INTERNET_FLAG_DONT_CACHE);		

	}catch(CInternetException * m_pException){

		file = NULL;

		m_pException->m_dwError;

		m_pException->Delete();

		session.Close();

		AfxMessageBox("CInternetException");

		return;

	}

	CString strLine;
	CString strResult = "";
	if(file != NULL){

		while(file->ReadString(strLine) != NULL){

			strResult += strLine;

		}

	}else{
		AfxMessageBox("fail");
	}
	file->Close();
	session.Close();
}
Exemplo n.º 6
0
int CXCCRA2MapUpdaterApp::update()
{
	int error = 0;
	try
	{
		CWaitCursor wait;
		CInternetSession is;
		CHttpFile* f = reinterpret_cast<CHttpFile*>(is.OpenURL("http://xccu.sourceforge.net/ra2_maps/official.ucf"));
		if (!f)
			error = 1;
		else
		{
			string s;
			while (1)
			{
				int cb_p = f->GetLength();
				if (!cb_p)
					break;
				char* p = new char[cb_p + 1];
				f->Read(p, cb_p);
				p[cb_p] = 0;
				s += p;
				delete[] p;
			}
			f->Close();
			Cvirtual_tfile f;
			f.load_data(Cvirtual_binary(s.c_str(), s.length()));
			while (!f.eof())
			{
				Cmulti_line l = f.read_line();
				Cfname fname = xcc_dirs::get_dir(game_ra2) + l.get_next_line('=') + ".mmx";
				if (!fname.exists())
				{
					string version = l.get_next_line(',');
					string link = l.get_next_line(',');
					error = download_update(link, fname);
					if (error)
					{
						delete_file(fname);
						MessageBox(NULL, "Error retrieving update.", NULL, MB_ICONERROR);
						error = 0;
					}
				}
			}
		}
	}
	catch (CInternetException*)
	{
		error = 1;
	}
	if (error)
		MessageBox(NULL, "Error querying for update.", NULL, MB_ICONERROR);
	return error;
}
Exemplo n.º 7
0
BOOL CAutoUpdateDlg::DownloadFile(LPCTSTR lpURL,LPCTSTR lpDestFile)
{
	CFile cUdpFile; 
	if(!cUdpFile.Open(lpDestFile,CFile::modeCreate|CFile::modeWrite|CFile::typeBinary|CFile::shareDenyWrite))
		return FALSE;
	BOOL bResult = FALSE;
	CInternetSession sessionDownload;
	try
	{
		CHttpFile* pFile = (CHttpFile*)sessionDownload.OpenURL(lpURL,1,INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_RELOAD|INTERNET_FLAG_DONT_CACHE);
		CString   query = _T("");
		pFile->QueryInfo(HTTP_QUERY_CONTENT_LENGTH,query);
		long file_len=_ttol(query);
		m_dwTotalSize = file_len;
		PostMessage(WM_POSMESSAGE,0,0);
		DWORD dwStatus;
		if (pFile->QueryInfoStatusCode(dwStatus))
		{
			if (dwStatus == 200)
			{
				pFile->SetReadBufferSize(10240);
				if (TRUE)
				{
					DWORD dwLen = 0;
					char buf[BLOCKSIZE];
					while (TRUE)
					{
						DWORD dwTemp = pFile->Read(buf,BLOCKSIZE);
						if (dwTemp)
						{
							cUdpFile.Write(buf,dwTemp);
						}
						m_dwDownloadedSize += dwTemp;
						PostMessage(WM_POSMESSAGE,0,0);
						if (dwTemp < BLOCKSIZE)
						{
							break;
						}
					}
				}
			}
		}
		pFile->Close();
		bResult = TRUE;
	}
	catch(CInternetException* pException)
	{
		pException->Delete();
		return bResult;
	}
	sessionDownload.Close();
	cUdpFile.Close();
	return bResult;
}
Exemplo n.º 8
0
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;
}
Exemplo n.º 9
0
DWORD CLoginDlg::userProfile(LPCTSTR serverURL, LPCTSTR requestPage)
{

#ifdef _HTTPS
	CInternetSession session(_T("HelloChat"), INTERNET_FLAG_SECURE);
	CHttpConnection* pConnection = session.GetHttpConnection(serverURL, INTERNET_SERVICE_HTTP, INTERNET_DEFAULT_HTTPS_PORT);
	CString strToken = L"token:";
	strToken = strToken + m_strMyToken + L"\r\n";
	CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET, requestPage, NULL, 1, NULL, NULL, INTERNET_FLAG_SECURE | INTERNET_FLAG_RELOAD |
		INTERNET_FLAG_DONT_CACHE |
		INTERNET_FLAG_NO_COOKIES);
#else
	CInternetSession session(_T("HelloChat"), PRE_CONFIG_INTERNET_ACCESS);
	CHttpConnection* pConnection = session.GetHttpConnection(serverURL);
	CString strToken = L"token:";
	//strToken = strToken + m_strToken + L"\r\n";
	strToken = strToken + m_strMyToken + L"\r\n";
	CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET, requestPage, NULL, 1, NULL, NULL, INTERNET_FLAG_RELOAD |
		INTERNET_FLAG_DONT_CACHE |
		INTERNET_FLAG_NO_COOKIES);
#endif

	VERIFY(pFile->AddRequestHeaders(HEADER));
	VERIFY(pFile->AddRequestHeaders(strToken));
	VERIFY(pFile->SendRequest());

	// GET POST STATUS 
	DWORD dwPostStatus = 0;
	VERIFY(pFile->QueryInfoStatusCode(dwPostStatus));
	
	CString strBuffer = L"";
	BOOL brtn = pFile->ReadString(strBuffer);
	char* rtnBuffer = LPSTR(LPCTSTR(strBuffer));

	if (dwPostStatus == HTTP_STATUS_OK)
	{	
		BOOL bRtn = dataParser(rtnBuffer);
		if (!bRtn){
			AfxMessageBox(L"User Info Paser Error");
		}
	}
	else{
		CComm func;
		func.WriteErrorLog(rtnBuffer);
	}
	pFile->Close();

	return dwPostStatus;
}
Exemplo n.º 10
0
BOOL CProxyIP::FillGoalUrlVec(const TCHAR* pFirstGoalUrl)
{
    BOOL bRet = FALSE;
    int totalPage = 0;
    CHttpFile* pHttpFile = (CHttpFile *)m_pSession->OpenURL(pFirstGoalUrl);
    DWORD dwStatusCode = 0;
    pHttpFile->QueryInfoStatusCode(dwStatusCode);
    if (dwStatusCode == HTTP_STATUS_OK)
    {
        BOOL bCheck = FALSE;
        CString strData;
        wstring subStrPage = _T("class=\"pagelist\"");
        while(pHttpFile->ReadString(strData))
        {
            TCHAR mainStr[MAX_STR_LEN] = {0};
            ConvertMultiByteToWideChar((char *)strData.GetBuffer(), mainStr, MAX_STR_LEN);
            wstring wMainStr = mainStr;
            if (bCheck)
            {
                int lenn = wMainStr.find(_T("共"));
                wstring wsPage = wMainStr.substr(lenn+1, 1).c_str();
                totalPage = _wtoi(wsPage.c_str());
                bCheck = FALSE;
                break;
            }

            if (wMainStr.find(subStrPage) < wMainStr.length())
            {
                bCheck = TRUE;
            }

        }

        wstring strGoalUrl = pFirstGoalUrl;
        int lenHtml = strGoalUrl.find(_T(".html"));
        wstring newStrGoalUrl = strGoalUrl.substr(0, lenHtml);
        for (int j = 2; j <= totalPage; j++)
        {
            TCHAR tChar[MAX_URL_LEN] = {0};
            swprintf(tChar, MAX_URL_LEN, _T("%s_%d.html"), newStrGoalUrl.c_str(), j);
            m_goalUrlVec.push_back(tChar);
        }
        bRet = TRUE;
    }
    pHttpFile->Close();
    delete pHttpFile;
    return bRet;
}
Exemplo n.º 11
0
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;
}   
Exemplo n.º 12
0
bool CDlgView::DownLoadFile(const string&UrpPath ,const string& strFilePath)
{
    CInternetSession session;
    std::string strHtml;

    try
    {
        CHttpFile* pfile = (CHttpFile*)session.OpenURL(UrpPath.c_str(),1,INTERNET_FLAG_TRANSFER_ASCII|INTERNET_FLAG_RELOAD,NULL,0);

        DWORD dwStatusCode;
        pfile->QueryInfoStatusCode(dwStatusCode);
        if(dwStatusCode == HTTP_STATUS_OK)
        {
            char strBuff[1025] = {0};
            while ((pfile->Read((void*)strBuff, 1024)) > 0)
            {
                strHtml += strBuff;
            }
        }
        else
        {
            return false;
        }

        pfile->Close();
        delete pfile;
        session.Close();
    }
    catch (CException* e)
    {
        e;//消除警告
        return false;
    }

    if (!strHtml.empty())
    {
        ofstream outfile(strFilePath);
        if (!outfile.is_open())
        {
            return false;
        }
        outfile<<strHtml;
        outfile.close();
    }
    return true;
}
Exemplo n.º 13
0
bool CWebpageHandler::GetSourceHtml(CString theUrl,CString fileName)
{
    CInternetSession session;
	CHttpFile *file = NULL; 
	CString strURL = theUrl;
	CString strHtml = _T("");   //存放网页数据 

	try{
		   file = (CHttpFile*)session.OpenURL(strURL);

	}catch(CInternetException * m_pException){
		   file = NULL;
		   m_pException->m_dwError;
		   m_pException->Delete();
		   session.Close();

		   MessageBox(_T("网络连接失败!"));
		   return false;
	}

	CString strLine;
	if(file != NULL){
		   while(file->ReadString(strLine) != NULL){
		   strHtml += strLine;
		   }
 	}else{
		MessageBox(_T("读取网络数据失败!"));
		return false;
	}
 
	CFile file0(fileName, CFile::modeCreate|CFile::modeWrite);
	int len = strHtml.GetLength()*2;
	file0.Write(strHtml, len);
	session.Close();
	file->Close();
	file0.Close();
	delete file;
	file = NULL;

	m_htmlStr = strHtml;
	m_url = theUrl;
	return true;
}
Exemplo n.º 14
0
BOOL CProxyIP::FillIpVec()
{
    int i = 0;
    for (i = 0; i < m_goalUrlVec.size(); i++)
    {
        CHttpFile* pHttpFile = (CHttpFile *)m_pSession->OpenURL(m_goalUrlVec[i].c_str());
        DWORD dwStatusCode = 0;
        pHttpFile->QueryInfoStatusCode(dwStatusCode);
        if (dwStatusCode == HTTP_STATUS_OK)
        {
            BOOL bCheck = FALSE;
            CString strData;
            wstring subStr = _T("class=\"cont_ad\"");
            while(pHttpFile->ReadString(strData))
            {
                TCHAR mainStr[MAX_STR_LEN] = {0};
                ConvertMultiByteToWideChar((char *)strData.GetBuffer(), mainStr, MAX_STR_LEN);
                wstring wMainStr = mainStr;
                if (bCheck)
                {
                    if (wMainStr.find(_T("</span>")) < wMainStr.length())
                    {
                        break;
                    }
                    TCHAR firstPosChar = wMainStr.at(0);
                    if (firstPosChar < 48 || firstPosChar > 57)
                    {
                        continue;
                    }
                    m_IpVec.push_back(wMainStr);
                    m_totalIp++;
                }
                if (wMainStr.find(subStr) < wMainStr.length())
                {
                    bCheck = TRUE;
                }
            }
        }
        pHttpFile->Close();
        delete pHttpFile;
    }
    return TRUE;
}
Exemplo n.º 15
0
CString  StockRetriever::GetStockInfo(CString url)
{
	CInternetSession inter_session;
	CString strHtml;
	CHttpFile* file =NULL;
	try{  
		file = (CHttpFile*)inter_session.OpenURL(url);  
	}catch(CInternetException * m_pException){  
		file = NULL;  
		m_pException->m_dwError;  
		m_pException->Delete();  
		inter_session.Close();
		return "";
		//AfxMessageBox("CInternetException");  
	}  
	CString strLine;  
	if(file != NULL){  
		while(file->ReadString(strLine) != NULL){  
			strHtml += strLine;  
		}  
	}else{  
		return "";
		//AfxMessageBox("fail");  
	}  
	inter_session.Close();  
	file->Close();  
	delete file;  
	file = NULL;  

	int start = strHtml.Find('"');

	int end = strHtml.Find('"', start+1);

	//ASSERT( end > start+1 );

	if ( ! (end > start+1 && start >0 ))
		return "";

	CString ret = strHtml.Mid(start+1, end-start-1);
	return ret;
}
Exemplo n.º 16
0
string GetHtmlSource(CString strURL)
{
	CInternetSession session;
	CHttpFile *file = NULL; 

	CString strHtml = _T(""); //存放网页数据
	file =(CHttpFile*)session.OpenURL(strURL,1,INTERNET_FLAG_RELOAD);
 
	//CString strLine;
	char sRecived[1024];
	if(file != NULL) {
	while(file->ReadString((LPTSTR)sRecived,1024)!=NULL) {
	strHtml += sRecived; }
 }
	session.Close();
	if(file!=NULL) file->Close();
	delete file; file = NULL;

	string html =  CT2A(strHtml.GetBuffer(0));
	return html;
}
Exemplo n.º 17
0
CHAR* WebFetcher::GetHttp(LPCSTR lpServerName)
{
	CInternetSession sess;

    // 统一以二进制方式下载
    DWORD dwFlag = INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_DONT_CACHE|INTERNET_FLAG_RELOAD;
    CHttpFile *pF = (CHttpFile*)sess.OpenURL(lpServerName, 1, dwFlag); ASSERT(pF);
    if (!pF)
    {
		AfxThrowInternetException(1);
	}

    // 得到文件大小
    CString str;
    pF->QueryInfo(HTTP_QUERY_CONTENT_LENGTH, str);
    int nFileSize = _ttoi(str);

    char *p = new char[nFileSize];
    while (true)
    {
        // 每次下载8Kb
        int n = pF->Read(p, (nFileSize < 8192) ? nFileSize : 8192);
        if (n <= 0)
		{
            break;
		}
        p += n;
		nFileSize -= n;
    }

    //delete[] p;
	pF->Close();
    delete pF;

	return p;
}
Exemplo n.º 18
0
static DWORD WINAPI URLGetAsyncThread( LPVOID lpParam ) 
{
	URLGetAsyncData *data = (URLGetAsyncData *)lpParam;
	if (!data->url.IsEmpty()) {
		CInternetSession session;
		try {
			CHttpFile* pFile;
			pFile = (CHttpFile*)session.OpenURL(data->url, NULL, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE);
			if (pFile) {
				pFile->QueryInfoStatusCode(data->statusCode);
				CStringA buf;
				char pBuf[256];
				int i;
				do {
					i = pFile->Read(pBuf,255);
					pBuf[i] = 0;
					data->body.AppendFormat("%s",pBuf);
				} while (i>0);
				//--
				pFile->QueryInfo(
					HTTP_QUERY_RAW_HEADERS_CRLF,
					data->headers
					);
				pFile->Close();
			}
			session.Close();
		} catch (CInternetException *e) {
			data->statusCode = 0;
		}
	}
	if (data->message) {
		SendMessage(data->hWnd,data->message,(WPARAM)data,0);
	}
	delete data;
	return 0;
}
Exemplo n.º 19
0
//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;
}
Exemplo n.º 20
0
DWORD CLoginDlg::login(LPCTSTR serverURL, LPCTSTR requestPage, LPCTSTR formData)
{


#ifdef _HTTPS
	CInternetSession session(_T("HelloChat"), INTERNET_FLAG_SECURE);
	CHttpConnection* pConnection = session.GetHttpConnection(serverURL, INTERNET_SERVICE_HTTP, INTERNET_DEFAULT_HTTPS_PORT);
	CString strHeaders = HEADER;
	// OPEN A POST REQUEST 
	CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, requestPage, NULL, 1, NULL, NULL, INTERNET_FLAG_SECURE | INTERNET_FLAG_RELOAD |
		INTERNET_FLAG_DONT_CACHE |
		INTERNET_FLAG_NO_COOKIES);
#else
	CInternetSession session(_T("HelloChat"), PRE_CONFIG_INTERNET_ACCESS);
	CHttpConnection* pConnection = session.GetHttpConnection(serverURL);
	CString strHeaders = HEADER;
	// OPEN A POST REQUEST 
	CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, requestPage, NULL, 1, NULL, NULL, INTERNET_FLAG_RELOAD |
		INTERNET_FLAG_DONT_CACHE |
		INTERNET_FLAG_NO_COOKIES);
#endif
	
	// UNICODE 
#if defined(_UNICODE) 
	// Length of form data (including '\\0') 
	const int dwLength = _tcslen(formData) + 1;
	// Alocate ANSI character array 
	char *lpFormData = new char[dwLength];
	// Convert wide char form data to ANSI 
	//멀티바이트코드로 변환.
	VERIFY(0 != ::WideCharToMultiByte(CP_ACP, 0, formData, -1, lpFormData, dwLength, 0, 0));
	// Send the request to the HTTP server 
	VERIFY(pFile->SendRequest(strHeaders, lpFormData, dwLength));
	
	//  Delete ANSI array 
	delete[] lpFormData;
	// ANSI 
#else 
	// Send the request to the HTTP server 
	VERIFY(pFile->SendRequest(strHeaders, (LPVOID)formData, strlen(formData)));
#endif 
	// GET POST STATUS 
	DWORD dwPostStatus = 0;
	VERIFY(pFile->QueryInfoStatusCode(dwPostStatus));

	CString strBuffer = L"";
	BOOL brtn = pFile->ReadString(strBuffer);
	char* szBuff = LPSTR(LPCTSTR(strBuffer));
	
	if (dwPostStatus == HTTP_STATUS_OK)
	{
		// 토큰 획득.
		BOOL bRtn = getToken(szBuff);
		if (!bRtn){
			//토큰 획득 실패시.
			dwPostStatus = HTTP_STATUS_NO_CONTENT;

			//토큰 획득 실패 메시지
			CComm func;
			func.WriteErrorLog(szBuff);
		}
	}
	else if (dwPostStatus == HTTP_STATUS_DENIED){
		//토큰 Expire 확인.
		CComm func;
		BOOL bRtn = func.isTokenExpire(szBuff);
		if (bRtn){
			//토큰 만료에 대한 로그 작성
			func.WriteErrorLog(szBuff);

			// 토큰 Expire  토큰 재발급.
			GetPrivateProfileString(L"MYINFO", L"token", L"", (LPWSTR)func.m_myInfo.token, sizeof(func.m_myInfo.token), func.m_strINI);
			m_strMyToken = (LPCTSTR)(LPWSTR)func.m_myInfo.token;
			DWORD dwRtn = func.TokenRefresh(m_strMyToken);
			if (dwRtn == HTTP_STATUS_OK){
				//토큰은 다시 재 발급 받았으므로 로그인 다시 시도 메시지.
				AfxMessageBox(L"Token Expired\r\nLogin Again");
			}
			else{
				//토큰 재 발급 과정에서 재 발급 실패.
				AfxMessageBox(L"Token Refresh Fail.");
			}
		}
	}
	
	pFile->Close();

	return dwPostStatus;
}
Exemplo n.º 21
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;
}
Exemplo n.º 22
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;
}
Exemplo n.º 23
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;

}
Exemplo n.º 24
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;

}
Exemplo n.º 25
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;
}
Exemplo n.º 26
0
bool CVBFile::getFile(TCHAR *url, TCHAR *location)
{
	bool bRet = true;
	
	CInternetSession   sess ;
	CHttpFile   *phttpFile;
	CString Status;
	CFile lfile;
	char *buf=NULL;
	char *pbuf=NULL;

	DWORD dwFlag = INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_DONT_CACHE |
					INTERNET_FLAG_RELOAD ;

	try
	{
		//here, should think of proxy SetOption.
		//
		//INTERNET_OPTION_PROXY 
		//INTERNET_OPTION_PROXY_PASSWORD 
		//INTERNET_OPTION_PROXY_USERNAME 


		phttpFile = (CHttpFile*)sess.OpenURL(url, 1, dwFlag); 

		VERIFY(phttpFile);

		phttpFile->QueryInfo(HTTP_QUERY_STATUS_CODE, Status) ;
		if (Status != _T("200"))
		{
			bRet=false;
			phttpFile->Close();
			delete phttpFile ;
			goto lExit;
		}

		phttpFile->QueryInfo(HTTP_QUERY_CONTENT_LENGTH, Status) ; // file's length
		long filelen = _ttol(Status);
		long totalLen = filelen;
		buf = new char[filelen+1];
		pbuf = buf;

		::ZeroMemory(buf, filelen+1);

		while(true)
		{
			int   n = phttpFile->Read (buf, (filelen < 8192) ? filelen : 8192) ;
			if (n <= 0)
				break ;
			buf += n ; filelen -= n ;
		}
		phttpFile->Close();
		delete phttpFile;

		lfile.Open(location, CFile::modeCreate | CFile::modeWrite);
		lfile.Write((void*)pbuf, totalLen);
		lfile.Close();
	}
	catch(...)
	{
		bRet = false;
		goto lExit;
	}

lExit:
	delete pbuf;
	return bRet;
}
Exemplo n.º 27
0
// 初始化更新列表
BOOL CUpdaterApp::_InitFileList()
{
	BOOL bReturn(FALSE);

	CString strFileList(m_szServer);
	strFileList += _T("/Filelist.txt");

	CInternetSession sess;
	sess.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 5000);
	sess.SetOption(INTERNET_OPTION_SEND_TIMEOUT, 1000);
	sess.SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT, 5000);
	sess.SetOption(INTERNET_OPTION_DATA_SEND_TIMEOUT, 1000);
	sess.SetOption(INTERNET_OPTION_DATA_RECEIVE_TIMEOUT, 5000);
	sess.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1);

	try
	{
		CHttpFile* pHttpFile = (CHttpFile*)sess.OpenURL(strFileList, 1, INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_TRANSFER_ASCII, NULL, 0);
		if (pHttpFile)
		{
			DWORD dwErrCode(0);
			pHttpFile->QueryInfo(HTTP_QUERY_STATUS_CODE, dwErrCode);
			if (dwErrCode >= 200 && dwErrCode < 300)
			{
				CStringA strLineA;
				while (pHttpFile->ReadString((LPTSTR)strLineA.GetBuffer(512), 511))
				{
					strLineA.ReleaseBuffer(); // MFC-bug
					CString strLine(strLineA);
					strLine.TrimLeft();
					if (strLine.GetLength() > 0 && strLine[0] != _T('\\'))
					{
						continue;
					}
					std::vector<CString> vecStrs = Split(strLine, _T("^^^^^^"));
					if (vecStrs.size() >= 2)
					{
						LPUPDATEITEM pUpdateItem = new UPDATEITEM;
						ZeroMemory(pUpdateItem, sizeof(*pUpdateItem));
						lstrcpyn(pUpdateItem->szFileName, vecStrs[0], MAX_PATH);
						lstrcpyn(pUpdateItem->szServerMD5, vecStrs[1], 33);
						m_arrUpdate.Add(pUpdateItem);
					}
				}
				pHttpFile->Close();
				sess.Close();
				bReturn = TRUE;
			}
			else
			{
				LOG(_T("网站访问错误码:%d"), dwErrCode);
			}
		}
	}
	catch (...)
	{
		LOG(_T("下载列表异常!"));
	}

	return bReturn;
}
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;
}
Exemplo n.º 29
0
CString GetServerDetailInfo(CString strServer, CString &strTitle)
{
	strServer.Insert(0, "http://");
	CString strReturn = "Unknown", szAllData, szData;
	CInternetSession ss(_T("session"), 0, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD);//设置不缓冲
	CHttpFile *pF = NULL;
    try
	{
		ss.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 10 * 1000);
		pF = (CHttpFile *)ss.OpenURL(strServer, 1, INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_TRANSFER_ASCII | INTERNET_FLAG_NO_AUTO_REDIRECT);
		pF->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, szAllData, 0);
		int nPos1 = szAllData.Find("Server: ", 0);
		if (nPos1 == -1)
		{
			strReturn = "Unknown";
		}
		else
		{
			nPos1 += 8;
			int nPos2 = szAllData.Find("\r\n", nPos1);
			strReturn = szAllData.Mid(nPos1, nPos2 - nPos1);
			if (strReturn.Find("Microsoft", 0) != -1)
			{
				strReturn.Insert(0, "Windows, ");
			}
		}

		szAllData.Empty();
		while(pF->ReadString(szData))
			szAllData += szData;

		szAllData.MakeLower();
		nPos1 = szAllData.Find("<title>", 0);
		if (nPos1 != -1)
		{
			int nPos2 = szAllData.Find("</title>", nPos1);
			if (nPos2 != -1)
			{
				strTitle = szAllData.Mid(nPos1 + 7, nPos2 - nPos1 - 7);
				if (IsTextUTF8(strTitle.GetBuffer(0), strTitle.GetLength()))
					Utf8ToAnsi(strTitle);
			}
		}
	}
	catch(...)
	{
		strReturn = "";
	}
	if (pF != NULL)
	{
		pF->Close();
		delete pF;
		pF = NULL;
	}
	if (ss != NULL)
	{
		ss.Close();
		delete ss;
	}
	return strReturn;
}
Exemplo n.º 30
0
Update_Status UpdateChecker::IsUpdateAvailable(const Version& currentVersion)
{
    Update_Status updateAvailable = UPDATER_LATEST_STABLE;

    try {
        CInternetSession internet;

        OSVERSIONINFOEX osVersion = SysVersion::GetFullVersion();
        CString osVersionStr;
        osVersionStr.Format(_T("Windows %1u.%1u"), osVersion.dwMajorVersion, osVersion.dwMinorVersion);
        if (SysVersion::Is64Bit()) {
            osVersionStr += _T(" x64");
        }

        CString headersFmt = _T("User-Agent: MPC-HC");
        if (VersionInfo::Is64Bit()) {
            headersFmt += _T(" (64-bit)");
        }
#ifdef MPCHC_LITE
        headersFmt += _T(" Lite");
#endif
        headersFmt += _T(" (%s)/");
        headersFmt += VersionInfo::GetFullVersionString();
        headersFmt += _T("\r\n");

        CString headers;
        headers.Format(headersFmt, osVersionStr);

        CHttpFile* versionFile = (CHttpFile*) internet.OpenURL(versionFileURL,
                                                               1,
                                                               INTERNET_FLAG_TRANSFER_ASCII | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD,
                                                               headers,
                                                               DWORD(-1));

        if (versionFile) {
            CString latestVersionStr;
            char buffer[101];
            UINT br = 0;

            while ((br = versionFile->Read(buffer, 50)) > 0) {
                buffer[br] = '\0';
                latestVersionStr += buffer;
            }

            if (!ParseVersion(latestVersionStr, latestVersion)) {
                updateAvailable = UPDATER_ERROR;
            } else {
                time_t lastCheck = time(nullptr);
                AfxGetApp()->WriteProfileBinary(IDS_R_SETTINGS, IDS_RS_UPDATER_LAST_CHECK, (LPBYTE)&lastCheck, sizeof(time_t));

                int comp = CompareVersion(currentVersion, latestVersion);

                if (comp < 0) {
                    CString ignoredVersionStr = AfxGetApp()->GetProfileString(IDS_R_SETTINGS, IDS_RS_UPDATER_IGNORE_VERSION, _T("0.0.0.0"));
                    Version ignoredVersion;
                    bool ignored = false;

                    if (ParseVersion(ignoredVersionStr, ignoredVersion)) {
                        ignored = (CompareVersion(ignoredVersion, latestVersion) >= 0);
                    }

                    updateAvailable = ignored ? UPDATER_UPDATE_AVAILABLE_IGNORED : UPDATER_UPDATE_AVAILABLE;
                } else if (comp > 0) {
                    updateAvailable = UPDATER_NEWER_VERSION;
                }
            }

            versionFile->Close(); // Close() isn't called by the destructor
            delete versionFile;
        } else {
            updateAvailable = UPDATER_ERROR;
        }
    } catch (CInternetException* pEx) {
        updateAvailable = UPDATER_ERROR;
        pEx->Delete();
    }

    return updateAvailable;
}