示例#1
0
BOOL IsValidPatchFile(LPCTSTR szFilename)
{
	// MSCF
	const CHAR szMagicMsu[] = {'M', 'S', 'C', 'F'};
	const CHAR szMagicExe[] = {'M', 'Z'};
	
	const int TEST_BUFFER_SIZE = 4;
	CHAR buffer[TEST_BUFFER_SIZE] = {0};

	BOOL bMatched = FALSE;
	CAtlFile file;
	if(S_OK == file.Create(szFilename, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING) )
	{		
		if(SUCCEEDED(file.Read(buffer, TEST_BUFFER_SIZE)))
		{
			LPCTSTR szDot = _tcsrchr(szFilename, _T('.'));
			if(szDot)
			{
				++szDot;
				if(_tcsicmp(szDot, _T("msu"))==0)
				{
					bMatched = memcmp(buffer, szMagicMsu, 4)==0;
				}
				else if(_tcsicmp(szDot, _T("exe"))==0)
				{
					bMatched = memcmp(buffer, szMagicExe, 2)==0;
				}
				else
					bMatched = TRUE;
			}
		}
		file.Close();
	}
	return bMatched;
}
示例#2
0
bool Speller::SaveWords( LPCTSTR path, const WordContainer& words )
{
	CAtlFile file;
	bool result = false;

	if (SUCCEEDED(file.Create(path, GENERIC_WRITE, FILE_SHARE_READ, OPEN_ALWAYS)))
	{
		WordContainer::const_iterator it = words.begin();
		std::vector<char> data;

		for (; it != words.end(); ++it) 
		{
			data.clear();
			const StringType text = *it + _T("\n");

			UTF16toUTF8(text.c_str(), text.size(), data);

			if (!data.empty())
				file.Write(&data[0], static_cast<DWORD>(data.size()));
		}

		result = true;
	}

	return result;
}
示例#3
0
bool Speller::LoadWords( LPCTSTR path, WordContainer& words )
{
	CAtlFile file;
	bool result = false;

	if (SUCCEEDED(file.Create(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING))) {
		ULONGLONG size = 0;
		file.GetSize(size);

		if (size > 0) {
			std::vector<char> data(static_cast<unsigned>(size));

			if (SUCCEEDED(file.Read(&data[0], static_cast<DWORD>(data.size())))) {
				std::vector<wchar_t> unicode;
				UTF8toUTF16(&data[0], data.size(), unicode);

				std::wistringstream in(std::wstring(&unicode[0], unicode.size()));
				typedef std::istream_iterator<StringType,StringType::value_type,
					StringType::traits_type> iterator;

				std::copy(iterator(in),iterator(),std::inserter(words,words.end()));
				result = true;
			}
		}
	}

	return result;
}
示例#4
0
BOOL file_put_contents(LPCTSTR lpszFilename, BYTE *pBuffer, INT nLen)
{
	CAtlFile file;
	if( FAILED( file.Create(lpszFilename, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, CREATE_ALWAYS) ) )
		return FALSE;
	
	file.Write( pBuffer, nLen );
	file.Close();
	return TRUE;
}
示例#5
0
INT64 file_get_size(LPCTSTR lpszFilename)
{
	CAtlFile file;
	if( FAILED( file.Create(lpszFilename, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING) ) )
		return 0;

	ULONGLONG filesize = 0;
	file.GetSize(filesize);
	return filesize;
}
示例#6
0
	virtual void _output_initialize()
	{
		if (SUCCEEDED(_file.Create(_T("debug.txt"), GENERIC_WRITE, FILE_SHARE_READ, OPEN_ALWAYS)))
		{
			SYSTEMTIME st;
			::GetLocalTime(&st);
			debugout(_T("----- %04d-%02d-%02d %02d:%02d:%02d -----"), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
		}
		else
			_out_type = DEBUGOUT_STRING;
	}
示例#7
0
void DebugTools::SelfPurecallHandler(void)
{
	wchar_t filename[MAX_PATH];
	::GetModuleFileNameW(nullptr,filename,MAX_PATH);
	wcscat_s(filename,L".dmp");
	::MessageBox(nullptr,filename,L"PurecallHandler",0);
	CAtlFile file;
	file.Create(filename,FILE_WRITE_DATA,FILE_SHARE_READ,CREATE_ALWAYS);
	BOOL res=::MiniDumpWriteDump(::GetCurrentProcess(),::GetCurrentProcessId(),file,MiniDumpNormal,nullptr,nullptr,nullptr);
	file.Close();
	exit(0);
}
示例#8
0
bool CCoBroker::HandleRequestService(const tstring& dstUserId, ULONG dstSvcId, const tstring& srcUserId, ULONG srcSvcId, ULONG rId, ULONG rType, ULONG param, const tstring& params)
{
TRY_CATCH
	HRESULT result;
	EBrokerStartTypes startParam=BST_SAME;
	tstring url;
	{
		tstring::size_type iBeginUrl=params.find(_T(";;"));
		if(iBeginUrl!=tstring::npos)
		{
			tstring::size_type iEndUrl=params.find(_T(";;"),iBeginUrl+2);
			url=params.substr(iBeginUrl+2,(tstring::npos!=iEndUrl)?iEndUrl-iBeginUrl-2:tstring::npos);
		}
	}
	Log.Add(_MESSAGE_,_T("***HandleRequestService*** url=[%s]"),url.c_str());

	const TCHAR SESSION_ID_PARAMETER_NAME[]=_T("supportRequestId=");
	tstring::size_type iWebSId=url.find(SESSION_ID_PARAMETER_NAME);
	if(iWebSId!=tstring::npos&&iWebSId+_countof(SESSION_ID_PARAMETER_NAME)<url.size())
	{
		iWebSId+=_countof(SESSION_ID_PARAMETER_NAME)-1;
		tstring::size_type iWebSIdEnd=url.find_first_of(_T("&#"),iWebSId);
		if(tstring::npos==iWebSIdEnd)
			iWebSIdEnd=url.length();
		tstring sId=url.substr(iWebSId,iWebSIdEnd-iWebSId);
		Log.Add(_MESSAGE_,_T("***HandleRequestService*** sId=[%s]"),sId.c_str());
		SHA1Hash hash_buf;
		CRYPTO_INSTANCE.MakeHash((char*)sId.c_str(),sId.length()*sizeof(tstring::value_type),hash_buf);
		tstring hashString;
		for(int i=0;i<sizeof(hash_buf);++i)
			//hashString+=i2tstring((int)(unsigned char)hash_buf[i],16);
			hashString+=Format(_T("%02x"),(int)(unsigned char)hash_buf[i]);
		url.insert(iWebSIdEnd,tstring(_T("&sri="))+hashString);
	}
	//Log.Add(_WARNING_,_T("***HandleRequestService*** HASHING TURN OFF"));
	Log.Add(_MESSAGE_,_T("***HandleRequestService*** url=[%s]"),url.c_str());
	
	CAtlFile cnfg;
	if(S_OK==cnfg.Create(Format(_T("%s\\%s"),GetModulePath(GetCurrentModule()).c_str(),_T("Broker.cfg")).c_str(),GENERIC_READ,0,OPEN_EXISTING))
	{
		TRY_CATCH
			DWORD readLen=0;
			readLen=GetFileSize(cnfg.m_h,NULL);
			if(INVALID_FILE_SIZE==readLen&&readLen>32768)
				throw MCException_Win("Broker.cfg size obtaining failed or file too large");
			std::auto_ptr<char> buf(new char[readLen]);
			if(!ReadFile(cnfg.m_h,buf.get(),readLen,&readLen,NULL))
				throw MCException_Win("Broker.cfg file reading failed");
			startParam=EBrokerStartTypes(atol(buf.get()));
			Log.Add(_MESSAGE_,_T("***HandleRequestService*** file startParam=[0x%x]"),startParam);
		CATCH_LOG()
	}
示例#9
0
bool CDTManager::SetContiInfo( CString file,CString& url,int64& len,int& cur )
{
	CAtlFile f;
	if(ERROR_SUCCESS!=f.Create(file,FILE_GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,CREATE_ALWAYS)!=ERROR_SUCCESS)
	{
		return false;
	}
	f.Write(&len,sizeof len);
	f.Write(&cur,sizeof cur);
	f.Write(url.GetBuffer(),url.GetLength()*2+2);
	f.Close();
	return true;
}
示例#10
0
DWORD CWinTrustVerifier::VerifyFile(LPCWSTR pwszFileFullPath, CWinTrustSignerInfoChain* pSignInfoChain)
{
    assert(pwszFileFullPath);
    CAtlFile hFile;
    HRESULT  hr = hFile.Create(
        pwszFileFullPath,
        GENERIC_READ,
        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
        OPEN_EXISTING);
    if (FAILED(hr))
        return hr;

    return VerifyFile(pwszFileFullPath, hFile, pSignInfoChain);
}
示例#11
0
BOOL CWinTrustVerifier::IsPEFile(LPCWSTR pwszFileFullPath)
{
    assert(pwszFileFullPath);

    CAtlFile hFile;
    HRESULT  hr = hFile.Create(
        pwszFileFullPath,
        GENERIC_READ,
        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
        OPEN_EXISTING);
    if (FAILED(hr))
        return hr;

    return IsPEFile(hFile);
}
示例#12
0
HICON	CFaviconManager::GetFaviconFromURL(LPCTSTR url)
{
    CString strFaviconURL;
    CString strHtmlPath;
    if (SUCCEEDED(::URLDownloadToCacheFile(NULL, url, strHtmlPath.GetBuffer(MAX_PATH), MAX_PATH, 0, NULL))) {
        strHtmlPath.ReleaseBuffer();
        CAtlFile	file;
        if (SUCCEEDED(file.Create(strHtmlPath, GENERIC_READ, 0, OPEN_EXISTING))) {
            enum { kMaxReadSize = 2000 };
            unique_ptr<char[]>	htmlContent(new char[kMaxReadSize + 1]);
            DWORD	dwReadSize = 0;
            file.Read((LPVOID)htmlContent.get(), kMaxReadSize, dwReadSize);
            htmlContent[dwReadSize] = '\0';

            boost::regex	rx("<link (?:(?<rel>rel=[\"']?(?:shortcut icon|icon)[\"']?) (?<href>href=[\"']?(?<url>[^ \"]+)[\"']?)|(?<href>href=[\"']?(?<url>[^ \"]+)[\"']?) (?<rel>rel=[\"']?(?:shortcut icon|icon)[\"']?))[^>]+>", boost::regex::icase);
            boost::cmatch	result;
            if (boost::regex_search(htmlContent.get(), result, rx)) {
                CString strhref = result["url"].str().c_str();
                DWORD	dwSize = INTERNET_MAX_URL_LENGTH;
                ::UrlCombine(url, strhref, strFaviconURL.GetBuffer(INTERNET_MAX_URL_LENGTH), &dwSize, 0);
                strFaviconURL.ReleaseBuffer();
            }
        }
    }
    if (strFaviconURL.IsEmpty()) {	// ルートにあるFaviconのアドレスを得る
        DWORD cchResult = INTERNET_MAX_URL_LENGTH;
        if (::CoInternetParseUrl(url, PARSE_ROOTDOCUMENT, 0, strFaviconURL.GetBuffer(INTERNET_MAX_URL_LENGTH), INTERNET_MAX_URL_LENGTH, &cchResult, 0) == S_OK) {
            strFaviconURL.ReleaseBuffer();
            strFaviconURL += _T("/favicon.ico");
        }
    }

    if (strFaviconURL.GetLength() > 0) {
        CCritSecLock	lock(s_cs);
        CIconHandle hIcon = GetFavicon(strFaviconURL);
        if (hIcon == NULL) {
            hIcon = _DownloadFavicon(strFaviconURL);
            if (hIcon) {
                s_mapIcon[std::wstring(strFaviconURL)] = hIcon;
                hIcon	= hIcon.DuplicateIcon();
            }
        } else {
            hIcon = hIcon.DuplicateIcon();
        }
        return hIcon;
    }
    return NULL;
}
示例#13
0
BOOL CTcpAgent::SendSmallFile(CONNID dwConnID, LPCTSTR lpszFileName, const LPWSABUF pHead, const LPWSABUF pTail)
{
	ASSERT(lpszFileName != nullptr);

	CAtlFile file;
	HRESULT hr = file.Create(lpszFileName, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING);

	if(SUCCEEDED(hr))
	{
		ULONGLONG ullLen;
		hr = file.GetSize(ullLen);

		if(SUCCEEDED(hr))
		{
			ULONGLONG ullTotal = ullLen + (pHead ? pHead->len : 0) + (pTail ? pTail->len : 0);

			if(ullLen > 0 && ullTotal <= MAX_SMALL_FILE_SIZE)
			{
				CAtlFileMapping<> fmap;
				hr = fmap.MapFile(file);

				if(SUCCEEDED(hr))
				{
					WSABUF bufs[3] = {0};

					bufs[1].len = (ULONG)ullLen;
					bufs[1].buf = fmap;

					if(pHead) memcpy(&bufs[0], pHead, sizeof(WSABUF));
					if(pTail) memcpy(&bufs[2], pTail, sizeof(WSABUF));

					return SendPackets(dwConnID, bufs, 3);
				}
			}
			else if(ullLen == 0)
				hr = HRESULT_FROM_WIN32(ERROR_FILE_INVALID);
			else
				hr = HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE);
		}
	}

	::SetLastError(hr & 0x0000FFFF);

	return FALSE;
}
示例#14
0
BOOL CXmlManager::LoadFromFile( LPCTSTR szfilename )
{
	BOOL ret = FALSE;
	CAtlFile file;
	if(S_OK == file.Create(szfilename, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING) )
	{
		int nsize = ::GetFileSize(file, NULL);
		char* szbuf = new char[nsize + 1];
		if(szbuf)
		{
			if(S_OK == file.Read(szbuf, nsize))
			{
				szbuf[nsize] = 0;
				ret = LoadFromString(szbuf, nsize);
			}
			delete [] szbuf;
		}
	}
	return ret;
}
示例#15
0
bool CDTManager::GetContiInfo( CString file,CString& url,int64& len,int& cur )
{
	CAtlFile f;
	if(ERROR_SUCCESS!=f.Create(file,FILE_GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,OPEN_EXISTING)!=ERROR_SUCCESS)
	{
		return false;
	}
	if(ERROR_SUCCESS!=f.Read(&len,sizeof len)&&f.Read(&cur,sizeof cur)!=ERROR_SUCCESS)
		return false;
	f.Read(&cur,sizeof cur);
	ULONGLONG flen=0;
	f.GetSize(flen);
	wchar_t* buf=new wchar_t[((size_t)flen)/2+1];
	ZeroMemory(buf,((size_t)flen)/2+1);
	f.Read(buf,(DWORD)flen);
	url=buf;
	delete [] buf;
	f.Close();
	return true;
}
示例#16
0
BOOL WaitFlagFile(LPCTSTR pszFile, DWORD dwWaitTime, BOOL bDeleteFlagFile, DWORD dwCheckInterval)
{
	BOOL bRet = FALSE;

	BOOL isInfine = (dwWaitTime == INFINITE);
	DWORD dwBeginTime = ::GetTickCount();
	while(isInfine || ::GetTickCount() - dwBeginTime < dwWaitTime)
	{
		CAtlFile f;
		if(SUCCEEDED(f.Create(pszFile, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING)))
		{
			if(bDeleteFlagFile)
				FHDeleteFile(pszFile);
			bRet = TRUE;
			break;
		}
		::Sleep(dwCheckInterval);
	}
	return bRet;
}
/**
 * @param uNotifyCode - notification code if the message is from a control. If the message is from an accelerator, this value is 1. If the message is from a menu, this value is zero.
 * @param nID - specifies the identifier of the menu item, control, or accelerator.
 * @param hWndCtl - handle to the control sending the message if the message is from a control. Otherwise, this parameter is NULL.
 */
void CExpressModeDlg::OnSave(UINT /*uNotifyCode*/, int /*nID*/, HWND /*hWndCtl*/)
{
	try
	{
		if (! ValidateXMLDocument())
			return;
		CString strLogFile;
		GetReportFileName(strLogFile);
		CCustomFileDialog dlgSaveFile(FALSE,
			_T("xml"),
			strLogFile,
			OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST,
			_T("Log Files\0*.log\0All Files\0*.*\0"),
			m_hWnd);
		if (dlgSaveFile.DoModal(m_hWnd) == IDOK)
		{
			CAtlFile fileLog;
			if (fileLog.Create(dlgSaveFile.m_szFileName, GENERIC_WRITE, 0, CREATE_ALWAYS) == S_OK)
			{
				CString strLogText;
				GetErrorLog(strLogText);
				CT2CW pchUnicodeText(strLogText);
				int nDestSize = AtlUnicodeToUTF8(pchUnicodeText, strLogText.GetLength(), NULL, 0);
				if (nDestSize >= 0)
				{
					static const BYTE arrUTF8Preamble[] = { 0xEF, 0xBB, 0xBF };
					int nTotalDestSize = sizeof(arrUTF8Preamble) + nDestSize;
					boost::scoped_array<CHAR> pchDest(new CHAR[nTotalDestSize]);
					CopyMemory(pchDest.get(), arrUTF8Preamble, sizeof(arrUTF8Preamble));
					AtlUnicodeToUTF8(pchUnicodeText, strLogText.GetLength(), pchDest.get() + sizeof(arrUTF8Preamble), nDestSize);
					fileLog.Write(pchDest.get(), nTotalDestSize);
				}
			}
		}
	}
	catch (std::exception& error)
	{
		HandleException(error);
	}
}
int OpenMyFileMap()
{
   // Create the file-mapping object.
   CAtlFileMappingBase myFileMap;

   // Create a file.
   CAtlFile myFile;
   myFile.Create(_T("myMapTestFile"),
      GENERIC_READ|GENERIC_WRITE|STANDARD_RIGHTS_ALL,
      FILE_SHARE_READ|FILE_SHARE_WRITE,
      OPEN_ALWAYS);

   // The file handle.
   HANDLE hFile = (HANDLE)myFile;

   // Test the file has opened successfully.
   ATLASSERT(hFile != INVALID_HANDLE_VALUE);

   // Open the file for file-mapping.
   // Must give a size as the file is zero by default.
   if (myFileMap.MapFile(hFile,
      1024,
      0,
      PAGE_READWRITE,
      FILE_MAP_READ) != S_OK)
   {
      CloseHandle(hFile);
      return 0;
   }

   // Confirm the size of the mapping file.
   ATLASSERT(myFileMap.GetMappingSize() == 1024);

   // Now the file-mapping object is open, a second
   // process could access the filemap object to exchange
   // data.

   return 0;
}
示例#19
0
void LogViewRE::SaveAs()
{
  CString sFilename;
  FileType aType;
  if (!FileDialog::GetSaveAsFilename(GetParent(), sFilename, aType)) {
    return;
  }

  CAtlFile file;
  HRESULT hr = file.Create(sFilename, GENERIC_WRITE, FILE_SHARE_WRITE, CREATE_ALWAYS);
  if (FAILED(hr)) {
    CString s, sErr;
    ::FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, hr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), sErr.GetBuffer(4096), 4096, NULL);
    sErr.ReleaseBuffer();
    s.Format(_T("Can't open file\n%s\n\nfor saving. Windows says:\n\"%s\""), sFilename, sErr);
    MessageBox(s, L"Save logfile", MB_OK|MB_ICONERROR);
    return;
  }
  UINT format = (TXT == aType) ? SF_TEXT : SF_RTF;

  EDITSTREAM eds = {(DWORD_PTR)&file, 0, StreamFileOut};
  StreamOut(format, eds);
}
示例#20
0
文件: Util.cpp 项目: ekicyou/pasta
	// 指定したcodepageのテキストとしてファイルを読み込みます
