Ejemplo n.º 1
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;
}
Ejemplo n.º 2
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();
}
Ejemplo n.º 3
0
DWORD CAsyncUrlReader::ThreadProc()
{
    AfxSocketInit(nullptr);

    DWORD cmd = GetRequest();
    if (cmd != CMD_INIT) {
        Reply((DWORD)E_FAIL);
        return (DWORD) - 1;
    }

    try {
        CInternetSession is;
        CAutoPtr<CStdioFile> fin(is.OpenURL(m_url, 1, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_CACHE_WRITE));

        TCHAR path[MAX_PATH], fn[MAX_PATH];
        CFile fout;
        if (GetTempPath(MAX_PATH, path) && GetTempFileName(path, _T("mpc_http"), 0, fn)
                && fout.Open(fn, modeCreate | modeWrite | shareDenyWrite | typeBinary)) {
            m_fn = fn;

            char buff[1024];
            int len = fin->Read(buff, sizeof(buff));
            if (len > 0) {
                fout.Write(buff, len);
            }

            Reply(S_OK);

            while (!CheckRequest(&cmd)) {
                int len2 = fin->Read(buff, sizeof(buff));
                if (len2 > 0) {
                    fout.Write(buff, len2);
                }
            }
        } else {
            Reply((DWORD)E_FAIL);
        }

        fin->Close(); // must close it because the destructor doesn't seem to do it and we will get an exception when "is" is destroying
    } catch (CInternetException* ie) {
        ie->Delete();
        Reply((DWORD)E_FAIL);
    }

    //

    cmd = GetRequest();
    ASSERT(cmd == CMD_EXIT);
    Reply(S_OK);

    //

    m_hThread = nullptr;

    return S_OK;
}
Ejemplo n.º 4
0
/*-----------------------------------------------------------------------------
	Get a string response from the given url (used for querying the EC2 instance config)
-----------------------------------------------------------------------------*/
bool CurlBlastDlg::GetUrlText(CString url, CString &response)
{
    bool ret = false;

    try
    {
        // set up the session
        CInternetSession * session = new CInternetSession();
        if( session )
        {
            DWORD timeout = 10000;
            session->SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, &timeout, sizeof(timeout), 0);
            session->SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT, &timeout, sizeof(timeout), 0);
            session->SetOption(INTERNET_OPTION_SEND_TIMEOUT, &timeout, sizeof(timeout), 0);
            session->SetOption(INTERNET_OPTION_DATA_SEND_TIMEOUT, &timeout, sizeof(timeout), 0);
            session->SetOption(INTERNET_OPTION_DATA_RECEIVE_TIMEOUT, &timeout, sizeof(timeout), 0);

            CInternetFile * file = (CInternetFile *)session->OpenURL(url);
            if( file )
            {
                char buff[4097];
                DWORD len = sizeof(buff) - 1;
                UINT bytes = 0;
                do
                {
                    bytes = file->Read(buff, len);
                    if( bytes )
                    {
                        ret = true;
                        buff[bytes] = 0;	// NULL-terminate it
                        response += CA2T(buff);
                    }
                } while( bytes );

                file->Close();
                delete file;
            }

            session->Close();
            delete session;
        }
    }
    catch(CInternetException * e)
    {
        e->Delete();
    }
    catch(...)
    {
    }

    log.Trace(_T("EC2 '%s' -> '%s'"), (LPCTSTR)url, (LPCTSTR)response);

    return ret;
}
Ejemplo n.º 5
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;
}
Ejemplo n.º 6
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;
}
Ejemplo n.º 7
0
DWORD WINAPI LoadUpdate (LPVOID param)
{
  CUpdateDlg* dlg = (CUpdateDlg*) param;

  if (dlg->autoCheck)
    UpdateVersion (NULL);

  char buf[2048];
  sprintf (buf, "Current version: %s\r\n"
                "Last version: %s\r\n",
                formatVersion (curVersion),
                formatVersion (lastVersion));
  dlg->SetDlgItemText (IDC_BUFFER, buf);

  if (curVersion < lastVersion)
  {
    CString log = buf;
    log += "\r\nLoading changelog...";
    dlg->SetDlgItemText (IDC_BUFFER, log);
    try
    {
      CInternetSession inet;
      CInternetFile* file = dynamic_cast<CInternetFile*> (inet.OpenURL (logURL));
      log = buf;
      log += "\r\nChangelog:\r\n";
      if (file != NULL)
      {
        while (file->ReadString (buf, sizeof buf - 5))
        {
          if (buf[0] == '*' && buf[1] == '*')
          {
            unsigned int ver = parseVersion (buf + 2);
            if (ver != 0 && ver <= curVersion)
              break;
          }
          log += buf;
        }
        log.Replace ("\n", "\r\n");
        dlg->SetDlgItemText (IDC_BUFFER, log);
        delete file;
      }
      else
        lastVersion = 0;
    }
    catch (CInternetException*)
    {
    }
  }

  return 0;
}
Ejemplo n.º 8
0
bool CUtil::IsReachableURL(CString sURL)
{
	CInternetSession Session;
	CHttpFile * pFile;
	try
	{
		pFile = (CHttpFile *) Session.OpenURL(sURL);
	}
	catch (CException * e)
	{
		e->Delete();
		pFile = NULL;
	}
	return (pFile != NULL);
}
Ejemplo n.º 9
0
void CVersionChecker::VersionCheckerThread()
{
	UINT totalBytesRead = 0;
	// The version tag usually shows up about 20,000 bytes in.
	char buffer[40000];
	try
	{
		CInternetSession	MySession;
		const wchar_t* const url = L"https://github.com/google/UIforETW/releases/";
		std::unique_ptr<CStdioFile> webFile(MySession.OpenURL(url));
		// Read into the buffer -- set the maximum to one less than the length
		// of the buffer.
		while (totalBytesRead < sizeof(buffer) - 1)
		{
			const UINT bytesRead = webFile->Read(buffer + totalBytesRead, sizeof(buffer) - 1 - totalBytesRead);
			if (!bytesRead)
				break;
			totalBytesRead += bytesRead;
		}
		webFile->Close();
	}
	catch (...)
	{
	}
	// Null terminate the buffer.
	buffer[totalBytesRead] = 0;
	const char* const marker = "<a href=\"/google/UIforETW/tree/";
	char* version_string = strstr(buffer, marker);
	if (version_string)
	{
		version_string += strlen(marker);
		if (strlen(version_string) > 4)
		{
			// String is something like: "v1.32\?..." and we want to cut off after
			// v1.32
			version_string[5] = 0;
			PackagedFloatVersion newVersion;
			newVersion.u = 0;
			if (sscanf_s(version_string, "v%f", &newVersion.f) == 1)
			{
				if (newVersion.f > kCurrentVersion)
				{
					pWindow_->PostMessage(WM_NEWVERSIONAVAILABLE, newVersion.u);
				}
			}
		}
	}
}
Ejemplo n.º 10
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;
}
Ejemplo n.º 11
0
Update_Status UpdateChecker::isUpdateAvailable(const Version& currentVersion)
{
	Update_Status updateAvailable = UPDATER_LATEST_STABLE;

	try {
		CInternetSession internet;
		CHttpFile* versionFile = (CHttpFile*) internet.OpenURL(versionFileURL,
															   1,
															   INTERNET_FLAG_TRANSFER_ASCII | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD,
															   NULL,
															   0);

		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)) {
				updateAvailable = UPDATER_ERROR;
			} else {
				int comp = compareVersion(currentVersion, latestVersion);

				if (comp < 0) {
					updateAvailable = UPDATER_UPDATE_AVAILABLE;
				} else if (comp > 0) {
					updateAvailable = UPDATER_NEWER_VERSION;
				}
			}

			delete versionFile;
		} else {
			updateAvailable = UPDATER_ERROR;
		}
	} catch (CInternetException* pEx) {
		updateAvailable = UPDATER_ERROR;
		pEx->Delete();
	}

	return updateAvailable;
}
Ejemplo n.º 12
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;
}
Ejemplo n.º 13
0
bool OpenUrl(CInternetSession& is, CString url, CStringA& str)
{
	str.Empty();

	try {
		CAutoPtr<CStdioFile> f(is.OpenURL(url, 1, INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_EXISTING_CONNECT));

		char buff[1024];
		for (int len; (len = f->Read(buff, sizeof(buff))) > 0; str += CStringA(buff, len)) {
			;
		}

		f->Close(); // must close it because the destructor doesn't seem to do it and we will get an exception when "is" is destroying
	} catch (CInternetException* ie) {
		ie->Delete();
		return false;
	}

	return true;
}
Ejemplo n.º 14
0
DWORD WINAPI UpdateVersion (LPVOID param)
{
  try
  {
    CInternetSession inet;
    CInternetFile* file = dynamic_cast<CInternetFile*> (inet.OpenURL (versionURL));
    char buf[256];
    if (file != NULL)
    {
      lastVersion = parseVersion (file->ReadString (buf, 255));
      delete file;
    }
    else
      lastVersion = 0;
  }
  catch (CInternetException*)
  {
  }
  return 0;
}
Ejemplo n.º 15
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;
}
Ejemplo n.º 16
0
int C51JobWebPost::GetGateWayIP(CString &strIP)
{
	CInternetSession session;
	CString strTemp = "";
	char temp[1001] = {0};
	CStdioFile *pFile = session.OpenURL("http://www.ip138.com/ip2city.asp");
	if (pFile != NULL)
	{
		long len = pFile->GetLength();
		if (len > 1000)
		{
			len = 1000;
		}		
		pFile->SeekToBegin();
		pFile->Read(temp,len);
		temp[len] = '\0';
		strTemp.Format("%s",temp);
		strTemp.MakeLower();
		if (strTemp.Find("您的ip地址是:[") !=-1)
		{
			CString strBefore = "您的ip地址是:[";
			CString strAfter = "]";
			strIP = GetKeyString(strTemp,strBefore,strAfter);
			pFile->Close();
			delete pFile;
			pFile = NULL;
			return 0;
		}
		if (pFile == NULL)
		{
			pFile->Close();
			delete pFile;
			pFile = NULL;
		}
		
	}
	return -1;
}
// Downloads the file at the given URL and returns the size of that file.
CString GetHttpFile(CInternetSession& session, const CString& strUrl)
{
   CString strResult;

   // Reads data from an HTTP server.
   CHttpFile* pHttpFile = NULL;

   try
   {
      // Open URL.
      pHttpFile = (CHttpFile*)session.OpenURL(strUrl, 1, 
         INTERNET_FLAG_TRANSFER_ASCII | 
         INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE);

      // Read the file.
      if(pHttpFile != NULL)
      {           
         UINT uiBytesRead;
         do
         {
            char chBuffer[10000];
            uiBytesRead = pHttpFile->Read(chBuffer, sizeof(chBuffer));
            strResult += chBuffer;
         }
         while (uiBytesRead > 0);
      }
    }
   catch (CInternetException)
   {
      // TODO: Handle exception
   }

   // Clean up and return.
   delete pHttpFile;

   return strResult;
}
Ejemplo n.º 18
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;
}
Ejemplo n.º 19
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;
}
Ejemplo n.º 20
0
inline UINT DownLoad(LPVOID pParam)
{
	while (1)
	{
		if(TempFileList.size()>0)
		{
			m_HeadCS.Lock();
			std::vector<std::string>::reverse_iterator rit = TempFileList.rbegin();
			LPCTSTR pszFace = (LPCTSTR)((std::string)*rit).c_str();;
			TempFileList.erase((++rit).base());
			m_HeadCS.Unlock();
			CString DATFile=TEXT("FaceImage.DAT");

			CFileFind	finder;
			BOOL	FF;

			FF=finder.FindFile(DATFile);
			if(!FF){
				CFile pwFile;
				pwFile.Open(DATFile,CFile::modeCreate);
				pwFile.Close();
			}
			CFile pwFile;
			pwFile.Open(DATFile,CFile::modeReadWrite| CFile::typeBinary);
			char FileNum[10];
			pwFile.Read(FileNum,9);
			sprintf(FileNum,"%d",atol(FileNum)+1);
			pwFile.SeekToBegin();
			pwFile.Write(FileNum,9);

			CInternetSession    is;
			CStdioFile        *psf;

			CString picUrl="http://www.17tzy.com/tzyBBS/avatars/common/0.bmp";

			psf = is.OpenURL( picUrl, 1, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD);

			BITMAPFILEHEADER bmfh;

			// 步骤1 读取文件头
			int nCount = psf->Read((LPVOID) &bmfh, sizeof(BITMAPFILEHEADER));

			// 判断是否是BMP格式的位图
			if(bmfh.bfType != BMP_HEADER_MARKER) 
			{
				continue;
			}

			// 计算信息头加上调色板的大小并分内存
			int nSize = bmfh.bfOffBits - sizeof(BITMAPFILEHEADER);
			LPBITMAPINFOHEADER m_pBMIH = (LPBITMAPINFOHEADER) new BYTE[nSize];

			// 步骤2 读取信息头和调色板
			nCount = psf->Read(m_pBMIH, nSize); 

			// 步骤3 读取图象数据
			LPBYTE	m_pBits = (LPBYTE) new BYTE[m_pBMIH->biSizeImage];
			nCount = psf->Read(m_pBits, m_pBMIH->biSizeImage); 

			//写入到DAT
			pwFile.SeekToEnd();
			pwFile.Write(pszFace,128);
			// 进行写操作
			pwFile.Write((LPVOID) &bmfh, sizeof(BITMAPFILEHEADER));
			pwFile.Write((LPVOID) m_pBMIH,  nSize);
			pwFile.Write((LPVOID) m_pBits, m_pBMIH->biSizeImage);

			m_HeadCS.Lock();
			ImgFileList.push_back(pszFace);
			m_HeadCS.Unlock();
		}
		
		Sleep(1);
	}
	return 0;

}
BOOL CT3000App::InitInstance()
{
	try
	{
	// InitCommonControlsEx() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
 	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	// Set this to include all the common control classes you want to use
	// in your application.
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	


	CWinAppEx::InitInstance();
	HRESULT hr;//


	if(!AfxInitRichEdit())
	{
		AfxMessageBox(IDS_INIT_RICHEDIT_ERROR);//
		return FALSE;//
	}

 
	if (!AfxSocketInit())//
	{
		AfxMessageBox(IDP_SOCKETS_INIT_FAILED);//
		return FALSE;//
	}
	// Initialize OLE libraries
	if (!AfxOleInit())
	{
		AfxMessageBox(IDP_OLE_INIT_FAILED);
		return FALSE;
	}
	AfxEnableControlContainer();

#if 1	
	try
	{

	TCHAR exeFullPath[MAX_PATH+1]; //
	GetModuleFileName(NULL, exeFullPath, MAX_PATH); //
	(_tcsrchr(exeFullPath, _T('\\')))[1] = 0;//
	g_strDatabasefilepath=exeFullPath;//
	g_strExePth=g_strDatabasefilepath;//
	CreateDirectory(g_strExePth+_T("Database"),NULL);//creat database folder;//
	g_strOrigDatabaseFilePath=g_strExePth+_T("T3000.mdb");//
	g_strDatabasefilepath+=_T("Database\\T3000.mdb");//

	CString FilePath;
	HANDLE hFind;//
	WIN32_FIND_DATA wfd;//
	hFind = FindFirstFile(g_strDatabasefilepath, &wfd);//
	if (hFind==INVALID_HANDLE_VALUE)//说明当前目录下无t3000.mdb
	{
		//CopyFile(g_strOrigDatabaseFilePath,g_strDatabasefilepath,FALSE);//
		  //没有找到就创建一个默认的数据库
		FilePath=g_strExePth+_T("Database\\T3000.mdb");
		HRSRC hrSrc = FindResource(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_T3000_DATABASE), _T("DB"));   
		HGLOBAL hGlobal = LoadResource(AfxGetResourceHandle(), hrSrc);   


		LPVOID lpExe = LockResource(hGlobal);   
		CFile file;
		if(file.Open(FilePath, CFile::modeCreate | CFile::modeWrite))    
			file.Write(lpExe, (UINT)SizeofResource(AfxGetResourceHandle(), hrSrc));    
		file.Close();    
		::UnlockResource(hGlobal);   
		::FreeResource(hGlobal);
	}//
	
	 
	FindClose(hFind);//
	g_strDatabasefilepath=(CString)FOR_DATABASE_CONNECT+g_strDatabasefilepath;//
	g_strImgeFolder=g_strExePth+_T("Database\\image\\");//
	CreateDirectory(g_strImgeFolder,NULL);//

 	JudgeDB();
	//CString strocx=g_strExePth+_T("MSFLXGRD.OCX");
	
	/*CStdioFile file;
	CString versionno;
	file.
	file.SetFilePath(_T("http://www.temcocontrols.com/ftp/software/T3000_Version.txt"));
	file.ReadString(versionno);
	file.Close();*/
	//CFile file;
//	file.Open(_T("http://www.temcocontrols.com/ftp/software/T3000_Version.txt"),modeRead);

 	InitModeName();//

	#if 0
	CInternetSession session;
	CInternetFile *file=NULL;
	try
	{
		INTERNET_PROXY_INFO  proxyinfo;
		proxyinfo.dwAccessType=INTERNET_OPEN_TYPE_PROXY;
		proxyinfo.lpszProxy=_T("192.168.0.4:8080 ");
		proxyinfo.lpszProxyBypass=NULL; 
		if (!session.SetOption(INTERNET_OPTION_PROXY,(LPVOID)&proxyinfo,sizeof(INTERNET_PROXY_INFO)))
		{
			AfxMessageBox(_T("UserName"));
		} 
		CString username=_T("alex");
		if(!session.SetOption(INTERNET_OPTION_PROXY_USERNAME,username.GetBuffer(),username.GetLength()+ 1)){

			AfxMessageBox(_T("UserName"));
		}
		CString password=_T("travel");
		if(!session.SetOption(INTERNET_OPTION_PROXY_PASSWORD,password.GetBuffer(),password.GetLength()+ 1)){

			AfxMessageBox(_T("Password"));
		}
		file=(CInternetFile*)session.OpenURL(_T("www.temcocontrols.com/ftp/software/T3000_Version.txt"));

	}
	catch (CInternetException* e)
	{
		file=NULL;
		e->Delete();

	}
	CString version;

	if (file)
	{
		while(file->ReadString(version)!=NULL){

		}
		AfxMessageBox(version);
	}
   #endif
	 

#endif

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	// of your final executable, you should remove from the following
	// the specific initialization routines you do not need
	// Change the registry key under which our settings are stored
	// TODO: You should modify this string to be something appropriate
	// such as the name of your company or organization
	SetRegistryKey(_T("Temco T3000 Application"));//
    LoadStdProfileSettings();  // Load standard INI file options (including MRU)//
	InitContextMenuManager();
	InitKeyboardManager();

	InitTooltipManager();
	CMFCToolTipInfo ttParams;
	ttParams.m_bVislManagerTheme = TRUE;
	theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL,
		RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams); 
#if 1
	hr=CoInitialize(NULL);//
	if(FAILED(hr)) 	//
	{
		AfxMessageBox(_T("Error Initialize the COM Interface"));//
		return FALSE;//
	}

#endif


	}
	catch (...)
	{
		AfxMessageBox(_T("Database operation to stop!"));

	}
	 
	
	CString registerfilename;
	 registerfilename=g_strExePth+_T("REG_msado15.bat");
	// ::ShellExecute(NULL, _T("open"), registerfilename.GetBuffer(), _T(""), _T(""), SW_HIDE);
	registerfilename=g_strExePth+_T("REG_MSFLXGRD.bat");
	//::ShellExecute(NULL, _T("open"), registerfilename.GetBuffer(), _T(""), _T(""), SW_HIDE);
	CString languagepath=g_strExePth+_T("\\Language");
	m_locale.AddCatalogLookupPath(languagepath);
	m_locale.SetLanguage(CLanguageLocale::LANGUAGE_ENGLISH);

	// Register the application's document templates.  Document templates
	//  serve as the connection between documents, frame windows and views

