Ejemplo n.º 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;
}
Ejemplo n.º 2
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;
}
Ejemplo n.º 3
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;
}
Ejemplo n.º 4
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;
}
Ejemplo n.º 5
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;
}
Ejemplo n.º 6
0
	// 指定した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;
}
Ejemplo n.º 7
0
std::vector<unsigned char> DumpUploaderWebServiceEx::ReadFile(const std::wstring& path)
{
    std::vector<unsigned char> data;

    CAtlFile file;
    for (int i = 0; ; ++i)
    {
        file.Attach(CreateFile(path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
        if (file != INVALID_HANDLE_VALUE)
            break;

        DWORD err = GetLastError();
        // File indexing services like to open just closed files (our doctor_dump_mini.zip file), so lets make few tries.
        if (err == ERROR_SHARING_VIOLATION && i < 10)
        {
            Sleep(1000);
            continue;
        }
        CStringA text;
        text.Format("failed (err %d) to open file %ls", err, path.c_str());
        throw std::runtime_error(text);
    }


    ULONGLONG fileSize;
    if (FAILED(file.GetSize(fileSize)))
        throw std::runtime_error(std::string("failed to get file size ") + (const char*)CW2A(path.c_str()));

    if (fileSize != 0)
    {
        data.resize((size_t)fileSize);
        if (FAILED(file.Read(&data[0], static_cast<DWORD>(fileSize))))
            throw std::runtime_error(std::string("failed to read file ") + (const char*)CW2A(path.c_str()));
    }

    return data;
}
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;
}
Ejemplo n.º 9
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;
}
Ejemplo n.º 10
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;
}
Ejemplo n.º 11
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;
}
Ejemplo n.º 12
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
}
Ejemplo n.º 13
0
bool CTrueType::GetProperties(LPCTSTR pszFilePath, TTF_PROPERTIES* pProperties)
{
	CAtlFile FontFile;
	HRESULT hr = FontFile.Create(pszFilePath, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING);
	if (FAILED(hr))
		return false;

	TTF_OFFSET_TABLE ttOffsetTable;
	FontFile.Read(&ttOffsetTable, sizeof(TTF_OFFSET_TABLE));
	ttOffsetTable.uNumOfTables = SWAPWORD(ttOffsetTable.uNumOfTables);
	ttOffsetTable.uMajorVersion = SWAPWORD(ttOffsetTable.uMajorVersion);
	ttOffsetTable.uMinorVersion = SWAPWORD(ttOffsetTable.uMinorVersion);

	// See if this is a true type font and the version is 1.0
	if (ttOffsetTable.uMajorVersion != 1 || ttOffsetTable.uMinorVersion != 0)
		return false;
	
	TTF_TABLE_DIRECTORY tblDir;
	TTF_TABLE_DIRECTORY tblName;
	TTF_TABLE_DIRECTORY tblOS2;
	bool bFoundNameTable = false;
	bool bFoundOS2Table = false;
	for (int i=0; i< ttOffsetTable.uNumOfTables; i++)
	{
		FontFile.Read(&tblDir, sizeof(TTF_TABLE_DIRECTORY));
		CString strName = CString(tblDir.szTag, 4);
		if (strName.IsEmpty())
			break;

		if (!strName.CompareNoCase("name"))
		{
			bFoundNameTable = true;
			tblName = tblDir;
			tblName.uLength = SWAPLONG(tblName.uLength);
			tblName.uOffset = SWAPLONG(tblName.uOffset);
		}
		else
		if (!strName.CompareNoCase("OS/2"))
		{
			bFoundOS2Table = true;
			tblOS2 = tblDir;
			tblOS2.uLength = SWAPLONG(tblOS2.uLength);
			tblOS2.uOffset = SWAPLONG(tblOS2.uOffset);
		}

		if (bFoundNameTable && bFoundOS2Table)
			break;
	}
	
	if (bFoundNameTable)
	{
		FontFile.Seek(tblName.uOffset, FILE_BEGIN);

		TTF_NAME_TABLE_HEADER ttNTHeader;
		FontFile.Read(&ttNTHeader, sizeof(TTF_NAME_TABLE_HEADER));
		ttNTHeader.uFSelector      = SWAPWORD(ttNTHeader.uFSelector);
		ttNTHeader.uNRCount        = SWAPWORD(ttNTHeader.uNRCount);
		ttNTHeader.uStorageOffset  = SWAPWORD(ttNTHeader.uStorageOffset);

		for (int i=0; i<ttNTHeader.uNRCount; i++)
		{
			TTF_NAME_RECORD ttRecord;
			FontFile.Read(&ttRecord, sizeof(TTF_NAME_RECORD));
			ttRecord.uPlatformID   = SWAPWORD(ttRecord.uPlatformID);
			ttRecord.uEncodingID   = SWAPWORD(ttRecord.uEncodingID);
			ttRecord.uLanguageID   = SWAPWORD(ttRecord.uLanguageID);
			ttRecord.uNameID       = SWAPWORD(ttRecord.uNameID);
			ttRecord.uStringLength = SWAPWORD(ttRecord.uStringLength);
			ttRecord.uStringOffset = SWAPWORD(ttRecord.uStringOffset);

			if (ttRecord.uPlatformID != 3) // Microsoft
				continue;

			ULONGLONG nPos = 0;
			FontFile.GetPosition(nPos);
			FontFile.Seek(tblName.uOffset + ttRecord.uStringOffset + ttNTHeader.uStorageOffset, FILE_BEGIN);

			int iUnicodeChars = (ttRecord.uStringLength + 1) / 2;
			WCHAR* pUnicodeBuffer = new WCHAR[iUnicodeChars];
			FontFile.Read(pUnicodeBuffer, ttRecord.uStringLength);
			for (int i = 0; i < iUnicodeChars; i++)
				pUnicodeBuffer[i] = SWAPWORD(pUnicodeBuffer[i]);

			CString strName = CString(pUnicodeBuffer, iUnicodeChars);
			delete [] pUnicodeBuffer;
			FontFile.Seek(nPos, FILE_BEGIN);
			
			if (strName.IsEmpty())
				continue;

			switch (ttRecord.uNameID)
			{
				case 1: // Font family
					pProperties->strFamily.IsEmpty() ? pProperties->strFamily = strName : void();
					break;
				case 0: // Copyright notice
					pProperties->strCopyright.IsEmpty() ? pProperties->strCopyright = strName : void();
					break;
				case 7: // Trademark notice
					pProperties->strTrademark.IsEmpty() ? pProperties->strTrademark = strName : void();
					break;
				case 4: // Full Name of the Font
					pProperties->strName.IsEmpty() ? pProperties->strName = strName : void();
					break;
				case 2: // Font sub family
				case 3: // Unique Family Identifier
				case 5: // Version of the name table
				case 6: // PostScript name of the font
				default:
				{
					break;
				}
			}
		}			
	}

	if (bFoundOS2Table)
	{
		FontFile.Seek(tblOS2.uOffset, FILE_BEGIN);

		TTF_OS2_TABLE ttNTHeader;
		FontFile.Read(&ttNTHeader, sizeof(TTF_OS2_TABLE));
		ttNTHeader.uVersion          = SWAPWORD(ttNTHeader.uVersion);
		ttNTHeader.uAverageCharWidth = SWAPWORD(ttNTHeader.uAverageCharWidth);
		ttNTHeader.uWeightClass      = SWAPWORD(ttNTHeader.uWeightClass);
		ttNTHeader.uWidthClass       = SWAPWORD(ttNTHeader.uWidthClass);
		ttNTHeader.uFsType           = SWAPWORD(ttNTHeader.uFsType);
	
		if (ttNTHeader.uFsType & 0x0001)	// 1: reserved - must be zero; if not, turn it off
			ttNTHeader.uFsType &= ~0x0001;

		if (ttNTHeader.uFsType == 0x0000)	// 0: embedding and permanent installation allowed
		{
			pProperties->strEmbed = "Installable";
			pProperties->enumEmbed = TTF_Embed_Installable;
		}
		else
		if (ttNTHeader.uFsType & 0x0008)	// 8: editable embedding allowed
		{
			pProperties->strEmbed = "Editable";
			pProperties->enumEmbed = TTF_Embed_Editable;
		}
		else
		if (ttNTHeader.uFsType & 0x0004)	// 4: preview and print embedding allowed
		{
			pProperties->strEmbed = "Printable";
			pProperties->enumEmbed = TTF_Embed_Printable;
		}
		else
		if (ttNTHeader.uFsType & 0x0002)
		{
			pProperties->strEmbed = "None"; // 2: no embedding allowed
			pProperties->enumEmbed = TTF_Embed_None;
		}
		else
		{
			pProperties->strEmbed.Format("%d", ttNTHeader.uFsType); // unknown
			pProperties->enumEmbed = TTF_Embed_Unknown;
		}
	}

	FontFile.Close();

	return !pProperties->strName.IsEmpty();
}
Ejemplo n.º 14
0
HRESULT CZlib::EncodeFile( LPCWSTR lpwszSrcFile, LPCWSTR lpwszDstFile, int level )
{
    if ( zlib_compress )
    {
        CAtlFile hInFile;
        HRESULT hr = hInFile.Create(
            lpwszSrcFile,
            GENERIC_READ,
            FILE_SHARE_READ | FILE_SHARE_DELETE,
            OPEN_EXISTING);
        if (FAILED(hr))
            return hr;

        CAtlFile hOutFile;
        hr = hOutFile.Create(
            lpwszDstFile,
            GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_DELETE,
            CREATE_ALWAYS);
        if (FAILED(hr))
            return hr;

        ULONGLONG uInFileSize = 0;
        hr = hInFile.GetSize(uInFileSize);
        if (FAILED(hr))
            return hr;

        // 0长度文件不需要压缩
        if (0 == uInFileSize)
            return S_OK;

        // 太大的文件不压缩
        if (uInFileSize >  ZLIB_SINGLE_FILE_MAX_SIZE ) //假定压缩比为4:1
            return E_FAIL;

        // 读取输入
        CAtlArray<BYTE> bufRead;
        bufRead.SetCount((size_t)uInFileSize);
        if (uInFileSize != bufRead.GetCount())
            return E_OUTOFMEMORY;

        hr = hInFile.Read(bufRead.GetData(), (DWORD)bufRead.GetCount());
        if (FAILED(hr))
            return hr;

        // 准备压缩
        ULONGLONG uOutFileSize = max(uInFileSize, ZLIB_DECOMPRESS_INIT_BUFF_SIZE);
        CAtlArray<BYTE> bufWrite;
        try
        {
            while (uOutFileSize <= ZLIB_SINGLE_FILE_MAX_SIZE )
            {
                bufWrite.SetCount(0);
                bufWrite.SetCount((DWORD)uOutFileSize);
                if (uOutFileSize != bufWrite.GetCount())
                    return E_OUTOFMEMORY;

                DWORD dwcompressSize = DWORD(uOutFileSize);
                int nRet = zlib_compress2(
                    bufWrite.GetData(),
                    &dwcompressSize,
                    bufRead.GetData(),
                    (int)bufRead.GetCount(),
                    level
                    );
                if (nRet == Z_OK && dwcompressSize <= uOutFileSize)
                {
                    bufWrite.SetCount(dwcompressSize);
                    break;
                }

                if (nRet != Z_BUF_ERROR)
                    return E_FAIL;

                uOutFileSize *= 2;
            }	
        }
        catch (...)
        {
            return E_FAIL;
        }

        hr = hOutFile.Write(bufWrite.GetData(), (DWORD)bufWrite.GetCount());
        if (FAILED(hr))
            return hr;

        return S_OK;
    }
    else
    {
        return E_NOINTERFACE;
    }
}
Ejemplo n.º 15
0
//----------------------------------------------------------------------------
//  Init
HRESULT CAnchoBackgroundAPI::Init(LPCTSTR lpszThisPath, LPCTSTR lpszRootURL, BSTR bsID, LPCTSTR lpszGUID, LPCTSTR lpszPath)
{
  // set our ID
  m_bsID = bsID;
  m_GUID = lpszGUID;

  m_sRootURL = lpszRootURL;

  CString sPath(lpszPath);

  // create logger window
  IF_FAILED_RET(CLogWindow::CreateLogWindow(&m_LogWindow.p));

  // create a magpie instance
#ifdef MAGPIE_REGISTERED
  IF_FAILED_RET(m_Magpie.CoCreateInstance(CLSID_MagpieApplication));
#else
  // Load magpie from the same path where this exe file is.
  CString s(lpszThisPath);
  s += _T("Magpie.dll");
  HMODULE hModMagpie = ::LoadLibrary(s);
  if (!hModMagpie)
  {
    return E_FAIL;
  }
  fnCreateMagpieInstance CreateMagpieInstance = (fnCreateMagpieInstance)::GetProcAddress(hModMagpie, "CreateMagpieInstance");
  if (!CreateMagpieInstance)
  {
    return E_FAIL;
  }
  IF_FAILED_RET(CreateMagpieInstance(&m_Magpie));
#endif
  // add a loader for scripts in the extension filesystem
  IF_FAILED_RET(m_Magpie->AddFilesystemScriptLoader((LPWSTR)(LPCWSTR)sPath));

  // add a loder for scripts in this exe file
  IF_FAILED_RET(m_Magpie->AddResourceScriptLoader((ULONG)_AtlModule.GetResourceInstance()));

  // advise logger
  IF_FAILED_RET(AtlAdvise(m_Magpie, (IUnknown*)(CAnchoAddonBackgroundLogger*)(this), DIID__IMagpieLoggerEvents, &m_dwMagpieSinkCookie));

  // load manifest
  CString sManifestFilename;
  sManifestFilename.Format(_T("%smanifest.json"), sPath);
  CAtlFile f;
  IF_FAILED_RET(f.Create(sManifestFilename, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING));
  ULONGLONG nLen = 0;
  IF_FAILED_RET(f.GetSize(nLen));
  // limit to 4gb
  if (nLen > 0x00000000ffffffff)
  {
    return E_OUTOFMEMORY;
  }
  DWORD dwLen = (DWORD)nLen;
  CStringA sManifest("exports.manifest = ");
  DWORD strLen = (DWORD)sManifest.GetLength();
  IF_FAILED_RET(f.Read(sManifest.GetBuffer(dwLen + strLen) + strLen, dwLen));
  sManifest.ReleaseBuffer(dwLen + strLen);
  sManifest += _T(';');
  IF_FAILED_RET(m_Magpie->RunScript(L"manifest", (LPWSTR)(LPCWSTR)CA2W(sManifest)));

  // set ourselfs in magpie as a global accessible object
  IF_FAILED_RET(m_Magpie->AddExtension((LPWSTR)s_AnchoGlobalAPIObjectName, (IAnchoBackgroundAPI*)this));

  // initialize Ancho API
  // api.js will do now additional initialization, like looking at the manifest
  // and creating a background page.
  IF_FAILED_RET(m_Magpie->Run((LPWSTR)s_AnchoMainAPIModuleID));

  return S_OK;
}