CString Util::File::ReadAllText(const CString& path, const UINT codePage)
{
	CString rc;
	CAtlFile file;
	if(file.Create(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING) != S_OK){
		rc.Format(_T("ERROR: File Not Found[path=%s]\n"), (LPCTSTR)path);
		return rc;
	}
	ULONGLONG size;
	if(file.GetSize(size) != S_OK){
		rc.Format(_T("ERROR: File GetSize[%s]\n"), (LPCTSTR)path);
		return rc;
	}
	CAtlArray<char> buf;
	buf.SetCount((size_t)size+1);
	if(file.Read(buf.GetData(), (DWORD)size) != S_OK){
		rc.Format(_T("ERROR: File Read[%s]\n"), (LPCTSTR)path);
		return rc;
	}
	buf[(size_t)size] = 0;
	rc = CA2CT(buf.GetData(), codePage);
	return rc;
}
LPVOID ReadFile(LPCTSTR pPath, DWORD *length /* = NULL */, DWORD *lengthPlusSpace /* = NULL */, DWORD spacepadding /* = 0 */, BOOL bEOF /* = FALSE */, BOOL bFailedMsgBox /* = TRUE */)
{
	CAtlFile file;
	if(FAILED(file.Create(pPath, GENERIC_READ, 0, OPEN_EXISTING))) {
    if(bFailedMsgBox)
    {
      /*CString sMsg;
      sMsg.Format(IDS_ERR_FILENOTFOUND, pPath);
      MessageBox(NULL, sMsg, _T("ERROR"), MB_OK);*/
    }
		return NULL;
	}
  UINT64 len64 = 0;
  file.GetSize(len64);
  if(len64 > _UI32_MAX)return NULL;
	DWORD len = (DWORD)len64;
  DWORD lenPlusSpace = len + spacepadding;
  if(lenPlusSpace < len)
  {
    lenPlusSpace = len;
    spacepadding = 0;
  }
	LPVOID p = new char[lenPlusSpace + 1];
	file.Read(p, len);
  LPBYTE sp = ((LPBYTE)p)+lenPlusSpace-1;
  for(;spacepadding;spacepadding--)
  {
    *sp = ' ';
    sp--;
  }
	*((LPBYTE)p+lenPlusSpace) = '\0';
	if(bEOF)*((LPBYTE)p+len) = 0x1a;
	file.Close();
  if(length!=NULL)*length=len;
  if(lengthPlusSpace!=NULL)*lengthPlusSpace = lenPlusSpace;
	return p;
}
示例#22
0
BOOL file_get_contents( LPCTSTR lpszFilename, CStringA &strA )
{
	CAtlFile file;
	if( FAILED( file.Create(lpszFilename, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING) ) )
		return FALSE;
	
	BOOL bRet = FALSE;
	do 
	{
		ULONGLONG filesize = 0;
		if( FAILED( file.GetSize(filesize) ) ) 
			break;

		strA = "";
		if(filesize>0)
		{
			file.Read( strA.GetBuffer((int)filesize), (DWORD)filesize );
			strA.ReleaseBuffer((int)filesize);
		}
		bRet = TRUE;
	} while (FALSE);
	file.Close();
	return bRet;
}
示例#23
0
void ServerAgent::FileSending(std::string filepath)
{
	int msglen=0;
	int requesttype=0;
	string filename;
	GetFileNameFromPath(filepath,filename);


	int times=10;//传输次数
	RequestFileMessage rqmsg;
	rqmsg.Filename=filename;

	CString pathstr(filepath.data());
	CAtlFile file;
	HRESULT r=file.Create(pathstr,GENERIC_READ | GENERIC_WRITE, 0, OPEN_EXISTING);
	if (FAILED(r))
	{
		std::cout<<"文件打开错误"<<std::endl;
	}
	ULONGLONG filesize;

	if(FAILED(file.GetSize(filesize)))
	{
		std::cout<<"获取文件大小错误"<<std::endl;
	}
	std::cout<<"文件"<<filepath<<"大小"<<filesize<<std::endl;

	times=filesize/packagelen;//计算出要发送的次数

	if ((filesize%packagelen)>0)
	{
		times++;
	}
	m_sendtimes=times;
	std::cout<<"文件需要发送次数"<<m_sendtimes<<std::endl;
	rqmsg.TransferTimes=times;


	MessageData rqmsgdata=rqmsg.GetBytes();
	ConnectServer();//连接服务器
	boost::system::error_code sendec,recvec;
	boost::shared_array<char> recbuf(new char[100]);

	std::size_t rec_num=m_sock.receive(boost::asio::buffer(recbuf.get(),100));//先接受4字节的数据
	m_sock.send(boost::asio::buffer(rqmsgdata.buf.get(),rqmsgdata.buflen));

	m_sock.receive(boost::asio::buffer(recbuf.get(),100));

	WrtieFileMessage writefilemsg;
	writefilemsg.packagebytesnum=packagelen;//设定上每包数据的数据量
	
	for (int i=0;i<m_sendtimes;i++)
	{
		writefilemsg.packagenum=i;
		if (i==(m_sendtimes-1))
		{
			if (filesize%packagelen>0)
			{
				writefilemsg.packagebytesnum=filesize%packagelen;
				MessageData data=writefilemsg.GetBytes();
				file.Read(data.buf.get()+MSGHEADLEN+WriteFileMessagelen,writefilemsg.packagebytesnum);
				m_sock.send(boost::asio::buffer(data.buf.get(),data.buflen));
				m_SendedBytes+=writefilemsg.packagebytesnum;
			}
			else
			{
				MessageData data=writefilemsg.GetBytes();
				file.Read(data.buf.get()+MSGHEADLEN+WriteFileMessagelen,packagelen);
				m_sock.send(boost::asio::buffer(data.buf.get(),data.buflen));
				m_SendedBytes+=packagelen;
			}
		}
		else
		{
			MessageData data=writefilemsg.GetBytes();
			file.Read(data.buf.get()+MSGHEADLEN+WriteFileMessagelen,packagelen);
			m_sock.send(boost::asio::buffer(data.buf.get(),data.buflen));
			m_SendedBytes+=packagelen;
		}
		rec_num=m_sock.receive(boost::asio::buffer(recbuf.get(),100));
	}
	m_Sending=false;
}
示例#24
0
void CDownloadTask::RunMergeFile(CDownload* pDownload, LPCTSTR szFilename, BOOL bMergeValidation, const Fragments::List& oMissedGaps, float fProgress)
{
//	HANDLE hSource = CreateFile( szFilename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL );

	QWORD nSourceSize = 0;		// qwSourceLength
	QWORD nSourceOffset = 0;	// qwSourceOffset

	CAtlFile oSource;
	oSource.Create( szFilename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, OPEN_EXISTING );
	VERIFY_FILE_ACCESS( oSource, szFilename )
	if ( ! oSource )
	{
		// Source file open error
		theApp.Message( MSG_ERROR, IDS_DOWNLOAD_FILE_OPEN_ERROR, szFilename );
		return;
	}

	oSource.GetSize( nSourceSize );
	if ( ! nSourceSize )
		return;		// Empty source file

	CSingleLock pLock( &Transfers.m_pSection, TRUE );

	if ( ! Downloads.Check( pDownload ) ||
		  pDownload->IsCompleted() ||
		  pDownload->IsMoving() )
		return;		// Moot download almost completed

	if ( m_bMergeValidation &&
		! pDownload->IsTorrent() &&
		 pDownload->NeedTigerTree() &&
		 pDownload->NeedHashset() )
	{
	//	pLock.Unlock();
	//	MsgBox( IDS_DOWNLOAD_EDIT_COMPLETE_NOHASH, MB_ICONEXCLAMATION );
		DEBUG_ONLY( theApp.Message( MSG_DEBUG, IDS_DOWNLOAD_EDIT_COMPLETE_NOHASH ) );
		return;		// No hashsets
	}

	if ( ! pDownload->PrepareFile() )
		return;		// Destination file open error

	Fragments::List oList( pDownload->GetEmptyFragmentList() );
	if ( ! oMissedGaps.empty() )
	{
		Fragments::List::const_iterator pItr = oMissedGaps.begin();
		const Fragments::List::const_iterator pEnd = oMissedGaps.end();
		for ( ; pItr != pEnd ; ++pItr )
			oList.erase( *pItr );
	}

	if ( ! oList.size() )
		return;		// No available fragments

	// Determine offset if needed
	if ( pDownload->IsMultiFileTorrent() )
	{
		QWORD nOffset = 0;		// qwOffset
		BOOL bFound = FALSE;
		CBTInfo::CBTFile* pFile;
		CString strTargetName;
		const CString strSourceName = PathFindFileName( szFilename );

		if ( GetAsyncKeyState( VK_SHIFT ) & 0x8000 )	// Forced selection dialog
		{
			int nIndex = pDownload->SelectFile( &pLock );
			if ( nIndex == 0 )
			{
				bFound = TRUE;
			}
			else if ( nIndex > 0 )
			{
				CBTInfo::CBTFile* pSelectFile = pDownload->m_pTorrent.m_pFiles.GetAt( pDownload->m_pTorrent.m_pFiles.FindIndex( nIndex ) );
				for ( POSITION pos = pDownload->m_pTorrent.m_pFiles.GetHeadPosition() ; pos ; )
				{
					pFile = pDownload->m_pTorrent.m_pFiles.GetNext( pos );
					if ( pFile->m_sPath == pSelectFile->m_sPath )
					{
						DEBUG_ONLY( theApp.Message( MSG_DEBUG, _T("Merge Selected File: ") + pFile->m_sPath ) );
						nSourceOffset = nOffset;
						bFound = TRUE;	// Avoid checks below
						break;
					}

					nOffset += pFile->m_nSize;
				}
			}
		}

		if ( ! bFound )		// No forced match, try filename
		{
			for ( POSITION pos = pDownload->m_pTorrent.m_pFiles.GetHeadPosition() ; pos ; )
			{
				pFile = pDownload->m_pTorrent.m_pFiles.GetNext( pos );
				strTargetName = PathFindFileName( pFile->m_sPath );

				if ( strTargetName.CompareNoCase( strSourceName ) == 0 )
				{
					DEBUG_ONLY( theApp.Message( MSG_DEBUG, _T("Merge Filename: ") + pFile->m_sPath ) );
					nSourceOffset = nOffset;
					bFound = TRUE;	// Avoid fallback check below
					break;
				}

				nOffset += pFile->m_nSize;
			}
		}

		if ( ! bFound )		// No filename match, try exact size
		{
			nOffset = 0;
		//	const CString strExt = PathFindExtension( strSourceName );
			for ( POSITION pos = pDownload->m_pTorrent.m_pFiles.GetHeadPosition() ; pos ; )
			{
				pFile = pDownload->m_pTorrent.m_pFiles.GetNext( pos );

				if ( pFile->m_nSize == nSourceSize )	// && strExt == PathFindExtension( pFile->m_sPath )
				{
					DEBUG_ONLY( theApp.Message( MSG_DEBUG, _T("Merge Filesize Fallback") ) );
					nSourceOffset = nOffset;
				//	bFound = TRUE;
					break;
				}

				nOffset += pFile->m_nSize;
			}
		}
	}

	pLock.Unlock();

	const float fIncrement = fProgress / oList.size();

	const DWORD nBufferLength = 256 * 1024;		// Was 65536?

	// Read missing file fragments from selected file
	auto_array< BYTE > Buf( new BYTE [nBufferLength] );
	Fragments::List::const_iterator pItr = oList.begin();
	const Fragments::List::const_iterator pEnd = oList.end();
	for ( ; ! m_pEvent && pItr != pEnd ; ++pItr )
	{
		m_fProgress += fIncrement;		// Update tooltip

		QWORD qwLength = pItr->end() - pItr->begin();
		QWORD qwOffset = pItr->begin();

		// Check for overlapped fragments
		if ( qwOffset + qwLength <= nSourceOffset ||
			 nSourceOffset + nSourceSize <= qwOffset )
			 continue;	 // No overlaps

		// Calculate overlapped range end offset
		QWORD qwEnd = min( qwOffset + qwLength, nSourceOffset + nSourceSize );
		// Calculate overlapped range start offset
		qwOffset = max( qwOffset, nSourceOffset );
		// Calculate overlapped range length
		qwLength = qwEnd - qwOffset;
		// Calculate file offset if any
		QWORD qwFileOffset = ( qwOffset > nSourceOffset ) ? qwOffset - nSourceOffset : 0;
		if ( FAILED( oSource.Seek( qwFileOffset, FILE_BEGIN ) ) )
			continue;

		DWORD dwToRead;
		while ( ( dwToRead = (DWORD)min( qwLength, (QWORD)nBufferLength ) ) != 0 && ! m_pEvent )
		{
			DWORD dwReaded = 0;
			if ( SUCCEEDED( oSource.Read( Buf.get(), dwToRead, dwReaded ) ) && dwReaded )
			{
				pLock.Lock();

				if ( ! Downloads.Check( pDownload ) || pDownload->IsCompleted() || pDownload->IsMoving() )
					return;

				pDownload->SubmitData( qwOffset, Buf.get(), (QWORD)dwReaded );
				pLock.Unlock();
				qwOffset += (QWORD)dwReaded;
				qwLength -= (QWORD)dwReaded;
			}
			else
			{
				// File error or end of file. Non-Fatal
				break;
			}
		}

		pLock.Lock();

		if ( ! Downloads.Check( pDownload ) || pDownload->IsCompleted() || pDownload->IsMoving() )
			return;

		if ( bMergeValidation )
			pDownload->RunValidation();

		pDownload->SetModified();

		pLock.Unlock();
	}

//	m_bSuccess = true;
}
示例#25
0
//////////////////////////////////////////////////////////////////////////
// 删除单个文件
BOOL slimhelper::DeleteFile(const CString& strFilePath,
                            ULONGLONG qwFileSize,
                            DWORD dwFileAttributes,
                            ISystemSlimCallBack* piCallback)
{
    BOOL retval = FALSE;
    BOOL bRetCode;
    CString strOldSecurityDescriptor;
    HRESULT hr;
    ULARGE_INTEGER tempSize;

    if (!piCallback)
        goto clean0;

    if (!piCallback->OnBeginProcessItem(strFilePath))
        goto clean0;

    if (INVALID_FILE_ATTRIBUTES == dwFileAttributes)
    {
        dwFileAttributes = ::GetFileAttributes(strFilePath);
        if (INVALID_FILE_ATTRIBUTES == dwFileAttributes)
            goto clean0;
    }

    if (dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED
        || dwFileAttributes & FILE_ATTRIBUTE_SPARSE_FILE)
    {
        tempSize.LowPart = GetCompressedFileSize(strFilePath, &tempSize.HighPart);
        qwFileSize = tempSize.QuadPart;
    }
    else
    {
        if (0 == qwFileSize)
        {
            CAtlFile file;
            hr = file.Create(strFilePath, 
                FILE_GENERIC_READ, 
                FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
                OPEN_EXISTING);
            if (FAILED(hr))
                goto clean0;

            tempSize.LowPart = GetFileSize((HANDLE)file, &tempSize.HighPart);
            qwFileSize = tempSize.QuadPart;
        }
    }

    qwFileSize = FileSizeConver::Instance().FileSizeOnDisk(qwFileSize);

    if (!GrantFileAccess(strFilePath, strOldSecurityDescriptor))
        goto clean0;

    bRetCode = ::DeleteFile(strFilePath);
    if (!bRetCode)
    {
        if (!::MoveFileEx(strFilePath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT))
        {
            goto clean0;
        }
    }

    piCallback->OnEndProcessItem(strFilePath, qwFileSize);

    retval = TRUE;

clean0:
    return retval;
}
示例#26
0
BOOL CLocalFileDownload::Fetch( INT nCorrurent/*=0*/ )
{
	m_bStopped = FALSE;
	
	try
	{
		CFileInStream fin(m_strUrl);
		if(!fin.Create())
		{
			m_errCode = DLLER_SERVER_FILENOTFOUND;
			return FALSE;
		}

		CString strTmpFile;
		strTmpFile.Format(_T("%s%s"), m_strFilePath, _T(".tc"));
		CAtlFile file;	
		if( FAILED( file.Create(strTmpFile, GENERIC_WRITE, FILE_SHARE_WRITE, CREATE_ALWAYS) ) )
		{
			m_errCode = DLERR_CREATEFILE;
			return FALSE;
		}
		
		m_errCode = DLERR_SUCCESS;
		m_FileInfo.Reset(fin.GetFileSize(), 0, TRUE);
		m_DownStat.OnDownBegin();
		
		int64 lastDownloaded = 0, downloadedPercent = m_FileInfo.fileSize/100;

		const int nBufferSize = 1024;
		BYTE *pBuffer = new BYTE[nBufferSize];
		while(!m_bStopped)
		{
			DWORD dwReaded = 0;
			fin.Read(pBuffer, nBufferSize, &dwReaded);
			if(dwReaded==0)
				break;
			
			DWORD dwWrited = 0;
			if( FAILED(file.Write(pBuffer, dwReaded, &dwWrited)) || dwWrited!=dwReaded)
			{
				m_errCode = DLERR_WRITEFILE;
				break;
			}

			m_FileInfo.fileDownloaded += dwReaded;			
			if((m_FileInfo.fileDownloaded-lastDownloaded) > downloadedPercent)
			{
				m_DownStat.OnDownData(GetTickCount(), (m_FileInfo.fileDownloaded-lastDownloaded));
				lastDownloaded = m_FileInfo.fileDownloaded;
				_Notify(ProcessState_ReceiveData);
			}
		}
		fin.CloseFile();
		file.Close();
		SAFE_DELETE_ARRAY(pBuffer);
		m_DownStat.OnDownEnd();
		
		if(m_FileInfo.fileDownloaded==m_FileInfo.fileSize)
		{
			MoveFileEx(strTmpFile, m_strFilePath, MOVEFILE_REPLACE_EXISTING);
			m_errCode = DLERR_SUCCESS;
		}
		else
		{
			DeleteFile(strTmpFile);
			m_errCode = DLLER_NETWORK;
		}
	}
	catch (...)
	{
		m_errCode = DLERR_WRITEFILE;
	}
	return DLERR_SUCCESS==m_errCode;
}
示例#27
0
BOOL slimhelper::ScanFile(const CString& strFilePath, 
                          ULONGLONG qwFileSize,
                          DWORD dwFileAttributes,
                          ISystemSlimCallBack* piCallback)
{
    BOOL retval = FALSE;
    HANDLE hFind = NULL;
    HRESULT hr;
    ULARGE_INTEGER tempSize;
    ULONGLONG qwSaveSize = 0;
    BOOL bCompressed = FALSE;

    if (!piCallback)
        goto clean0;

    if (INVALID_FILE_ATTRIBUTES == dwFileAttributes)
    {
        dwFileAttributes = GetFileAttributes(strFilePath);
        if (INVALID_FILE_ATTRIBUTES == dwFileAttributes)
            goto clean0;
    }

    if (dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED
        || dwFileAttributes & FILE_ATTRIBUTE_SPARSE_FILE)
    {
        bCompressed = TRUE;
    }

    if (bCompressed)
    {
        tempSize.LowPart = GetCompressedFileSize(strFilePath, &tempSize.HighPart);
        qwFileSize = tempSize.QuadPart;
    }
    else
    {
        if (0 == qwFileSize)
        {
            CAtlFile file;

            hr = file.Create(
                strFilePath, 
                FILE_GENERIC_READ, 
                FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
                OPEN_EXISTING
                );
            if (FAILED(hr))
                goto clean0;

            tempSize.LowPart = GetFileSize((HANDLE)file, &tempSize.HighPart);
            qwFileSize = tempSize.QuadPart;
        }
    }

    qwFileSize = FileSizeConver::Instance().FileSizeOnDisk(qwFileSize);

    piCallback->OnScanItem(strFilePath, qwFileSize, bCompressed);

    retval = TRUE;

clean0:
    if (hFind)
    {
        FindClose(hFind);
        hFind = NULL;
    }

    return retval;
}
示例#28
0
HRESULT STDMETHODCALLTYPE CSoftMgrUpdateHelper::Combine( LPCWSTR lpwszDifflib )
{
#if OPEN_VCDIFF
	// 加载Delta
	BkDatLibContent delta;
	CDataFileLoader	loader;
	if(!loader.GetLibDatContent(lpwszDifflib, delta)) return ::HRESULT_FROM_WIN32(ERROR_BAD_FORMAT);

	// 目标文件路径
	wchar_t szDstPath[MAX_PATH] = {0};
	{
		::GetModuleFileNameW(NULL, szDstPath, MAX_PATH);

		::PathRemoveFileSpecW(szDstPath);
		wcscat_s(szDstPath, MAX_PATH, L"\\KSoft\\Data\\");
		wcscat_s(szDstPath, MAX_PATH, ::PathFindFileNameW(lpwszDifflib));

		//
		//@Issue
		// 根据名称来判断库类型
		//
		//@Note
		// 命名规则为:libname_old_new.dat
		//
		LPWSTR pSep = wcschr(::PathFindFileNameW(szDstPath), L'_');
		if(pSep == NULL) return ::HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER);

		pSep[0] = L'\0';
		wcscat_s(szDstPath, MAX_PATH,  L".dat");
	}

	// 加载字典文件
	CAtlFile dictFile;
	HRESULT hr = dictFile.Create(szDstPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING);
	if(!SUCCEEDED(hr)) return hr;

	ULONGLONG dictSize;
	hr = dictFile.GetSize(dictSize);
	if(!SUCCEEDED(hr)) return hr;

	auto_buffer<char> dict(static_cast<size_t>(dictSize));
	if(dict.empty()) return ::HRESULT_FROM_WIN32(ERROR_OUTOFMEMORY);

	DWORD bytesRead;
	hr = dictFile.Read(dict.data(), static_cast<DWORD>(dict.size()), bytesRead);
	if(!SUCCEEDED(hr)) return hr;

	dictFile.Close();

	// 创建目标临时文件
	CAtlTemporaryFile tempTarget;
	hr = tempTarget.Create();
	if(!SUCCEEDED(hr)) return hr;

	//
	// 开始合并
	//
	//@Note
	// Dict(Source) + Delta => Target
	//
	Output2File output2File(tempTarget);
	{
		VCDiffStreamingDecoder decoder;
		decoder.StartDecoding(&dict[0], dict.size());

		size_t beg = 0;
		size_t end = static_cast<size_t>(delta.nLen);
		LPCSTR pDelta = reinterpret_cast<LPCSTR>(delta.pBuffer);

		while(beg < end)
		{
			static const size_t MAX_THUNK_SIZE = 16*1024;

			size_t size = end - beg;
			if(size > MAX_THUNK_SIZE) size = MAX_THUNK_SIZE;

			if(!decoder.DecodeChunkToInterface(pDelta + beg, size, &output2File))
				return ::HRESULT_FROM_WIN32(ERROR_BAD_FORMAT);

			beg += size;
		}

		if(!decoder.FinishDecoding())
			return ::HRESULT_FROM_WIN32(ERROR_BAD_FORMAT);
	}

	// 根据写入文件大小与期望大小来判断是否合并成功
	ULONGLONG dstSize;
	hr = tempTarget.GetPosition(dstSize);
	if(!SUCCEEDED(hr) || dstSize != output2File.GetTotalBytes()) return ::HRESULT_FROM_WIN32(ERROR_WRITE_FAULT);

	// 移动到目标路径
	return tempTarget.Close(szDstPath);