#ifndef Fance_Enable_Test
	CSingleDocTemplate* pDocTemplate;
	pDocTemplate = new CSingleDocTemplate(
		IDR_MAINFRAME,
		RUNTIME_CLASS(CT3000Doc),
		RUNTIME_CLASS(CMainFrame),       // main SDI frame window
		RUNTIME_CLASS(CT3000View));
#endif

#ifdef Fance_Enable_Test
	CSingleDocTemplate* pDocTemplate;
	pDocTemplate = new CSingleDocTemplate(
		IDR_MAINFRAME,
		RUNTIME_CLASS(CT3000Doc),
		RUNTIME_CLASS(CMainFrame),       // main SDI frame window
		RUNTIME_CLASS(CDialogCM5_BacNet));
#endif




	if (!pDocTemplate)
		return FALSE;


	


	AddDocTemplate(pDocTemplate);
	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo cmdInfo;	
	ParseCommandLine(cmdInfo);

	//cmdInfo.m_nShellCommand   =   CCommandLineInfo::FileNothing; //lsc


	// Dispatch commands specified on the command line.  Will return FALSE if
	// app was launched with /RegServer, /Register, /Unregserver or /Unregister.

	if (!ProcessShellCommand(cmdInfo))
		return FALSE;
 
	
	GdiplusStartupInput gdiplusStartupInput;//
	GdiplusStartup(&g_gdiplusToken, &gdiplusStartupInput, NULL);//

