예제 #1
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;
}
예제 #2
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;
}
예제 #3
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;
}
예제 #4
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;
}
예제 #5
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;
}
예제 #6
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;
}
예제 #8
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;
}
예제 #9
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;
}
예제 #10
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;
}
예제 #11
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
}
예제 #12
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;
    }
}
예제 #13
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;
}