#else
	return S_OK;
#endif
}
示例#29
0
BOOL slimhelper::RecyclePath(const CString& strFilePath, BOOL bKeepRootDir)
{
    BOOL retval = FALSE;
    CString strOldSecurityDescriptor;
    HRESULT hr;
    int nRetCode;
    ULARGE_INTEGER tempSize;
    DWORD dwFileAttributes;
    BOOL bIsDir = FALSE;
    SHFILEOPSTRUCTW fileopt = { 0 };
    ULONGLONG qwFileSize = 0;
    TCHAR* szDelPath = new TCHAR[MAX_PATH * 2];
    CString strFlagFile;

    RtlZeroMemory(szDelPath, sizeof(TCHAR) * MAX_PATH * 2);
    StringCchCopy(szDelPath, MAX_PATH * 2, strFilePath);

    fileopt.pFrom = szDelPath;
    fileopt.wFunc = FO_DELETE;
    fileopt.fFlags = FOF_SILENT|FOF_NOCONFIRMATION|FOF_NOERRORUI|FOF_ALLOWUNDO;

    dwFileAttributes = ::GetFileAttributes(strFilePath);
    if (INVALID_FILE_ATTRIBUTES == dwFileAttributes)
        goto clean0;

    if (dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        bIsDir = TRUE;

    GrantFileAccess(strFilePath, strOldSecurityDescriptor, bIsDir);
    //if (!GrantFileAccess(strFilePath, strOldSecurityDescriptor))
    //    goto clean0;

    strFlagFile = strFilePath + _T("\\"); 
    strFlagFile += g_kSlimFlag;

    if (bIsDir)
    {
        ::DeleteFile(strFlagFile);
        nRetCode = SHFileOperationW(&fileopt);
        if (32 == nRetCode)
            goto clean0;

        if (0x78 == nRetCode || 5 == nRetCode)
        {
            GrantDirAccess(strFilePath);
            ::DeleteFile(strFlagFile);
            nRetCode = SHFileOperationW(&fileopt);;
        }

        if (!nRetCode)
        {
            if (bKeepRootDir)
            {
                ::CreateDirectory(strFilePath, NULL);
                // 创建瘦身后的标记文件
//                 CAtlFile file;
//                 file.Create(strFlagFile, 
//                     FILE_GENERIC_WRITE, 
//                     FILE_SHARE_READ|FILE_SHARE_WRITE,
//                     CREATE_ALWAYS);
            }
            retval = TRUE;
        }
        goto clean0;
    }

    if (dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED
        || dwFileAttributes & FILE_ATTRIBUTE_SPARSE_FILE)
    {
        tempSize.LowPart = GetCompressedFileSize(strFilePath, &tempSize.HighPart);
        qwFileSize = tempSize.QuadPart;
    }
    else
    {
        CAtlFile file;
        hr = file.Create(strFilePath, 
                         FILE_GENERIC_READ, 
                         FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
                         OPEN_EXISTING);
        if (FAILED(hr))
            goto clean0;

        tempSize.LowPart = GetFileSize((HANDLE)file, &tempSize.HighPart);
        qwFileSize = tempSize.QuadPart;
    }

    qwFileSize = FileSizeConver::Instance().FileSizeOnDisk(qwFileSize);

    nRetCode = SHFileOperationW(&fileopt);
    if (nRetCode)
        goto clean0;

    retval = TRUE;

clean0:
    if (szDelPath)
    {
        delete[] szDelPath;
        szDelPath = NULL;
    }

    return retval;
}
示例#30
0
HRESULT FAsyncDownload::FHttpDownloadTP::ProcessDownload(FAsyncDownData *pData)
{
    HRESULT hr = E_FAIL; 


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

    CUrl url;
    url.CrackUrl(ReqUrl);

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

     
    if (NULL == hIn)
        return E_HTTP_NET_ERROR; 

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

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

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


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

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

	size_type FileSize = 0;
	
	

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

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


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

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

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

    FHttpConnection FConn = hReq;

    DWORD dwStatusCode = FConn.GetStatusCode(); 

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

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

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

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

    CAtlFile OutFile; 

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

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

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

    size_type llTotalRead = 0; 
    size_type llSizeMax = 0; 

	size_type ContentLen = FConn.GetContentLength(); 

	pData->m_pUrlInfo->m_ContentLength = ContentLen; 

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

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

    if (llSizeMax == 0)
		llSizeMax = ContentLen;


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

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

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

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

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

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


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

	OutFile.Close();
    return hr; 
}