#if 1
////////////////////////////////////////////////////////
	_ConnectionPtr m_pCon;
	_RecordsetPtr m_pRs;
	m_pCon.CreateInstance(_T("ADODB.Connection"));
	hr=m_pRs.CreateInstance(_T("ADODB.Recordset"));
	if(FAILED(hr)) 	
	{
	    AfxMessageBox(_T("Load msado12.dll erro"));
	      return FALSE;
	}
	m_pCon->Open(g_strDatabasefilepath.GetString(),"","",adModeUnknown);
	m_pRs->Open(_T("select * from Userlogin"),_variant_t((IDispatch *)m_pCon,true),adOpenStatic,adLockOptimistic,adCmdText);		
	int nRecord=m_pRs->GetRecordCount();
	if (nRecord<=0)
	{
		g_bPrivilegeMannage=FALSE;
	}
	else
	{
		int nUse;
		_variant_t temp_variant;
		temp_variant=m_pRs->GetCollect("USE_PASSWORD");//
		if(temp_variant.vt!=VT_NULL)
			nUse=temp_variant;
		else
			nUse=0;
		if(nUse==-1)
		{
			g_bPrivilegeMannage=TRUE;
		}
		else
		{
			g_bPrivilegeMannage=FALSE;
		}
	}
	m_pRs->Close();
	m_pCon->Close();



	if (g_bPrivilegeMannage)
	{//for just quick debug,only on this computer
		if(!user_login())
		{
			AfxMessageBox(_T("Error password!"));	
			return false;
		}
		
	}

