//
// Locates the requested resource and loads the file into memory.  A pointer to the
// file in memory is returned.  The calling function is responsible for deleting the
// memory.
//
char * DLLResourceManager::UnZipResourceMemberIntoMemory(std::wstring sZippedFileToRetrieve)
{
	ZIPENTRY ze;
	int i;
	char *ibuf = 0;

	try
	{
		const wchar_t* szFileName = sZippedFileToRetrieve.c_str();
		FindZipItem(hz,szFileName,true,&i,&ze);    

		// - unzip to a membuffer 
		ibuf = new char[ze.unc_size + 2];
		UnzipItem(hz,i, ibuf, ze.unc_size);

		// cut off the buffer at the ze.unc_size
		ibuf[ze.unc_size] = EOF;   // This was '\0', then '\n' (that didn't work well for the schema id list
		ibuf[ze.unc_size + 1] = EOF;
	}
	catch (...)
	{
		SgGenerateException("test", "UnZipResourceMemberIntoMemory");
	}

	return ibuf;
}
Esempio n. 2
0
void CPropertiesFiles::OnBnClickedPropPreview()
{
	// TODO: 在此加入控制項告知處理常式程式碼
	CListBox* listBox=(CListBox*)this->GetDlgItem(IDC_PROP_FILELIST);
	int curSel=listBox->GetCurSel();

	if (curSel>=0) {
		LPTSTR pszFile=(LPTSTR)malloc(listBox->GetTextLen(curSel)+1);
		HZIP hZip;
		ZIPENTRY ze;
		CARMDlg* dlg=(CARMDlg*)this->GetParentOwner()->GetParent();
		arfile* arFile=(arfile*)dlg->m_lstFiles.GetItemDataPtr(dlg->m_lstFiles.GetCurSel());

		listBox->GetText(curSel,pszFile);
		hZip=OpenZip(arFile->fileName,0,ZIP_FILENAME);
		if (hZip) {
			int nIndex;
			if (FindZipItem(hZip,pszFile,TRUE,&nIndex,&ze)!=ZR_ARGS) {
				LPBYTE pszContent=(LPBYTE)malloc(ze.unc_size);
				UnzipItem(hZip,nIndex,pszContent,ze.unc_size,ZIP_MEMORY);
				bitmapInfo=&ze;

				DialogBoxParam(theApp.m_hInstance,MAKEINTRESOURCE(IDD_PREVIEW),this->GetSafeHwnd(),(DLGPROC)CPropertiesFiles::previewWndProc,(LPARAM)pszContent);
				free(pszContent);
			}

			CloseZip(hZip);
		}

		free(pszFile);
	}
}
Esempio n. 3
0
bool CZipObj::UnZipFile(CString strZipPath, CString strUnzipPath)
{
	USES_CONVERSION;
	int nPos = strZipPath.ReverseFind('.');
	CString strPath = strZipPath.Left(nPos);		//.zip		strZipPath.GetLength() - 4
	if (strUnzipPath != "")
		strPath = strUnzipPath;
	std::string strUtf8Path = CMyCodeConvert::Gb2312ToUtf8(T2A(strPath));

	try
	{
		Poco::File p(strUtf8Path);	//T2A(strPath)
		if (p.exists())
			p.remove(true);
	}
	catch (Poco::Exception)
	{
	}
	
	HZIP hz = OpenZip(strZipPath, _strPwd.c_str());
	ZIPENTRY ze;
	GetZipItem(hz, -1, &ze);
	int numitems = ze.index;
	SetUnzipBaseDir(hz, strPath);
	for (int i = 0; i < numitems; i++)
	{
		GetZipItem(hz, i, &ze);
		UnzipItem(hz, i, ze.name);
	}
	CloseZip(hz);

	return true;
}
Esempio n. 4
0
void UnzipWithProgress(const TCHAR *zipfn, HWND hprog)
{ HZIP hz = OpenZip(zipfn,0);
  ZIPENTRY ze; GetZipItem(hz,-1,&ze); int numentries=ze.index;
  // first we retrieve the total size of all zip items
  DWORD tot=0; for (int i=0; i<numentries; i++) {GetZipItem(hz,i,&ze); tot+=ze.unc_size;}
  //
  DWORD countall=0; // this is our progress so far
  for (int i=0; i<numentries && !abort_p; i++)
  { GetZipItem(hz,i,&ze);
    // We'll unzip each file bit by bit, to a file on disk
    char fn[1024]; wsprintf(fn,"\\z\\%s",ze.name);
    HANDLE hf = CreateFile(fn,GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
    char buf[16384]; // Each chunk will be 16k big. After each chunk, we show progress
    DWORD countfile=0;
    for (ZRESULT zr=ZR_MORE; zr==ZR_MORE && !abort_p; ) // nb. the global "abort_p" flag is set by the user clicking the Cancel button.
    { zr=UnzipItem(hz,i,buf,16384);
      unsigned long bufsize=16384; if (zr==ZR_OK) bufsize=ze.unc_size-countfile; // bufsize is how much we got this time
      DWORD writ; WriteFile(hf,buf,bufsize,&writ,0); 
      countfile+=bufsize; // countfile counts how much of this file we've unzipped so far
      countall+=bufsize; // countall counts how much total we've unzipped so far
      // Now show progress, and let Windows catch up...
      int i = (int)(100.0*((double)countall)/((double)tot));
      SendMessage(hprog,PBM_SETPOS,i,0); PumpMessages();
    }
    CloseHandle(hf);
    if (abort_p) DeleteFile(fn);
  }
  CloseZip(hz);
}
Esempio n. 5
0
PBYTE WINAPI duWindowManager::GetZipResource(LPCTSTR lpszResName, HANDLE &hMem, IStream *&pStream)
{
	if (lpszResName == NULL || m_hZip == NULL)
		return NULL;
	
	TCHAR szDir[1024];
	_tcsncpy(szDir, lpszResName, MAX_PATH);
	
	TCHAR *lpStartChar = szDir; 
	TCHAR *lpChar = _tcschr(lpStartChar, '\\');
	while (lpChar)
	{
		*lpChar = 0;
		if (SetUnzipBaseDir(m_hZip, lpStartChar) != ZR_OK)
			return NULL;
		
		lpChar++;
		lpStartChar = lpChar;
		lpChar = _tcschr(lpStartChar, '\\');
	}

	_tcsncpy(szDir, lpszResName, MAX_PATH);
	lpChar = szDir;
	while (*lpChar)
	{
		if (*lpChar == '\\') 
			*lpChar = '/';
		lpChar++;
	}
	
	int nIndex = 0;
	ZIPENTRY ze;
	if (FindZipItem(m_hZip, szDir, true, &nIndex, &ze) != ZR_OK || nIndex == -1)
		return NULL;
	
	hMem = ::GlobalAlloc(GMEM_FIXED, ze.unc_size);
	::CreateStreamOnHGlobal(hMem, FALSE, &pStream);
	if (pStream == NULL)
	{
		::GlobalFree(hMem);
		hMem = NULL;
		return NULL;
	}

	PBYTE pByte = (PBYTE)::GlobalLock(hMem);
	if (UnzipItem(m_hZip, nIndex, pByte, ze.unc_size) != ZR_OK)
	{
		pStream->Release();
		pStream = NULL;
		
		::GlobalFree(hMem);
		hMem = NULL;
		return NULL;
	}
	
	SetUnzipBaseDir(m_hZip, _T(""));
	return pByte;
}
Esempio n. 6
0
bool CZip::extract(const QString & filePath, const QString & extDirPath, const QString & singleFileName, const QString &password)
{
    HZIP hz = OpenZip(filePath.toStdString().c_str(), password.isEmpty() ? 0 : password.toStdString().c_str());

    if(!hz) {
        return false;
    }

    SetUnzipBaseDir(hz,extDirPath.toStdString().c_str());

    if (!singleFileName.isEmpty())
    {
        ZIPENTRY ze;
        int i; 
        FindZipItem(hz, singleFileName.toStdString().c_str(), true, &i, &ze);
        UnzipItem(hz, i, ze.name);
        CloseZip(hz);

        return true;
    }

    for (int i = 0; ;i++)
    { 
        ZIPENTRY ze;
        ZRESULT zr = GetZipItem(hz, i, &ze); 

        if (zr != ZR_OK) {

            if(zr == ZR_FAILED || zr == ZR_NOTFOUND) {
                CloseZip(hz);
                return false;
            }

            break; // no more
        }
        UnzipItem(hz, i, ze.name);
    }

    CloseZip(hz);

    return true;
}
BOOL CMyUtility::UnZip( LPCTSTR wcPathIn, LPCTSTR wcExtractObject, LPCTSTR wcPathOut )
{
	HZIP hz;
	int index, numfile;
	ZIPENTRYW ze = {0};
	TCHAR wcFilePath[MAX_PATH] = {0};
	if(!wcPathIn)
		return FALSE;


	hz = OpenZip((void*)wcPathIn, 0, ZIP_FILENAME);
	if (!hz)
		return FALSE;
	GetZipItem(hz, -1, &ze);
	numfile = ze.index;
	for(index = 0; index < numfile; index++)
	{
		GetZipItem(hz, index, &ze);
		if (!wcExtractObject)
		{
			swprintf(wcFilePath, MAX_PATH - 1, _T("%s\\%s"), wcPathOut, ze.name);
			UnzipItem(hz, index, wcFilePath, 0, ZIP_FILENAME);
		}
		else 
		{
			int len = lstrlen(wcExtractObject);
			if (_tcsnicmp(wcExtractObject, ze.name, len) == 0)
			{
				swprintf(wcFilePath, MAX_PATH - 1, _T("%s\\%s"), wcPathOut, ze.name);
				UnzipItem(hz, index, wcFilePath, 0, ZIP_FILENAME);
				//check to know object need to be extracted is file
				if (!(ze.attr & FILE_ATTRIBUTE_DIRECTORY) && len == lstrlen(ze.name))
					break;
			}
		}
	}
	CloseZip(hz);
	return TRUE;

	return TRUE;
}
Esempio n. 8
0
int unziplib_c::extractFile(char * fName, char * fFile) {
  ZIPENTRY ze;
  int itemCount = getCount();
  for (int i=0; i<itemCount; i++) {
    GetZipItem(hz,i,&ze);
    if (strcmp(ze.name, fName) == 0) {
      UnzipItem(hz,i,fFile);
      i = itemCount;
    }
  }
  return 0;
}
Esempio n. 9
0
void CAppManager::ReloadRhoBundle(const char* szUrl, const char* szZipPassword)
{
	if ( szUrl )
	{
		//get zip file with rhodes
		DWORD dwDataSize = 0;
		char* zipData = remote_data( L"GET", const_cast<char*>(szUrl), NULL, 0, false, true, false, &dwDataSize );

		LPWSTR rootw = wce_mbtowc(RhoGetRootPath());  

		//TODO: Add error handling
		if ( zipData && dwDataSize > 0 )
		{
			ZIPENTRY ze; 
			// Open zip file
			HZIP hz = OpenZip(zipData, dwDataSize, szZipPassword);
			
			if ( hz )
			{
				//Stop HTTP Server
				CHttpServer::Instance()->FreezeThread();

				// Set base for unziping
				SetUnzipBaseDir(hz, rootw);
				
				// Get info about the zip
				// -1 gives overall information about the zipfile
				GetZipItem(hz,-1,&ze);
				int numitems = ze.index;
				
				// Iterate through items and unzip them
				for (int zi = 0; zi<numitems; zi++)
				{ 
					// fetch individual details, e.g. the item's name.
					GetZipItem(hz,zi,&ze); 
					// unzip item
					UnzipItem(hz, zi, ze.name);         
				}
				
				CloseZip(hz);

				//Show MessageBox
				MessageBox(NULL, _T("Rhobundle has been updated successfully.\n\nPlease restart application."), _T("Information"), MB_OK | MB_ICONINFORMATION );
			}
		}

		if ( rootw )
			free(rootw);

		if ( zipData )
			delete zipData;
	}
}
Esempio n. 10
0
int unziplib_c::unzipall(char * aFolder) {
  ZIPENTRY ze;
  char * path = new char[MAX_PATH];
  memcpy(path,aFolder,strlen(aFolder)+1);
  int itemCount = getCount();
  for (int i=0; i<itemCount; i++) {
    GetZipItem(hz,i,&ze);
    memcpy(path+strlen(aFolder),ze.name,strlen(ze.name)+1);
    UnzipItem(hz,i,path);
  }
  delete[] path;
  return 0;
}
QString ClassSpaceChecker::unzipFile(const QString &jarPath, const ClassFileContext *ctx)
{
	QString output;
	bool ok = false;

#if defined(Q_WS_WIN)
	QString f = jarPath;
	
	HZIP hz = OpenZip( (void *)f.toStdWString().c_str(), 0, ZIP_FILENAME );
	if( !hz ) 
	{
		QMessageBox::warning(this, "", tr("Jar file not found."));
		ui.comboBox_JarFile->setFocus();
		return "";
	}

	do{
		ZIPENTRYW ze; 
		ZRESULT zr = GetZipItem( hz, -1, &ze ); 
		if( zr != ZR_OK )
			break;
		
		int i; 
		zr = FindZipItem(hz, ctx->filePath.toStdWString().c_str(), true, &i, &ze);
		if( zr != ZR_OK )
			break;

		//QString output = generateFileTempPath() + "Temp.class";
		output = generateFileTempPath() + ctx->fullClassNameForKey + (ctx->javaFileFlag ? ".java" : ".class");
		zr = UnzipItem(hz, i, (void*)output.toStdWString().c_str(), 0, ZIP_FILENAME);
		if( zr != ZR_OK )
			break;

		ok = true;
	} while( false );

	CloseZip(hz);

#else
	// TODO : other platform(MacOS) unzip patch file
	return false;
#endif

	if(ok)
		return output;

	return "";
}
Esempio n. 12
0
int CUpdateThread::UnzipPackage(wchar_t* pPackageName)
{
	if( pPackageName == NULL)
		return -1;

	// 启动线程,进行更新
	HZIP hz = OpenZip((void*)pPackageName, 0, 2);

	unsigned int nZipItemNum;
	ZRESULT zResult = GetZipItemNum(hz, &nZipItemNum);
	if( zResult != ZR_OK)
		return -1;

	size_t i=0;
	for( ; i<nZipItemNum; i++)
	{
		ZIPENTRY ze; 
		zResult = GetZipItemA(hz, i, &ze);
		if( zResult != ZR_OK)
			continue;

		USES_CONVERSION;
		wchar_t* pName = wcsdup(A2W(ze.name));

		wchar_t szName[MAX_PATH];
		memset(szName, 0x0, MAX_PATH);
		swprintf(szName, L"%s%s", MiscHelper::GetUnpackagePath(),pName);
		zResult = UnzipItem(hz, i, (void*)szName, wcslen(szName),ZIP_FILENAME);

		// 解压失败
		if( zResult != ZR_OK)
			break;

		FileHelper::ModifyFileAttribute(szName, 0, FILE_ATTRIBUTE_READONLY);
	}
	CloseZip(hz);

	// 更新失败
	if( i < nZipItemNum)
	{
		::MessageBox(NULL, L"安装包解压失败,无法正确进行更新", L"更新提示", MB_OK);
		return -1;
	}

	return 0;
}
Esempio n. 13
0
bool CDlgView::UnZipFile(string unzipfilename,string zipfilepath)
{
    HZIP hz; //DWORD writ;

    // EXAMPLE 2 - unzip it with the names suggested in the zip
    hz = OpenZip(unzipfilename.c_str(),0);
    string path = zipfilepath +"\\";
    SetUnzipBaseDir(hz,path.c_str());
    ZIPENTRY ze;
    GetZipItem(hz,-1,&ze);
    int numitems=ze.index;
    for (int zi=0; zi<numitems; zi++)
    {   GetZipItem(hz,zi,&ze);
        UnzipItem(hz,zi,ze.name);
    }
    CloseZip(hz);
    return true;
}
Esempio n. 14
0
void test_unzip()
{
    wstring sFilePath;
    sFilePath = L"c:\\1.zip";

    HZIP hz = OpenZip((void *)sFilePath.c_str(), 0, 2);
    if( hz == NULL )
    {
        cout<<"Error opening zip file"<<endl;
        return;
    }
    ZIPENTRY ze; 
    int i; 
    if( FindZipItem(hz, L"1.txt", true, &i, &ze) != 0 )
    {
        cout<<"Could not find ziped file"<<endl;
        return;
    }
    DWORD dwSize = ze.unc_size;
    if( dwSize == 0 ) 
    {
        cout<<"File is empty";
        return;
    }
    if ( dwSize > 4096*1024 ) 
    {
        cout<<"File too large";
        return;
    }
    BYTE* pByte = new BYTE[ dwSize + 1 ];
    ZeroMemory(pByte, dwSize + 1);
    int res = UnzipItem(hz, i, pByte, dwSize, 3);
    if( res != 0x00000000 && res != 0x00000600)
    {
        delete[] pByte;
        CloseZip(hz);
        cout<<"Could not unzip file";
        return;
    }
    CloseZip(hz);
    cout<<pByte<<endl;
    delete[] pByte;
}
Esempio n. 15
0
static BOOL unzip(HZIP zipf, int nitems, IProgressDialog *pd) {
    int i = 0;
    ZRESULT res;
    ZIPENTRYW ze;

    for (i = 0; i < nitems; i++) {
        res = GetZipItem(zipf, i, &ze);
        if (res != ZR_OK) { show_zip_error(L"Failed to get zip item", L"", res); return false;}
        
        res = UnzipItem(zipf, i, ze.name, 0, ZIP_FILENAME);
        if (res != ZR_OK) { CloseZip(zipf); show_zip_error(L"Failed to extract zip item (is your disk full?):", ze.name, res); return false;}

        pd->SetLine(2, ze.name, true, NULL);
        pd->SetProgress(i, nitems);
    }

    CloseZip(zipf);

    return true;
}
Esempio n. 16
0
int main()
{   HZIP hz;

    hz = CreateZip("std1.zip",0);
    ZipAdd(hz,"znsimple.jpg", "std_sample.jpg");
    ZipAdd(hz,"znsimple.txt", "std_sample.txt");
    CloseZip(hz);

    hz = OpenZip("std1.zip",0);
    ZIPENTRY ze;
    GetZipItem(hz,-1,&ze);
    int numitems=ze.index;
    for (int zi=0; zi<numitems; zi++)
    {   GetZipItem(hz,zi,&ze);
        UnzipItem(hz,zi,ze.name);
    }
    CloseZip(hz);

    return 0;
}
Esempio n. 17
0
int rho_unzip_file(const char* szZipPath)
{
#ifdef  UNICODE
    rho::StringW strZipPathW;
    rho::common::convertToStringW(szZipPath, strZipPathW);
    HZIP hz = OpenZipFile(strZipPathW.c_str(), "");
    if ( !hz )
        return 0;

	// Set base for unziping
    SetUnzipBaseDir(hz, rho::common::convertToStringW(RHODESAPPBASE().getDBDirPath()).c_str() );
#else
    HZIP hz = OpenZipFile(szZipPath, "");
    if ( !hz )
        return 0;

	// Set base for unziping
    SetUnzipBaseDir(hz, RHODESAPPBASE().getDBDirPath().c_str() );
#endif

    ZIPENTRY ze;
    ZRESULT res = 0;
	// Get info about the zip
	// -1 gives overall information about the zipfile
	res = GetZipItem(hz,-1,&ze);
	int numitems = ze.index;

	// Iterate through items and unzip them
	for (int zi = 0; zi<numitems; zi++)
	{ 
		// fetch individual details, e.g. the item's name.
		res = GetZipItem(hz,zi,&ze); 
        if ( res == ZR_OK )
    		res = UnzipItem(hz, zi, ze.name);         
	}

	CloseZip(hz);

    return res == ZR_OK ? 1 : 0;
}
Esempio n. 18
0
	void FileUtils::Unzip(std::string& source, std::string& destination, 
		UnzipCallback callback, void *data)
	{
		std::wstring wideSource = UTILS_NS::UTF8ToWide(source);
		std::wstring wideDestination = UTILS_NS::UTF8ToWide(destination);

		HZIP handle = OpenZip(wideSource.c_str(), 0);
		SetUnzipBaseDir(handle, wideDestination.c_str());

		ZIPENTRY zipEntry; ZeroMemory(&zipEntry, sizeof(ZIPENTRY));

		GetZipItem(handle, -1, &zipEntry);
		int numItems = zipEntry.index;
		if (callback != NULL)
		{ 
			std::ostringstream message;
			message << "Starting extraction of " << numItems 
				<< " items from " << source << "to " << destination;
			std::string messageString = message.str();
			callback((char*) messageString.c_str(), 0, numItems, data);
		}
		
		for (int zi = 0; zi < numItems; zi++) 
		{ 
			ZeroMemory(&zipEntry, sizeof(ZIPENTRY));
			GetZipItem(handle, zi, &zipEntry);
			
			if (callback != NULL)
			{
				std::string name = WideToUTF8(zipEntry.name);
				std::string message = "Extracting ";
				message.append(name);
				message.append("...");
				callback((char*) message.c_str(), zi, numItems, data);
			}
			
			UnzipItem(handle, zi, zipEntry.name);
		}
		CloseZip(handle);
	}
Esempio n. 19
0
std::pair<size_t, std::unique_ptr<T[]>> OpticPack::fetchFile(HZIP handle, const std::string& file, bool text) {
    int index = -1;
    ZIPENTRY entry;

    ZRESULT zr = FindZipItem(handle, file.c_str(), true, &index, &entry);

    if(zr != ZR_OK) {
        throw OpticPackException();
    }

    size_t bufferLen = text? entry.unc_size + 1 : entry.unc_size;

    std::unique_ptr<T[]> buffer(new T[bufferLen]);
    memset(buffer.get(), 0, bufferLen);
    zr = UnzipItem(handle, index, buffer.get(), entry.unc_size, ZIP_MEMORY);

    if(zr != ZR_OK && zr != ZR_MORE) { //Xzip doesn't work properly - this means nothing
        throw OpticPackException();
    }

    return std::make_pair(bufferLen, std::move(buffer));
}
Esempio n. 20
0
bool unzipPatchFile( void )
{
#if defined(Q_WS_WIN)
	QString f = DEFAULT_UPGRADE_FILE_NAME;
	
	HZIP hz = OpenZip( (void *)f.toStdWString().c_str(), 0, ZIP_FILENAME );
	if( !hz )
		return false;

	do{
		ZIPENTRYW ze; 
		ZRESULT zr = GetZipItem( hz, -1, &ze ); 
		if( zr != ZR_OK )
		{
			qDebug() <<  "unzipPatchFile failed : " << zr; 
			break;
		}
		int numitems = ze.index;
		for( int i = 0; i < numitems; i++ )
		{ 
			GetZipItem( hz, i, &ze );
			qDebug() <<  "unzipPatchFile" << ze.name;
			UnzipItem( hz, i, ze.name, 0, ZIP_FILENAME );
		}
	} while( false );

	CloseZip(hz);

	QFile::remove( DEFAULT_UPGRADE_FILE_NAME );

#else
	// TODO : other platform(MacOS) unzip patch file
#endif

	return false;
}
Esempio n. 21
0
void ZipArchive::UnzipThreadFunc(const std::string& zip, const std::string& target, UnzipDoneCallback callback, void* cbUserdata)
{
	LogInfo() << "Unzipping file: " << zip;

	HZIP hz = OpenZip((void *)zip.c_str(), 0, ZIP_FILENAME);

	if(!hz)
	{
		LogWarn() << "Failed to open Zip-File: " << zip;
		return;
	}

	// Get last entry
	ZIPENTRY ze;
	ZRESULT zr = GetZipItem(hz, -1, &ze); 

	if (zr == ZR_OK)
	{
		int numItems = ze.index;

		LogInfo() << " - Found " << numItems << " items in ZipFile";

		for(int i=0;i<numItems;i++)
		{
			GetZipItem(hz, i, &ze); 
			std::string t = target + "\\" + ze.name;
			LogInfo() << " - Unzipping file to: " << t;;

			UnzipItem(hz, i, (void *)t.c_str(), 0, ZIP_FILENAME);

			callback(zip, cbUserdata, i, numItems);
		}
	}
	
	CloseZip(hz);
}
Esempio n. 22
0
/** unzips the given archive */
XRESULT ZipArchive::Unzip(const std::string& zip, const std::string& target)
{
	LogInfo() << "Unzipping file: " << zip;

	HZIP hz = OpenZip((void *)zip.c_str(), 0, ZIP_FILENAME);

	if(!hz)
	{
		LogWarn() << "Failed to open Zip-File: " << zip;
		return XR_FAILED;
	}

	// Get last entry
	ZIPENTRY ze;
	ZRESULT zr = GetZipItem(hz, -1, &ze); 

	if (zr == ZR_OK)
	{
		int numItems = ze.index;

		LogInfo() << " - Found " << numItems << " items in ZipFile";

		for(int i=0;i<numItems;i++)
		{
			GetZipItem(hz, i, &ze); 
			std::string t = target + "\\" + ze.name;
			LogInfo() << " - Unzipping file to: " << t;;

			UnzipItem(hz, i, (void *)t.c_str(), 0, ZIP_FILENAME);
		}
	}
	
	CloseZip(hz);

	return XR_SUCCESS;
}
Esempio n. 23
0
DWORD WINAPI decompress(LPVOID lpParam)
{	
	//Open struct and set variables
	PMYDATA pDataArray = (PMYDATA)lpParam;				//Open the struct
	char *infilename = pDataArray -> para_infilename;	//Get input file name
	char *outfilename = pDataArray -> para_outfilename;	//Get output file name
	char *password = pDataArray -> para_password;		//Get password
	LPRDATA rdPtr = pDataArray -> para_rdPtr;			//Get rdPtr
	
	//Set non-struct variables & begin extraction
	HZIP hz = OpenZip(infilename,0); //0 = no password
	SetUnzipBaseDir(hz,outfilename); //Set the extract-to folder
	ZIPENTRY baseze;
	ZRESULT zr = GetZipItem(hz,-1,&baseze); //ZRESULT zr contains error number.

	//This part may get complicated.
	//No error with no password, so just extract
	for (int zi=0; zi<baseze.index; zi++)
	{
		ZIPENTRY ze;
		GetZipItem(hz,zi,&ze);			// fetch individual details
		zr=UnzipItem(hz, zi, ze.name);	// e.g. the item's name.
	}
	CloseZip(hz);
	if (zr==ZR_OK)
	{
		rdPtr->rRd->PushEvent(0);
		NoCurrentCompression=true;
		PasswordBeingUsed=false;
	}
	else
	{ //Error occured when extracting with no password
		if (zr==ZR_PASSWORD&&password!="0")
		{ //ZR_PASSWORD -> invalid password. So try with password, if one is provided.
			zr = ZR_OK;
			CloseZip(hz);
			hz = OpenZip(infilename,password);
			GetZipItem(hz,-1,&baseze);
			NumberOfFilesExtracted=baseze.index;
			MessageBox(NULL,"zr==ZR_PASSWORD&&password!=\"0\"", "Debug", NULL);
			PasswordBeingUsed=true;
			
			//No error when extracting with given password, so just extract.
			for (int zi=0; zi<baseze.index; zi++)
			{	//I Can Haz Stallage
				ZIPENTRY ze;
				GetZipItem(hz,zi,&ze);			// fetch individual details
				zr=UnzipItem(hz, zi, ze.name);	// e.g. the item's name.
			}
			CloseZip(hz);
			NoCurrentCompression=true;
			if (zr==ZR_OK)
			{
				rdPtr->rRd->PushEvent(0);
				MessageBox(NULL,"zr==ZR_PASSWORD&&password!=\"0\" > zr==ZR_OK", "Debug", NULL);
			}
			else
			{
				if (zr==ZR_PASSWORD)
				{ //The password provided was wrong, so report it.
					returnstring="Password incorrect or required.";
					MessageBox(NULL,"zr==ZR_PASSWORD&&password!=\"0\" > zr==ZR_PASSWORD", "Debug", NULL);
					rdPtr->rRd->PushEvent(1);
				}
				else
				{ //Password was correct but error occured anyway
					MessageBox(NULL,"zr==ZR_PASSWORD&&password!=\"0\" > zr!=ZR_PASSWORD", "Debug", NULL);
					stringstream temp; 
					temp<<"An error occured, but the provided password was correct. Error number "<<zr<<".";
					returnstring=temp.str();
					NoCurrentCompression=true;
					rdPtr->rRd->PushEvent(1);
				}
			}
		}
		else
		{ //Not a password error when we tried to open without a password...
			stringstream temp; 
			temp<<"An error occured - not a password error. Error number "<<zr<<".";
			returnstring=temp.str();
			NoCurrentCompression=true;
			rdPtr->rRd->PushEvent(1);
		}
	}
	//FormatZipMessage(zr,LastFileExtracted,sizeof(LastFileExtracted));
	return 0;
}
Esempio n. 24
0
///////////////////////////////////////////////////////////////////////////////
// VerifyZip
void CXZipTestDlg::VerifyZip(HZIP hz, LPCTSTR lpszFile)
{
#ifdef _UNICODE
	ZIPENTRYW ze;
#else
	ZIPENTRY ze; 
#endif

	memset(&ze, 0, sizeof(ze));
	int index = -1;
	ZRESULT zr = 0;

	zr = FindZipItem(hz, lpszFile, TRUE, &index, &ze);
	TRACE(_T("index=%d\n"), index);

	m_List.Printf(CXListBox::Black, CXListBox::White, 0, 
		_T("    === Checking contents of zip entry %s ==="), lpszFile);

	if (zr == ZR_OK)
		m_List.Printf(CXListBox::Green, CXListBox::White, 0, 
			_T("    FindZipItem returned OK"));
	else
		m_List.Printf(CXListBox::Red, CXListBox::White, 0, 
			_T("    FindZipItem failed"));

	if (_tcscmp(lpszFile, ze.name) == 0)
		m_List.Printf(CXListBox::Green, CXListBox::White, 0, 
			_T("    FindZipItem found name ==> OK"));
	else
		m_List.Printf(CXListBox::Red, CXListBox::White, 0, 
			_T("    FindZipItem failed to find name"));

	TCHAR targetname[MAX_PATH];
	_tcscpy(targetname, _T("_unzip"));
	_tcscat(targetname, lpszFile);

	// delete target file if it exists
	::DeleteFile(targetname);

	zr = UnzipItem(hz, index, targetname, 0, ZIP_FILENAME);

	if (zr == ZR_OK)
		m_List.Printf(CXListBox::Green, CXListBox::White, 0, 
			_T("    UnzipItem returned OK"));
	else
		m_List.Printf(CXListBox::Red, CXListBox::White, 0, 
			_T("    UnzipItem failed"));

	if (_taccess(targetname, 04) == 0)
		m_List.Printf(CXListBox::Green, CXListBox::White, 0, 
			_T("    Target file created OK"));
	else
		m_List.Printf(CXListBox::Red, CXListBox::White, 0, 
			_T("    UnzipItem failed to create target file"));

	BOOL bResult = FALSE;
	BOOL bRet = Compare(lpszFile, targetname, &bResult);

	if (bRet && bResult)
		m_List.Printf(CXListBox::Green, CXListBox::White, 0, 
			_T("    Target file matches original file ==> OK"));
	else
		m_List.Printf(CXListBox::Red, CXListBox::White, 0, 
			_T("    Target file does not match original file"));

	// the target file is not deleted - you can inspect it after running test

	//::DeleteFile(targetname);
}
Esempio n. 25
0
int 
GetFileList(CString sZipName, std::map<std::string, std::string>& file_list)
{
  strconv_t strconv;

  HZIP hz = OpenZip(sZipName, NULL);
  if(hz==NULL)
    return 1;

  int index = -1;
  ZIPENTRY ze;
  ZRESULT zr = FindZipItem(hz, _T("crashrpt.xml"), false, &index, &ze);
  if(zr!=ZR_OK)
  {
    CloseZip(hz);
    return 2;
  }

  CString sTempFileName = Utility::getTempFileName();
  zr = UnzipItem(hz, index, sTempFileName);
  if(zr!=ZR_OK)
  {
    CloseZip(hz);
    return 2;
  }

  CString sTempDir = Utility::getTempFileName();
  DeleteFile(sTempDir);

  BOOL bCreateDir = CreateDirectory(sTempDir, NULL);  
  ATLASSERT(bCreateDir);
  bCreateDir;
  
  LPCSTR lpszTempFileName = strconv.t2a(sTempFileName.GetBuffer(0));

  TiXmlDocument doc;
  bool bLoad = doc.LoadFile(lpszTempFileName);
  if(!bLoad)
  {
    CloseZip(hz);
    return 3;
  }

  TiXmlHandle hRoot = doc.FirstChild("CrashRpt");
  if(hRoot.ToElement()==NULL)
  {
    CloseZip(hz);
    return 4;
  }
  
  TiXmlHandle fl = hRoot.FirstChild("FileList");
  if(fl.ToElement()==0)
  {
    CloseZip(hz);
    return 5;
  }

  TiXmlHandle fi = fl.FirstChild("FileItem");
  while(fi.ToElement()!=0)
  {
    const char* pszName = fi.ToElement()->Attribute("name");
    const char* pszDesc = fi.ToElement()->Attribute("description");

    if(pszName!=NULL && pszDesc!=NULL)
    {
	    CString sFileName = pszName;
      CString sFilePathName = sTempDir + _T("\\") + CString(pszName);      
      int index = -1;
      ZIPENTRY ze;	  
      ZRESULT zr = FindZipItem(hz, sFileName, false, &index, &ze);
      zr = UnzipItem(hz, index, sFilePathName);
	    LPCSTR pszFilePathName = strconv.t2a(sFilePathName.GetBuffer(0));
      file_list[pszFilePathName]=pszDesc;
    }

    fi = fi.ToElement()->NextSibling("FileItem");
  }

  CloseZip(hz);

  return 0;
}
Esempio n. 26
0
int unziplib_c::extractFile(int i, char * fFile) {
  UnzipItem(hz,i,fFile);
  return 0;
}
Esempio n. 27
0
DWORD DecompressManager::deCompressProc_(LPVOID lpParameter)
{

    DecompressManager* self = (DecompressManager*)lpParameter;

    TCHAR* sourceFileName = FileInfo::getInstance().getSourceFileName();
    TCHAR* targetDir = FileInfo::getInstance().getTargetFileName();

    if (sourceFileName == NULL)
    {
        self->decompressDelegate_->decompressError(SOURCE_FILE_PATH_ERROR);
        return 0;
    }

    if (targetDir == NULL)
    {
        self->decompressDelegate_->decompressError(TARGET_DIR_PATH_ERROR);
        return 0;
    }



    HZIP hz = OpenZip(sourceFileName,0);
    if (hz == NULL)
    {
        self->decompressDelegate_->decompressError(OPEN_ZIP_FILE_ERROR);
        return 0;
    }

    TCHAR appDir[MAX_PATH];
    wcscpy(appDir, targetDir);
    wcscat(appDir, L"F33APP\\");
    self->deleteDirectory_(appDir);

    ZIPENTRY ze;
    if (GetZipItem(hz,-1,&ze) != ZR_OK)
    {
        self->decompressDelegate_->decompressError(GET_ZIP_HEAD_ERROR);
        return 0;
    }

    DWORD numitems=ze.index;
    long unzipSize = ze.unc_size;

    for (int zi=0; zi<numitems; zi++)
    {

        ZIPENTRY ze;
        if (GetZipItem(hz,zi,&ze) != ZR_OK) // fetch individual details
        {
            self->decompressDelegate_->decompressError(GET_ZIP_ITEM_ERROR);
            return 0;
        }
        unzipSize += ze.unc_size;
    }

    ULARGE_INTEGER freeBytesAvailableToCaller;
    ULARGE_INTEGER totalNumberOfBytes;
    ULARGE_INTEGER totalNumberOfFreeBytes;

#define RESERVED_SPACE	1024*1024
    if (GetDiskFreeSpaceEx(targetDir, &freeBytesAvailableToCaller, &totalNumberOfBytes, &totalNumberOfFreeBytes))
    {
        if (freeBytesAvailableToCaller.QuadPart < (unzipSize + RESERVED_SPACE))
        {
            self->decompressDelegate_->decompressError(NO_ENOUGH_SPACE_ERROR);
            CloseZip(hz);
            return 0;
        }
    }
    else
    {
        self->decompressDelegate_->decompressError(NO_ENOUGH_SPACE_ERROR);
        CloseZip(hz);
        return 0;
    }

    self->decompressDelegate_->updateZipInfo(numitems);

    for (int zi=0; zi<numitems; zi++)
    {

        ZIPENTRY ze;
        if (GetZipItem(hz,zi,&ze) != ZR_OK) // fetch individual details
        {
            self->decompressDelegate_->decompressError(GET_ZIP_ITEM_ERROR);
            return 0;
        }

        TCHAR tempPath[MAX_PATH] = {0};
        wcscpy(tempPath, targetDir);
        wcscat(tempPath, ze.name);
        self->replace_(tempPath);

        DWORD unzipResult = UnzipItem(hz, zi, tempPath);
        if (unzipResult != ZR_OK)         // e.g. the item's name.
        {
            self->decompressDelegate_->decompressError(UNZIP_PROC_ERROR);
            return 0;
        }
        self->decompressDelegate_->updateStep(ze.name);
        int lastPostion = wcslen(ze.name)-1;
        if ((ze.name[lastPostion] != L'\\') && (ze.name[lastPostion] != L'/'))
        {
            //处理一下,使MAP的KEY和JSON的KEY一致
            TCHAR keyName[MAX_PATH] = {0};
            wcscpy(keyName, ze.name);
            self->replace_(keyName);
            self->fileContainer_[keyName] = tempPath;
        }
    }
    CloseZip(hz);
    if (self->checkFlag_)
    {
        self->checkMd5();
    }

    self->decompressDelegate_->decompressFinish();
    return 0;
}
Esempio n. 28
0
int CUpdateRunner::ExtractUpdaterAndRun(wchar_t* lpCommandLine)
{
	PROCESS_INFORMATION pi = { 0 };
	STARTUPINFO si = { 0 };
	CResource zipResource;
	wchar_t targetDir[MAX_PATH];
	wchar_t logFile[MAX_PATH];
	std::vector<CString> to_delete;

	ExpandEnvironmentStrings(L"%LocalAppData%\\SquirrelTemp", targetDir, _countof(targetDir));
	if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {
		goto failedExtract;
	}

	swprintf_s(logFile, L"%s\\SquirrelSetup.log", targetDir);

	if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) {
		goto failedExtract;
	}

	DWORD dwSize = zipResource.GetSize();
	if (dwSize < 0x100) {
		goto failedExtract;
	}

	BYTE* pData = (BYTE*)zipResource.Lock();
	HZIP zipFile = OpenZip(pData, dwSize, NULL);
	SetUnzipBaseDir(zipFile, targetDir);

	// NB: This library is kind of a disaster
	ZRESULT zr;
	int index = 0;
	do {
		ZIPENTRY zentry;
		wchar_t targetFile[MAX_PATH];

		zr = GetZipItem(zipFile, index, &zentry);
		if (zr != ZR_OK && zr != ZR_MORE) {
			break;
		}

		// NB: UnzipItem won't overwrite data, we need to do it ourselves
		swprintf_s(targetFile, L"%s\\%s", targetDir, zentry.name);
		DeleteFile(targetFile);

		if (UnzipItem(zipFile, index, zentry.name) != ZR_OK) break;
		to_delete.push_back(CString(targetFile));
		index++;
	} while (zr == ZR_MORE || zr == ZR_OK);

	CloseZip(zipFile);
	zipResource.Release();

	// nfi if the zip extract actually worked, check for Update.exe
	wchar_t updateExePath[MAX_PATH];
	swprintf_s(updateExePath, L"%s\\%s", targetDir, L"Update.exe");

	if (GetFileAttributes(updateExePath) == INVALID_FILE_ATTRIBUTES) {
		goto failedExtract;
	}

	// Run Update.exe
	si.cb = sizeof(STARTUPINFO);
	si.wShowWindow = SW_SHOW;
	si.dwFlags = STARTF_USESHOWWINDOW;

	if (!lpCommandLine || wcsnlen_s(lpCommandLine, MAX_PATH) < 1) {
		lpCommandLine = L"--install .";
	}

	wchar_t cmd[MAX_PATH];
	swprintf_s(cmd, L"%s %s", updateExePath, lpCommandLine);

	if (!CreateProcess(NULL, cmd, NULL, NULL, false, 0, NULL, targetDir, &si, &pi)) {
		goto failedExtract;
	}

	WaitForSingleObject(pi.hProcess, INFINITE);

	DWORD dwExitCode;
	if (!GetExitCodeProcess(pi.hProcess, &dwExitCode)) {
		dwExitCode = (DWORD)-1;
	}

	if (dwExitCode != 0) {
		DisplayErrorMessage(CString(
			L"There was an error while installing the application. " 
			L"Check the setup log for more information and contact the author."), logFile);
	}

	for (unsigned int i = 0; i < to_delete.size(); i++) {
		DeleteFile(to_delete[i]);
	}

	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);
	return (int) dwExitCode;