#endif

	

  	((CMainFrame*)m_pMainWnd)->InitViews();//

   	m_pMainWnd->SetWindowText(_T("T3000 Building Automation System"));//
  	m_pMainWnd->ShowWindow(SW_SHOW);
  	m_pMainWnd->UpdateWindow();
     

	}
	catch (...)
	{
	//	AfxMessageBox(_T("Double click 'REG_msado15.dll',Please!\nAt C:\\Program Files\\Temcocontrols\\T3000"));

// 		CString strFilter = _T("hex File;bin File|*.hex;*.bin|all File|*.*||");
// 		CFileDialog dlg(true,_T("hex"),NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_EXPLORER,strFilter);
// 		dlg.DoModal();

//		CFileDialog dlg(true,NULL,_T("C:\Program Files\Common Files\System\ado"));
		//dlg.lpstrInitialDir = "..\\hisdata";
		//dlg.op
////
	//		OPENFILENAME

		
//		if (dlg.DoModal()==IDOK)
//		{
// 			path = dlg.GetPathName();
// 			pLogFile = fopen("Log.txt", "wt+");   
// 			fprintf(pLogFile, "%s", (LPCSTR)path); 
// 			fclose(pLogFile);
// 			pLogFile = NULL; 
//		}


// 		CFileDialog fileDlg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
// 			NULL,NULL);//_T("工作表(*.xls)|*.xls|文本文件(*.txt)|*.txt||")
// 		fileDlg.m_ofn.lpstrInitialDir = _T("C:\\Program Files\\Temcocontrols\\T3000\\REG_msado15.dll.bat");
// 		fileDlg.DoModal();



		//::ShellExecute(NULL, _T("open"), _T("C:\\Program Files\\Temcocontrols\\T3000\\REG_msado15.dll.bat"), _T(""), _T(""), SW_SHOW);
		//vcredist_x86.zip
		
	//	::ShellExecute(NULL, _T("open"), _T("C:\\Program Files\\Temcocontrols\\T3000\\vcredist_x86.zip"), _T(""), _T(""), SW_SHOW);
		//这个要先试试,当电脑没有安装这个文件时,如何捕获这个信息,然后再执行这个。
		AfxMessageBox(_T("Open'T3000'Again,Please!"));


		return TRUE;

	}


	return TRUE;
}
Ejemplo n.º 22
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;
}
Ejemplo n.º 23
0
std::string CallHprose::DownloadHprose( std::string strHproseDownloadUrl, std::string strFileDir, std::string strFileName )
{
	CInternetSession sess;
	CHttpFile* pHttpFile;
	try
	{
		pHttpFile=(CHttpFile*)sess.OpenURL(strHproseDownloadUrl.c_str());
	}
	catch(CException* e)
	{
		pHttpFile = 0;
		TCHAR msg[1024];
		memset(msg, 0, 1024);
		e->GetErrorMessage(msg, 1023, NULL);
		ZTools::WriteZToolsFormatLog("打开URL失败:%s", msg);
		return "";
	}

	DWORD dwStatus;
	DWORD dwBuffLen = sizeof(dwStatus);
	BOOL bSuccess = pHttpFile->QueryInfo(HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwBuffLen);

	int nReadBlockSize = 256*1024;
	char* pBuffer = new char[nReadBlockSize];
	if( bSuccess && dwStatus>= 200&& dwStatus<300 )
	{
		if (strFileName.length() == 0)
		{
			CString sContentDisposition;
			DWORD dwIndex = 0;
			bSuccess = pHttpFile->QueryInfo(HTTP_QUERY_CONTENT_DISPOSITION, sContentDisposition, &dwIndex);
			std::string strContentDisposition((LPCTSTR)sContentDisposition);
			std::string strKeyBegin("filename=\"");
			std::string strKeyEnd("\"");

			if (!strContentDisposition.empty())
			{
				size_t nBegin = strContentDisposition.find(strKeyBegin) + strKeyBegin.length();
				if (nBegin < strContentDisposition.length())
				{
					size_t nEnd = strContentDisposition.find(strKeyEnd, nBegin);
					strFileName = strContentDisposition.substr(nBegin, nEnd - nBegin);
				}
				strFileName = deescapeURL(strFileName);
				ZTools::UTF8ToMB(strFileName);
			}
		}

		if (strFileName.length() == 0)
		{
			delete[] pBuffer;
			pBuffer = NULL;
			pHttpFile->Close();
			//delete pHttpFile;
			sess.Close();
			ZTools::WriteZToolsFormatLog("没有找到文件名");
			return "";
		}

		std::replace(strFileDir.begin(), strFileDir.end(), '/', '\\');
		strFileDir.erase(strFileDir.find_last_not_of('\\') + 1);
		std::replace(strFileName.begin(), strFileName.end(), '/', '\\');
		strFileName.erase(0, strFileName.find_first_not_of('\\'));
		std::string strFilePath = ZTools::FormatString("%s\\%s", strFileDir.c_str(), strFileName.c_str());
		//先下载到临时文件中,下载成功后重命名
		std::string strFilePathTemp = ZTools::FormatString("%s\\%s", strFileDir.c_str(), GuidToString(CreateGuid()).c_str());

		if (!MakeSureDirectoryPathExists(strFilePath.c_str()))
		{
			delete[] pBuffer;
			pBuffer = NULL;
			pHttpFile->Close();
			//delete pHttpFile;
			sess.Close();
			ZTools::WriteZToolsFormatLog("创建文件夹失败:%s", strFilePath.c_str());
			return "";
		}

		CFile fileWrite;
		ULONGLONG dwFileLen = 0;
		DWORD dwWriteIndex = 0;
		dwFileLen = pHttpFile->SeekToEnd();
		pHttpFile->SeekToBegin();
		if(fileWrite.Open(strFilePathTemp.c_str(), CFile::modeWrite|CFile::modeCreate))
		{
			int nCount = 0;
			while(dwWriteIndex < dwFileLen)
			{
				nCount = pHttpFile->Read(pBuffer, nReadBlockSize);
				fileWrite.Write(pBuffer, nCount);
				dwWriteIndex += nCount;                
			}
			fileWrite.Close();

			rename(strFilePathTemp.c_str(), strFilePath.c_str());

			delete[] pBuffer;
			pBuffer = NULL;
			pHttpFile->Close();
			delete pHttpFile;
			sess.Close();

			if (PathFileExists(strFilePath.c_str()))
			{
				return strFilePath;
			}
			else
			{
				return "";
			}
		}
		else
		{
			delete[] pBuffer;
			pBuffer = NULL;
			pHttpFile->Close();
			//delete pHttpFile;
			sess.Close();
			ZTools::WriteZToolsFormatLog("本地文件%s打开出错", strFilePath.c_str());
			return "";
		}
	}
	else
	{
		delete[] pBuffer;
		pBuffer = NULL;
		pHttpFile->Close();
		//delete pHttpFile;
		sess.Close();
		ZTools::WriteZToolsFormatLog("打开网页文件出错,错误码:%d", dwStatus);
		return "";
	}

	delete[] pBuffer;
	pBuffer = NULL;
	pHttpFile->Close();
	//delete pHttpFile;
	sess.Close();	
	return "";
}
Ejemplo n.º 24
0
bool CMainDlg::GetUrlServer()
{
	m_mapUrl.clear();
	CString url(_T("http://139.129.60.122/UpData/forumupdata.json"));    
	CInternetSession session;


	std::string strHtml;
	try
	{
		CHttpFile* pfile = (CHttpFile*)session.OpenURL(url,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())
	{
		CStdioFile myFile;
		CString strLine; 
		string strpath = theApp.m_strInsPath;
		strpath +="\\polopointsUpdate.json";
		if(myFile.Open((LPCTSTR)(LPSTR)strpath.c_str(), CFile::modeRead))
		{
			while(myFile.ReadString(strLine))
			{
				strHtml +=strprintf("%s",strLine);
			}
			//读取
			myFile.Close();
		}else{
			return false;
		}
	}else{
		//创建
		CStdioFile  File;
		string strpath = theApp.m_strInsPath;
		strpath +="\\polopointsUpdate.json";
		File.Open((LPCTSTR)(LPSTR)strpath.c_str(),CFile::modeWrite | CFile::modeCreate);  
		File.WriteString(strHtml.c_str());
		File.Close();
	}


	Json::Reader reader;  
	Json::Value root; 

	if (reader.parse(strHtml, root))
	{
		if (!root.isObject())
		{
			return false;
		}
		Json::Value rootcn = root["Chinese"];
		if (rootcn.isNull()&& !rootcn.isArray())
		{
			return false;
		}
		int index = rootcn.size();
		for (int i = 0;i <index;i++)
		{
			Json::Value  msgroot = rootcn[i];
			Json::Value value = msgroot["msn"];
			if (value.isNull())
			{
				return false;
			}
			CString key = msgroot["msn"].asCString();
			value = msgroot["url"];
			if (value.isNull())
			{
				return false;
			}
			CString valuetemp = msgroot["url"].asCString();
			m_mapUrl[key] = valuetemp;
		}
		return true;
	}
	return false;
}
Ejemplo n.º 25
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;
}
Ejemplo n.º 26
0
BOOL CLoginDlg::AuthWeb()
{
	CString csBuff;
	char		httpBuff[1024];
	CString		csHash;
	CMD5		md5SPIP;
	int			nBytes;
	unsigned char	lpszBuffer[16];

	// Authentication for web pages
	TRY 
	{
		CInternetSession session;
		CString csIdSession, csSession;

		csBuff.Empty();
		memset(httpBuff, 0, 1024);
		session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 1000);
		session.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 3);

		CFile*	pf	= session.OpenURL(URL_LOGIN_WEB, 1, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD);

		while(nBytes = pf->Read(httpBuff, 1024)) 
		{
			csBuff	+= httpBuff;
		}
		pf->Close();
		if(csBuff.Find('/') != -1)
		{
			csSession	= csBuff.Left(csBuff.Find('/'));
			csIdSession	= csBuff.Mid(csSession.GetLength()+1);

			md5SPIP.SetContent(APP.m_csPassword + csSession);
			memset(lpszBuffer, 0, 16);
			md5SPIP.GetDigest(lpszBuffer);
			csHash	= md5SPIP.ConvertToAscii(lpszBuffer);
			APP.m_bAuthWeb	= TRUE;

			TRY
			{
				CHttpConnection*	phttp	= session.GetHttpConnection(_T(RYZOM_HOST));
				CHttpFile*			pfile	= phttp->OpenRequest(CHttpConnection::HTTP_VERB_POST, "/betatest/betatest_login_valid.php");
				if(pfile)
				{
					CString csHeaders = _T("Content-Type: application/x-www-form-urlencoded");
					CString csFormParams = _T("txtLogin="******"&digest="+csHash+"&idsession="+csIdSession);
					
					TRY
					{
						csBuff.Empty();
						pfile->SendRequest(csHeaders, (LPVOID)(LPCTSTR)csFormParams, csFormParams.GetLength());

					   UINT nRead = pfile->Read(csBuff.GetBuffer(15000), 14999);
					   csBuff.ReleaseBuffer();
					   csBuff.SetAt(nRead, 0);
					   if(csBuff.Find("/news/") == -1)
					   {
							APP.m_bAuthWeb	= FALSE;
					   }
					}
					CATCH_ALL(error)
					{
						APP.m_bAuthWeb	= FALSE;
					}
					END_CATCH_ALL;

					delete pfile;
				}
				else
				{
					APP.m_bAuthWeb	= FALSE;
				}
			}
			CATCH_ALL(error)
			{
				APP.m_bAuthWeb	= FALSE;
			}
			END_CATCH_ALL;
		}
Ejemplo n.º 27
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;
}
Ejemplo n.º 28
0
CHAR* WebFetcher::GetHttp(LPCSTR lpServerName)
{

        // start download file
        char   *pBuf = NULL ;
        int    nBufLen = 0 ;
        TRY
        {
            // connection
            CInternetSession   sess ;
            sess.SetOption (INTERNET_OPTION_CONNECT_TIMEOUT, 30 * 1000) ;
            sess.SetOption (INTERNET_OPTION_CONNECT_BACKOFF, 1000) ;
            sess.SetOption (INTERNET_OPTION_CONNECT_RETRIES, 1) ;

            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);}

            // connection status
            CString      str ;
            pF->QueryInfo (HTTP_QUERY_STATUS_CODE, str) ;

            // Proxy Authentication Required
            if (str == _T("407"))
            {
                CString   strUsername, strPassword ;
//                pPara->pThis->df_Notify (GetMsg_ProxyValidate(), &WM_DLF_PROXY_VALIDATE(&lpServerName, &strUsername, &strPassword)) ;
                pF->SetOption (INTERNET_OPTION_PROXY_USERNAME, (VOID*)(LPCTSTR)strUsername, strUsername.GetLength()) ;
                pF->SetOption (INTERNET_OPTION_PROXY_PASSWORD, (VOID*)(LPCTSTR)strPassword, strPassword.GetLength()) ;
                pF->SendRequest (NULL) ;
            }

            pF->QueryInfo (HTTP_QUERY_STATUS_CODE, str) ;
            if (str != _T("200"))
            {
                pF->Close() ;
                delete pF ;
                AfxThrowInternetException(1);
            }

            // confirm update
            pF->QueryInfo (HTTP_QUERY_LAST_MODIFIED, str) ;