failedExtract:
	DisplayErrorMessage(CString(L"Failed to extract installer"), NULL);
	return (int) dwExitCode;
}
Esempio n. 29
0
bool UncompressAllFiles(std::string ZipName, std::vector<std::string>* pFileNames, std::vector<std::vector<char> >* data, std::string* pError)
{
#ifdef WIN32

	HZIP hz = OpenZip(ZipName.c_str(),0);
	if (!hz){if(pError) *pError += ("Unable to open ZIP archive. Aborting.\n"); return false;}

	ZIPENTRY ze;
	if (GetZipItem(hz, -1, &ze) != ZR_OK) {if(pError) *pError += ("Unable to return information about ZIP archive. Aborting.\n"); return false;}
	int NumFiles = ze.index;

	//set up returns for the number of files...
	pFileNames->resize(NumFiles);
	data->resize(NumFiles);

	for (int i=0; i<NumFiles; i++){
		if (GetZipItem(hz,i,&ze) != ZR_OK) {if(pError) *pError += "Error loading ZIP file information. Aborting.\n"; return false;}
		int size = ze.unc_size;
		(*data)[i].resize(size+1);

		if (UnzipItem(hz, i, &((*data)[i].front()), size) != ZR_OK) {if(pError) *pError += "Could not unzip sub-file. Aborting.\n"; return false;}

		(*data)[i][size] = '\0';

		(*pFileNames)[i] = ze.name;
	}
	if (CloseZip(hz) != ZR_OK) {if(pError) *pError += "Error closing ZIP file.\n"; return false;}

	return true;

#else
	//Mac/Linux Zip read code
	int err;
	struct zip * hz = zip_open(ZipName.c_str(), ZIP_CHECKCONS, &err);

	if (!hz){if(pError) *pError += ("Unable to open ZIP archive. Aborting.\n"); return false;}

	int NumFiles = zip_get_num_entries(hz,0);
	if (NumFiles < 0) { if(pError) *pError += ("Unable to return information about ZIP archive. Aborting.\n"); return false;}

	//set up returns for the number of files...
	pFileNames->resize(NumFiles);
	data->resize(NumFiles);

	for (int i=0; i<NumFiles; i++){
		struct zip_stat stat;
		err = zip_stat_index(hz, i, 0, &stat);
		int size = stat.size;
		(*data)[i].resize(size+1);

	        struct zip_file * zfile = zip_fopen_index(hz, i, 0);

		if (zip_fread(zfile, &((*data)[i].front()), size) != size) {if(pError) *pError += "Could not unzip sub-file. Aborting.\n"; return false;}

		(*data)[i][size] = '\0';

		(*pFileNames)[i] = zip_get_name(hz, i, 0);
	}

	if (zip_close(hz) != 0) {if(pError) *pError += "Error closing ZIP file.\n"; return false;}
	return true;
#endif
}
Esempio n. 30
0
bool GetCompressedFiles(std::string ZipName, std::vector<std::string>* pFileNames,
			std::vector<std::vector<char> >* data, std::string* pError)
{
#ifdef WIN32

	HZIP hz = OpenZip(ZipName.c_str(),0);
	if (!hz){if(pError) *pError += ("Unable to open ZIP archive. Aborting.\n"); return false;}

	ZIPENTRY ze;
	if (GetZipItem(hz, -1, &ze) != ZR_OK) {if(pError) *pError += ("Unable to return information about ZIP archive. Aborting.\n"); return false;}
	int NumFiles = ze.index;

	//set up returns for data...
	data->resize(NumFiles);

	for (int i=0; i<NumFiles; i++){
		if (GetZipItem(hz,i,&ze) != ZR_OK) {if(pError) *pError += "Error loading ZIP file information. Aborting.\n"; return false;}

		int NumDesiredFiles = pFileNames->size();
		for (int j=0; j<NumDesiredFiles; j++){
			if ((*pFileNames)[j].compare(ze.name)==0){ //if this is one of the file's we're looking for
				int size = ze.unc_size;
				(*data)[j].resize(size+1); //or clear...

				if (UnzipItem(hz, i, &((*data)[j].front()), size) != ZR_OK) {if(pError) *pError += "Could not unzip sub-file. Aborting.\n"; return false;}

				(*data)[j][size] = '\0';

			}
		}
	}
	if (CloseZip(hz) != ZR_OK) {if(pError) *pError += "Error closing ZIP file.\n"; return false;}

	return true;

#else
	//Mac/Linux Zip read code
	int err;
	struct zip * hz = zip_open(ZipName.c_str(), ZIP_CHECKCONS, &err);

	if (!hz){if(pError) *pError += ("Unable to open ZIP archive. Aborting.\n"); return false;}

	int NumFiles = zip_get_num_entries(hz,0);
	if (NumFiles < 0) { if(pError) *pError += ("Unable to return information about ZIP archive. Aborting.\n"); return false;}

	//set up returns for data...
	data->resize(NumFiles);

	for (uint i=0; i<NumFiles; i++){
	        struct zip_file * zfile = zip_fopen_index(hz, i, 0);

		int NumDesiredFiles = pFileNames->size();
		const char * entryname = zip_get_name(hz, i, 0);
		struct zip_stat stat;
		err = zip_stat_index(hz, i, 0, &stat);

		for (int j=0; j<NumDesiredFiles; j++){
			if ((*pFileNames)[j].compare(entryname)==0){ //if this is one of the file's we're looking for
				int size = stat.size;
				(*data)[j].resize(size+1); //or clear...

				if (zip_fread(zfile, &((*data)[j].front()), size) != size) {if(pError) *pError += "Could not unzip sub-file. Aborting.\n"; return false;}

				(*data)[j][size] = '\0';
			}
		}
		zip_fclose(zfile);
	}
	if (zip_close(hz) != 0) {if(pError) *pError += "Error closing ZIP file.\n"; return false;}

	return true;
#endif
}