/*            if (!pPara->pThis->df_Notify (GetMsg_CheckTime(), &WM_DLF_CHECKTIME(&lpServerName, &str)))
            {
                pF->Close() ;
                delete pF ;
                AfxThrowInternetException(1);
            }
*/
            // start download
            pF->QueryInfo (HTTP_QUERY_CONTENT_LENGTH, str) ; // file's length
  //          pPara->pThis->df_Notify (GetMsg_StartDownload(), &pPara->strFileURL) ;

            if (_ttoi(str))
            {
                // know file's size
                int     nLen = (nBufLen = _ttoi(str)) ;
                char    * p = (pBuf = new char[nLen+8]) ;
                ZeroMemory (p, nLen+8) ;

               // while (IsWindow(pPara->pThis->GetSafeHwnd()))
				while (true)
                {
                    // download 8K every
                    int   n = pF->Read (p, (nLen < 8192) ? nLen : 8192) ;
                    if (n <= 0)
                        break ; // success exit
                    p += n ; nLen -= n ;

                    //pPara->pThis->df_Notify (GetMsg_Progress(), &WM_DLF_PROGRESS(&pPara->strFileURL, nBufLen-nLen, nBufLen)) ;
                }

                // interrupted
                if (nLen != 0)
                {
                    delete[] pBuf;
					pBuf=NULL;
                    nBufLen = 0 ;
                }
            }
            else
            {
                // don't know file's size, save context to a temp file.
                bstr_t   strFile = QueryTempFilePath() ;
                CFile    outFile (strFile, CFile::modeCreate|CFile::modeReadWrite) ;
                int      n = (int)pF->GetLength() ;
                while (n)
                {
                    char   * pa = new char[n] ;
                    n = pF->Read (pa, n) ;
                    outFile.Write (pa, n) ;
               //     pPara->pThis->df_Notify (GetMsg_Progress(), &WM_DLF_PROGRESS(&pPara->strFileURL, (int)outFile.GetLength(), 0)) ;
                    n = (int)pF->GetLength() ;
                    delete[] pa ;
                }
                outFile.Close() ;

                // success
                if (n == 0)
                {
                    DWORD   dw ;
                    if (::InternetQueryDataAvailable ((HINTERNET)(*pF), &dw, 0, 0) && (dw == 0))
                    {
                        LoadFileToBuffer (strFile, pBuf, nBufLen) ;
                    }
                }
                ::DeleteFile(strFile) ;
            }

            pF->Close() ;
            delete pF ;
        }
        CATCH_ALL(e) {}
        END_CATCH_ALL
/*
        if (pBuf)
        {
            //pPara->pThis->df_Notify (GetMsg_DownFinished(), &WM_DLF_FINISHED(&pPara->strFileURL, pBuf, nBufLen)) ;
            delete[] pBuf ;
        }
        else
        {
            //pPara->pThis->df_Notify (GetMsg_Error(), &pPara->strFileURL) ;
        }*/
		//AfxMessageBox(pBuf);
        return pBuf;
    //}
}