Exemplo n.º 1
0
nglFileOffset nglZipFS::SetPos (void* pUnzip, nglFileOffset Where, nglIZip* pFile)
{
  unzSetCurrentFile(mpPrivate->mZip, pUnzip);
  char dummy[1024];
  nglFileOffset Pos = GetPos(pUnzip);

  if (Where < Pos)
  {
    unzCloseCurrentFile(mpPrivate->mZip);

    unz_file_pos file_pos;
    file_pos.num_of_file = pFile->mNumOfFile;
    file_pos.pos_in_zip_directory = pFile->mPosInZipDirectory;
    unzGoToFilePos(mpPrivate->mZip, &file_pos);

    if (unzOpenCurrentFile(mpPrivate->mZip) != UNZ_OK)
      return 0;

    pUnzip = unzGetCurrentFile(mpPrivate->mZip);
    pFile->SetRef(pUnzip);
    Pos = 0;

    if (!pUnzip)
      return 0;
  }

  Where -= Pos;
  while (Where > 0)
  {
    nglFileOffset size = MIN(Where, 1024);
    nglSize res = Read(pUnzip, dummy, (long)size, 1, eEndianNative);

    if (res <= 0) // An Error occured
      return GetPos(pUnzip);

    Where -= res;
  }

  return GetPos(pUnzip);
}
Exemplo n.º 2
0
unsigned char* ZipFile::getFileData(const std::string& fileName, unsigned long* pSize)
{
    unsigned char* pBuffer = NULL;
    if (pSize)
    {
        *pSize = 0;
    }

    do
    {
        CC_BREAK_IF(!m_data->zipFile);
        CC_BREAK_IF(fileName.empty());
		
		std::string file(fileName);
		//str_tolower(file);

        ZipFilePrivate::FileListContainer::const_iterator it = m_data->fileList.find(file);
        CC_BREAK_IF(it == m_data->fileList.end());

        ZipEntryInfo fileInfo = it->second;

        int nRet = unzGoToFilePos(m_data->zipFile, &fileInfo.pos);
        CC_BREAK_IF(UNZ_OK != nRet);

        nRet = unzOpenCurrentFile(m_data->zipFile);
        CC_BREAK_IF(UNZ_OK != nRet);

        pBuffer = new unsigned char[fileInfo.uncompressed_size];
        int CC_UNUSED nSize = unzReadCurrentFile(m_data->zipFile, pBuffer, (unsigned int)fileInfo.uncompressed_size);
        CCAssert(nSize == 0 || nSize == (int)fileInfo.uncompressed_size, "the file size is wrong");

        if (pSize)
        {
            *pSize = fileInfo.uncompressed_size;
        }
        unzCloseCurrentFile(m_data->zipFile);
    } while (0);

    return pBuffer;
}
Exemplo n.º 3
0
KDubyte* ZipFile::getFileData ( const std::string& sFileName, KDsize* pSize )
{
    KDubyte*  pBuffer = KD_NULL;

    if ( pSize )
    {
        *pSize = 0;
    }

    do
    {
        CC_BREAK_IF ( !m_pData->zipFile );
        CC_BREAK_IF ( sFileName.empty ( ) );

        ZipFilePrivate::FileListContainer::const_iterator  it = m_pData->fileList.find ( sFileName );
        CC_BREAK_IF ( it ==  m_pData->fileList.end ( ) );

        ZipEntryInfo  tFileInfo = it->second;

        KDint  nRet = unzGoToFilePos ( m_pData->zipFile, &tFileInfo.pos );
        CC_BREAK_IF ( UNZ_OK != nRet );

        nRet = unzOpenCurrentFile ( m_pData->zipFile );
        CC_BREAK_IF ( UNZ_OK != nRet );

        pBuffer = new KDubyte [ tFileInfo.uncompressed_size ];
        KDint  nSize = 0;
        nSize = unzReadCurrentFile ( m_pData->zipFile, pBuffer, tFileInfo.uncompressed_size );
        CCAssert ( nSize == 0 || nSize == (KDint) tFileInfo.uncompressed_size, "the file size is wrong" );

        if ( pSize )
        {
            *pSize = tFileInfo.uncompressed_size;
        }
        unzCloseCurrentFile ( m_pData->zipFile );

    } while ( 0 );

    return pBuffer;
}
Exemplo n.º 4
0
// This is DEFINITELY NOT thread safe! 
void ovr_ReadFileFromApplicationPackage( const char * nameInZip, int &length, void * & buffer )
{
	length = 0;
	buffer = NULL;
	const int locateRet = unzLocateFile( packageZipFile, nameInZip, 2 /* case insensitive */ );
	if ( locateRet != UNZ_OK )
	{
		LOG( "File '%s' not found in apk!", nameInZip );
		return;
	}

	unz_file_info	info;
	const int getRet = unzGetCurrentFileInfo( packageZipFile, &info, NULL,0, NULL,0, NULL,0);
	if ( getRet != UNZ_OK )
	{
		LOG( "File info error reading '%s' from apk!", nameInZip );
		return;
	}
	const int openRet = unzOpenCurrentFile( packageZipFile );
	if ( openRet != UNZ_OK )
	{
		LOG( "Error opening file '%s' from apk!", nameInZip );
		return;
	}

	length = info.uncompressed_size;
	buffer = malloc( length );

	const int readRet = unzReadCurrentFile( packageZipFile, buffer, length );
	if ( readRet <= 0 )
	{
		LOG( "Error reading file '%s' from apk!", nameInZip );
		free( buffer );
		length = 0;
		buffer = NULL;
		return;
	}

	unzCloseCurrentFile( packageZipFile );
}
Exemplo n.º 5
0
            fileHandleZipStreaming(const file_entry* entry, const Zips& z): _cpos(0)
            {
                int r = 0;
                r = unzGoToFilePos(entry->zp, const_cast<unz_file_pos*>(&entry->pos));
                OX_ASSERT(r == UNZ_OK);

                r = unzOpenCurrentFile(entry->zp);
                OX_ASSERT(r == UNZ_OK);


                void* ptr;
                r = unzRealTell(entry->zp, &_pos, &_size, &ptr);
                OX_ASSERT(r == UNZ_OK);

                zlib_filefunc_def* f = (zlib_filefunc_def*)ptr;
                const char* ssss = z.getZipFileName((int)(size_t)f->opaque);

                _h = file::open(ssss, "rb");
                file::seek(_h, static_cast<unsigned int>(_pos), SEEK_SET);

                unzCloseCurrentFile(entry->zp);
            }
Exemplo n.º 6
0
	string unzReadFile(unzFile zf, const char* fileName)
	{
		string result;
		if (unzLocateFile(zf, fileName, 0) == UNZ_OK)
		{
			if (unzOpenCurrentFile(zf) == UNZ_OK){
				unz_file_info fileInfo;
				memset(&fileInfo, 0, sizeof(unz_file_info));

				if (unzGetCurrentFileInfo(zf, &fileInfo, NULL, 0, NULL, 0, NULL, 0) == UNZ_OK)
				{
					char* buffer = new char[fileInfo.uncompressed_size];
					int readSize = unzReadCurrentFile(zf, buffer, fileInfo.uncompressed_size);
					if (readSize > 0)
						result.assign(buffer, readSize);
					delete[] buffer;
				}
				unzCloseCurrentFile(zf);
			}
		}
		return result;
	}
Exemplo n.º 7
0
	//-----------------------------------------------------------------//
	bool unzip::create_file(uint32_t index, const std::string& filename)
	{
		if(index < static_cast<uint32_t>(files_.size())) {
			unzSetOffset(hnd_, files_[index].ofs_);

			if(unzOpenCurrentFile(hnd_) != UNZ_OK) return false;

			utils::file_io fout;
			fout.open(filename, "wb");

			char buff[4096];
			uLong sz;
			while((sz = unzReadCurrentFile(hnd_, buff, sizeof(buff))) > 0) {
				fout.write(buff, 1, sz);
			}
			unzCloseCurrentFile(hnd_);
			fout.close();

			return true;
		}
		return false;
	}
Exemplo n.º 8
0
unsigned char* FileUtils::getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t *size)
{
    unsigned char * buffer = nullptr;
    unzFile file = nullptr;
    *size = 0;

    do 
    {
        CC_BREAK_IF(zipFilePath.empty());

        file = unzOpen(zipFilePath.c_str());
        CC_BREAK_IF(!file);

        int ret = unzLocateFile(file, filename.c_str(), 1);
        CC_BREAK_IF(UNZ_OK != ret);

        char filePathA[260];
        unz_file_info fileInfo;
        ret = unzGetCurrentFileInfo(file, &fileInfo, filePathA, sizeof(filePathA), nullptr, 0, nullptr, 0);
        CC_BREAK_IF(UNZ_OK != ret);

        ret = unzOpenCurrentFile(file);
        CC_BREAK_IF(UNZ_OK != ret);

        buffer = (unsigned char*)malloc(fileInfo.uncompressed_size);
        int CC_UNUSED readedSize = unzReadCurrentFile(file, buffer, static_cast<unsigned>(fileInfo.uncompressed_size));
        CCASSERT(readedSize == 0 || readedSize == (int)fileInfo.uncompressed_size, "the file size is wrong");

        *size = fileInfo.uncompressed_size;
        unzCloseCurrentFile(file);
    } while (0);

    if (file)
    {
        unzClose(file);
    }

    return buffer;
}
Exemplo n.º 9
0
void FileUtils::extractFromZip(const char* zipFilePath, const char* src, const char* dest) throw (IOException)
{
	unzFile zipFile = unzOpen(zipFilePath);
	int result = unzLocateFile(zipFile,src,0);
	if (result == UNZ_OK)
	{
		// found a match which is now the current file
		unzOpenCurrentFile(zipFile);
		const int chunkSize = 4096;
		char buffer[chunkSize];

		std::ofstream outputFile(dest,std::ofstream::binary);
		if (!outputFile.good())
		{
			throw IOException("Unable to write to file " + std::string(dest));
		}
		while (true)
		{
			int count = unzReadCurrentFile(zipFile,buffer,chunkSize);
			if (count <= 0)
			{
				if (count < 0)
				{
					throw IOException("Error extracting file from archive " + std::string(src));
				}
				break;
			}
			outputFile.write(buffer,count);
		}
		outputFile.close();

		unzCloseCurrentFile(zipFile);
	}
	else
	{
		throw IOException("Unable to find file " + std::string(src) + " in zip archive " + std::string(zipFilePath));
	}
	unzClose(zipFile);
}
Exemplo n.º 10
0
void archive_load_data( const char *file, void **ptr, size_t *size )
{
	unz_file_info info;
	char *data, *data_end;
	int got;

	if ( unzLocateFile(archive_handle, file, 1) != UNZ_OK ) {
		fatal( "Failed to locate archived file: %s\n", file );
	}
	unzOpenCurrentFile( archive_handle );
	unzGetCurrentFileInfo( archive_handle, &info, NULL, 0, NULL, 0, NULL, 0 );
	data = (char*)SDL_malloc( info.uncompressed_size+1 );
	*ptr = data;
	*size = info.uncompressed_size;
	data_end = data + info.uncompressed_size;
	*data_end = 0;

	while ((got = unzReadCurrentFile(archive_handle, data, data_end - data)) > 0) {
		data = data + got;
	}
	unzCloseCurrentFile( archive_handle );
}
Exemplo n.º 11
0
std::vector<unsigned char> Unzip::getFileContent(const std::string & fileName)
{
	std::vector<unsigned char> fileContent;

	if(fileInfos.count(fileName) == 0){
		return fileContent;
	}

	//locate file
	if(! goToFile(fileName)){
		return fileContent;
	}

	//open file
	if(UNZ_OK != unzOpenCurrentFile3(zipfile_handle, NULL, NULL, 0, formatPassword(this->password))){
		return fileContent;
	}

	//read content
	unsigned char buffer[CPPZIP_UNZIP_CHAR_ARRAY_BUFFER_SIZE];

	unsigned int len = 0;
	while((len = unzReadCurrentFile(
			zipfile_handle,
			buffer,
			CPPZIP_UNZIP_CHAR_ARRAY_BUFFER_SIZE))
	){
		for(unsigned int i = 0; i < len; ++i){
			fileContent.push_back(buffer[i]);
		}
	}

	//close file
	if(UNZ_OK != unzCloseCurrentFile(zipfile_handle)){
		return fileContent;
	}

	return fileContent;
}
/// Internal routine to extract a single file from ZIP archive
int ExtractCurrentFile_ZIP( unzFile uf, const char* password, int* abort_flag, float* progress, const clPtr<iOStream>& fout )
{
	char filename_inzip[256];
	int err = UNZ_OK;
	void* buf;
	uInt size_buf;
	unz_file_info64 file_info;

	err = unzGetCurrentFileInfo64( uf, &file_info, filename_inzip, sizeof( filename_inzip ), NULL, 0, NULL, 0 );

	if ( err != UNZ_OK ) { return err; }

	uint64 file_size = ( uint64 )file_info.uncompressed_size;
	uint64 total_bytes = 0;

	unsigned char _buf[WRITEBUFFERSIZE];
	size_buf = WRITEBUFFERSIZE;
	buf = ( void* )_buf;

	err = unzOpenCurrentFilePassword( uf, password );

	if ( err != UNZ_OK ) { return err; }

	do
	{
		err = unzReadCurrentFile( uf, buf, size_buf );

		if ( err < 0 ) { break; }

		if ( err > 0 ) { total_bytes += err; fout->Write( buf, err ); }
	}
	while ( err > 0 );

	int close_err = unzCloseCurrentFile ( uf );

	if ( close_err != UNZ_OK ) { return close_err; }

	return err;
}
Exemplo n.º 13
0
bool FileUtils::mzExtractFile(unzFile uf,
                              const std::string &directory)
{
    unz_file_info64 fi;
    std::string filename;

    if (!mzGetInfo(uf, &fi, &filename)) {
        return false;
    }

    std::string fullPath(directory);
    fullPath += "/";
    fullPath += filename;

    boost::filesystem::path path(fullPath);
    boost::filesystem::create_directories(path.parent_path());

    std::ofstream file(fullPath, std::ios::binary);
    if (file.fail()) {
        return false;
    }

    int ret = unzOpenCurrentFile(uf);
    if (ret != UNZ_OK) {
        return false;
    }

    int n;
    char buf[32768];

    while ((n = unzReadCurrentFile(uf, buf, sizeof(buf))) > 0) {
        file.write(buf, n);
    }

    unzCloseCurrentFile(uf);

    return n == 0;
}
Exemplo n.º 14
0
bool FileUtils::mzReadToMemory(unzFile uf,
                               std::vector<unsigned char> *output,
                               void (*cb)(uint64_t bytes, void *), void *userData)
{
    unz_file_info64 fi;

    if (!mzGetInfo(uf, &fi, nullptr)) {
        return false;
    }

    std::vector<unsigned char> data;
    data.reserve(fi.uncompressed_size);

    int ret = unzOpenCurrentFile(uf);
    if (ret != UNZ_OK) {
        return false;
    }

    int n;
    char buf[32768];

    while ((n = unzReadCurrentFile(uf, buf, sizeof(buf))) > 0) {
        if (cb) {
            cb(data.size() + n, userData);
        }

        data.insert(data.end(), buf, buf + n);
    }

    unzCloseCurrentFile(uf);

    if (n != 0) {
        return false;
    }

    data.swap(*output);
    return true;
}
Exemplo n.º 15
0
static duk_ret_t dukzip_unz_readfile(duk_context *ctx) {
	unz_file_info fileInfo;
	unzFile archive = dukzip_unz_from_this(ctx);
	int ret = UNZ_OK;

	unzGetCurrentFileInfo(archive, &fileInfo, NULL, 0, NULL, 0, NULL, 0);
	void *bytes = duk_push_fixed_buffer(ctx, fileInfo.uncompressed_size);

	ret = unzOpenCurrentFile(archive);
	if (ret != UNZ_OK) {
		duk_error(ctx, DUK_ERR_INTERNAL_ERROR, "unable to open file in archive");
		return -1;
	}

	ret = unzReadCurrentFile(archive, bytes, fileInfo.uncompressed_size);
	if (ret < 0) {
		duk_error(ctx, DUK_ERR_INTERNAL_ERROR, "unable to read file in archive");
		return -1;
	}
	unzCloseCurrentFile(archive);

	return 1;
}
Exemplo n.º 16
0
unsigned char* CCZipFile::getFileDataNoOrder(const char *fileName, unsigned long *pSize)
{
    unsigned char * pBuffer = NULL;
    if (pSize)
    {
        *pSize = 0;
    }    
    do
    {
        CC_BREAK_IF(!m_zipFile);
        CC_BREAK_IF(m_fileList.empty());
        
        std::map<std::string, struct __ZipEntryInfo>::const_iterator it = m_fileList.find(fileName);
        CC_BREAK_IF(it ==  m_fileList.end());
        
        __ZipEntryInfo fileInfo = it->second;
        
        int nRet = unzGoToFilePos(m_zipFile, &fileInfo.pos);
        CC_BREAK_IF(UNZ_OK != nRet);
        
        nRet = unzOpenCurrentFile(m_zipFile);
        CC_BREAK_IF(UNZ_OK != nRet);
        //MARK unfinish process big file
        pBuffer = new unsigned char[fileInfo.uncompressed_size];
        int CC_UNUSED nSize = unzReadCurrentFile(m_zipFile, pBuffer, fileInfo.uncompressed_size);
        CCAssert(nSize == 0 || nSize == (int)fileInfo.uncompressed_size, "the file size is wrong");
        
        if (pSize)
        {
            *pSize = fileInfo.uncompressed_size;
        }
        unzCloseCurrentFile(m_zipFile);
    } while (0);
    
    return pBuffer;

}
Exemplo n.º 17
0
int XSYNCZIP_getEntryDataByName ( XDRM_CTRL_CONTEXT_PTR pCtx,  char *name, char *buffer )
{
   int retval =0;

#if 0
   // before info
   unz_file_info64 cur_file_infoSaved;
   unz_file_info64_internal cur_file_info_internalSaved;
   ZPOS64_T num_fileSaved;
   ZPOS64_T pos_in_central_dirSaved;

   /* Save the current state */
   num_fileSaved = s->num_file;
   pos_in_central_dirSaved = s->pos_in_central_dir;
   cur_file_infoSaved = s->cur_file_info;
   cur_file_info_internalSaved = s->cur_file_info_internal;
#endif

   if ( unzLocateFile ( pCtx->pZipFile,name,0/*CASESENSITIVITY*/ ) !=UNZ_OK ) {
      retval= -1;
   } else {
      retval = unzOpenCurrentFile ( pCtx->pZipFile );
      if ( retval == UNZ_OK ) {
#if 0
         retval =unzReadCurrentFile ( pCtx->pZipFile, buffer, ( unsigned int ) pCtx->pZipFile->cur_file_info.uncompressed_size );
#else
         retval =unzReadEntry ( pCtx->pZipFile, buffer, 0, ( unsigned int ) pCtx->pZipFile->cur_file_info.uncompressed_size, Z_FINISH );
#endif
      } else {
         retval =-1;
      }
   }

   unzCloseCurrentFile ( pCtx->pZipFile );
   return retval;

}
Exemplo n.º 18
0
gboolean
managed_unzip_stream_to_stream (ManagedStreamCallbacks *source, ManagedStreamCallbacks *dest, const char *partname)
{
	zlib_filefunc_def funcs;
	unzFile zipFile;
	gboolean ret;

	ret = FALSE;

	funcs.zopen_file = managed_stream_open;
	funcs.zread_file = managed_stream_read;
	funcs.zwrite_file = managed_stream_write;
	funcs.ztell_file = managed_stream_tell;
	funcs.zseek_file = managed_stream_seek;
	funcs.zclose_file = managed_stream_close;
	funcs.zerror_file = managed_stream_error;
	funcs.opaque = source;

	zipFile = unzOpen2 (NULL, &funcs);

	if (!zipFile)
		return FALSE;

	if (unzLocateFile (zipFile, partname, 2) != UNZ_OK)
		goto cleanup;	

	if (unzOpenCurrentFile (zipFile) != UNZ_OK)
		goto cleanup;

	ret = managed_unzip_extract_to_stream (zipFile, dest);

cleanup:
	unzCloseCurrentFile (zipFile);
	unzClose (zipFile);

	return ret;
}
Exemplo n.º 19
0
	char* Zip::getFileData(const char* filename, unsigned long& size)
	{
		char * pBuffer = NULL;

		auto it = _files.find(filename);

		if (it == _files.end()) return NULL;

		ZipEntryInfo fileInfo = it->second;

		int nRet = unzGoToFilePos(_zipFile, &fileInfo.pos);
		if (UNZ_OK != nRet) return NULL;

		nRet = unzOpenCurrentFile(_zipFile);
		if (UNZ_OK != nRet) return NULL;

		pBuffer = new char[fileInfo.uncompressed_size];
		unzReadCurrentFile(_zipFile, pBuffer, fileInfo.uncompressed_size);

		size = fileInfo.uncompressed_size;
		unzCloseCurrentFile(_zipFile);

		return pBuffer;
	}
Exemplo n.º 20
0
enum ApkResult
apk_uncompress_internal(AndroidApk *apk, char **buffer, size_t *size)
{
    zlib_filefunc_def filefunc;
    fill_memory_filefunc(&filefunc);
    char *old_buffer = *buffer;
    char path[1024];
    sprintf(path, "%x+%x", *buffer, *size);

    /* Decompress a single file in a .zip from memory */
    unz_file_info info;
    unzFile *unz = unzOpen2(path, &filefunc);
    unzGoToFirstFile(unz);
    unzGetCurrentFileInfo(unz, &info, NULL, 0, NULL, 0, NULL, 0);
    *size = info.uncompressed_size;
    *buffer = malloc(*size);
    unzOpenCurrentFile(unz);
    unzReadCurrentFile(unz, *buffer, *size);
    unzCloseCurrentFile(unz);
    unzClose(unz);
    free(old_buffer);

    return APK_OK;
}
Exemplo n.º 21
0
bool eFileTypeZIP::OpenCurrent(unzFile h, char* name) const
{
	unz_file_info fi;
	char n[xIo::MAX_PATH_LEN];
	if(unzGetCurrentFileInfo(h, &fi, n, xIo::MAX_PATH_LEN, NULL, 0, NULL, 0) != UNZ_OK)
		return false;
	const eFileType* t = eFileType::FindByName(n);
	if(!t)
		return false;
	if(unzOpenCurrentFile(h) != UNZ_OK)
		return false;

	bool ok = false;
	byte* buf = new byte[fi.uncompressed_size];
	if(unzReadCurrentFile(h, buf, fi.uncompressed_size) == int(fi.uncompressed_size))
	{
		ok = t->Open(buf, fi.uncompressed_size);
		if(ok && name)
			strcpy(name, n);
	}
	SAFE_DELETE_ARRAY(buf);
	unzCloseCurrentFile(h);
	return ok;
}
Exemplo n.º 22
0
int PackFileGetFileWithIndex (packfile_t *pf, int idx , char **buf)
{
	DWORD	err;
	
	if (idx >= (int)pf->gi.number_entry)
		return ERROR_FILE_NOT_EXIST;
	
	*buf = (char *)malloc (pf->fi[idx].size);

	unzLocateFileMy (pf->uf, idx, pf->fi[idx].c_offset);

	unzOpenCurrentFile (pf->uf);
	err = unzReadCurrentFile (pf->uf,*buf,pf->fi[idx].size);
	unzCloseCurrentFile (pf->uf);

	if (err!=pf->fi[idx].size)
	{
		free (*buf);
		*buf = NULL;
		return ERROR_FILE_NOT_EXTRACTED;
	}

	return pf->fi[idx].size;
}
Exemplo n.º 23
0
static void	unz_extract(void **ptr, size_t *size, const char *filename)
{
	unz_file_info info;
	char *data, *data_end;
	int got;

	if (!unz_exists(filename))
		FATAL("Failed to locate packaged file: %s", filename);

	if (unzOpenCurrentFile(foundzip) != UNZ_OK)
		FATAL("Failed to unpack %s", filename);

	unzGetCurrentFileInfo(foundzip, &info, NULL, 0, NULL, 0, NULL, 0);
	data = (char*)malloc(info.uncompressed_size+1);
	*ptr = data;
	*size = info.uncompressed_size;
	data_end = data + info.uncompressed_size;
	*data_end = 0;

	while ((got = unzReadCurrentFile(foundzip, data, data_end - data)) > 0) {
		data = data + got;	
	}
	unzCloseCurrentFile(foundzip);
}
Exemplo n.º 24
0
bool zip::ZipArchiveInput::ReadCurrentFile( String_t const& fileName, Byte_t*& pMemoryBlock, size_t& size )
{
	int err = UNZ_OK;

#ifdef SCARAB_WCHAR_MODE
	std::string filename_inzip = utf_convert::as_utf8( fileName );
#else
	std::string filename_inzip = fileName;
#endif

	unz_file_info64 file_info;
	uLong ratio=0;
	err = unzGetCurrentFileInfo64(uf,&file_info,(char*)filename_inzip.c_str(),filename_inzip.size()+1,NULL,0,NULL,0);
	if ( err != UNZ_OK )
	{
		m_errorMessage << "unzGetCurrentFileInfo error in file " << fileName << " error code: " << err << std::endl;
		return false;
	}

	size_t size_buf = (size_t)file_info.uncompressed_size;
	void* buf = malloc(size_buf);
	if (buf == NULL)
	{
		m_errorMessage << "Error allocating memory for file " << fileName << " requested: " << size_buf << std::endl;
		return false;
	}

	err = unzOpenCurrentFilePassword(uf,password);
	if (err != UNZ_OK)
	{
		m_errorMessage << "unzOpenCurrentFilePassword error in file " << fileName << " error code: " << err << std::endl;
		return false;
	}

	int numRead = unzReadCurrentFile(uf,buf,size_buf);
	if( numRead < 0 )
	{
		m_errorMessage << "unzReadCurrentFile error in file " << fileName << " error code: " << err << std::endl;
		err = numRead;
	}
	else
		err = UNZ_OK;

	if (err==UNZ_OK)
	{
		err = unzCloseCurrentFile (uf);
		if (err!=UNZ_OK)
			m_errorMessage << "unzCloseCurrentFile error in file " << fileName << " error code: " << err << std::endl;
	}
	else
		unzCloseCurrentFile(uf); /* don't lose the error */

	if( err != UNZ_OK )
	{
		free(buf);
		return false;
	}

	pMemoryBlock = (Byte_t*)buf;
	size = size_buf;
	return true;
}
Exemplo n.º 25
0
void ExportTemplateManager::_install_from_file(const String &p_file, bool p_use_progress) {

	FileAccess *fa = NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&fa);

	unzFile pkg = unzOpen2(p_file.utf8().get_data(), &io);
	if (!pkg) {

		EditorNode::get_singleton()->show_warning(TTR("Can't open export templates zip."));
		return;
	}
	int ret = unzGoToFirstFile(pkg);

	int fc = 0; //count them and find version
	String version;

	while (ret == UNZ_OK) {

		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);

		String file = fname;

		if (file.ends_with("version.txt")) {

			Vector<uint8_t> data;
			data.resize(info.uncompressed_size);

			//read
			unzOpenCurrentFile(pkg);
			ret = unzReadCurrentFile(pkg, data.ptrw(), data.size());
			unzCloseCurrentFile(pkg);

			String data_str;
			data_str.parse_utf8((const char *)data.ptr(), data.size());
			data_str = data_str.strip_edges();

			// Version number should be of the form major.minor[.patch].status[.module_config]
			// so it can in theory have 3 or more slices.
			if (data_str.get_slice_count(".") < 3) {
				EditorNode::get_singleton()->show_warning(vformat(TTR("Invalid version.txt format inside templates: %s."), data_str));
				unzClose(pkg);
				return;
			}

			version = data_str;
		}

		if (file.get_file().size() != 0) {
			fc++;
		}

		ret = unzGoToNextFile(pkg);
	}

	if (version == String()) {
		EditorNode::get_singleton()->show_warning(TTR("No version.txt found inside templates."));
		unzClose(pkg);
		return;
	}

	String template_path = EditorSettings::get_singleton()->get_templates_dir().plus_file(version);

	DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	Error err = d->make_dir_recursive(template_path);
	if (err != OK) {
		EditorNode::get_singleton()->show_warning(TTR("Error creating path for templates:") + "\n" + template_path);
		unzClose(pkg);
		return;
	}

	memdelete(d);

	ret = unzGoToFirstFile(pkg);

	EditorProgress *p = NULL;
	if (p_use_progress) {
		p = memnew(EditorProgress("ltask", TTR("Extracting Export Templates"), fc));
	}

	fc = 0;

	while (ret == UNZ_OK) {

		//get filename
		unz_file_info info;
		char fname[16384];
		unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);

		String file = String(fname).get_file();

		if (file.size() == 0) {
			ret = unzGoToNextFile(pkg);
			continue;
		}

		Vector<uint8_t> data;
		data.resize(info.uncompressed_size);

		//read
		unzOpenCurrentFile(pkg);
		unzReadCurrentFile(pkg, data.ptrw(), data.size());
		unzCloseCurrentFile(pkg);

		if (p) {
			p->step(TTR("Importing:") + " " + file, fc);
		}

		FileAccess *f = FileAccess::open(template_path.plus_file(file), FileAccess::WRITE);

		if (!f) {
			ret = unzGoToNextFile(pkg);
			fc++;
			ERR_CONTINUE(!f);
		}

		f->store_buffer(data.ptr(), data.size());

		memdelete(f);

		ret = unzGoToNextFile(pkg);
		fc++;
	}

	if (p) {
		memdelete(p);
	}

	unzClose(pkg);

	_update_template_list();
}
Exemplo n.º 26
0
// NOTE: when loading a file, you have to allocate one extra byte and set it to \0
int vfsLoadFile (const char *filename, void **bufferptr, int index)
{
  int i, count = 0;
  char tmp[NAME_MAX], fixed[NAME_MAX];
  GSList *lst;
  
  // filename is a full path
  if (index == -1)
  {
    long len;
    FILE *f;
    
    f = fopen (filename, "rb");
    if (f == NULL)
      return -1;
    
    fseek (f, 0, SEEK_END);
    len = ftell (f);
    rewind (f);
    
    *bufferptr = safe_malloc (len+1);
    if (*bufferptr == NULL)
      return -1;
    
    fread (*bufferptr, 1, len, f);
    fclose (f);
    
    // we need to end the buffer with a 0
    ((char*) (*bufferptr))[len] = 0;
    
    return len;
  }
  
  *bufferptr = NULL;
  strcpy (fixed, filename);
  vfsFixDOSName (fixed);
  g_strdown (fixed);
  
  for (i = 0; i < g_numDirs; i++)
  {
    strcpy (tmp, g_strDirs[i]);
    strcat (tmp, filename);
    if (access (tmp, R_OK) == 0)
    {
      if (count == index)
      {
        long len;
        FILE *f;
        
        f = fopen (tmp, "rb");
        if (f == NULL)
          return -1;
        
        fseek (f, 0, SEEK_END);
        len = ftell (f);
        rewind (f);
        
        *bufferptr = safe_malloc (len+1);
        if (*bufferptr == NULL)
          return -1;
        
        fread (*bufferptr, 1, len, f);
        fclose (f);
        
        // we need to end the buffer with a 0
        ((char*) (*bufferptr))[len] = 0;
        
        return len;
      }
      
      count++;
    }
  }
  
  for (lst = g_pakFiles; lst != NULL; lst = g_slist_next (lst))
  {
    VFS_PAKFILE* file = (VFS_PAKFILE*)lst->data;
    
    if (strcmp (file->name, fixed) != 0)
      continue;
    
    if (count == index)
    {
      memcpy (file->zipfile, &file->zipinfo, sizeof (unz_s));
      
      if (unzOpenCurrentFile (file->zipfile) != UNZ_OK)
        return -1;
      
      *bufferptr = safe_malloc (file->size+1);
      // we need to end the buffer with a 0
      ((char*) (*bufferptr))[file->size] = 0;
      
      i = unzReadCurrentFile (file->zipfile , *bufferptr, file->size);
      unzCloseCurrentFile (file->zipfile);
      if (i < 0)
        return -1;
      else
        return file->size;
    }
    
    count++;
  }
  
  return -1;
}
Exemplo n.º 27
0
int zipExtractCurrentfile(unzFile uf, int overwrite, const char* password)
{
    char filename_inzip[256];
    char* filename_withoutpath;
    char* p;
    int err=UNZ_OK;
    FILE *fout=NULL;
    void* buf;
    uInt size_buf;

    unz_file_info file_info;
    err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);

    if( err != UNZ_OK ) {
        printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
        return 0;
    }

    size_buf = WRITEBUFFERSIZE;
    buf = (void*)malloc(size_buf);

    p = filename_withoutpath = filename_inzip;
    while ((*p) != '\0') {
        if (((*p)=='/') || ((*p)=='\\'))
            filename_withoutpath = p+1;
        p++;
    }

    if ((*filename_withoutpath)=='\0') {
        MKDIR(filename_inzip);
    }else{
        const char* write_filename;
        int skip=0;

        write_filename = filename_inzip;

        err = unzOpenCurrentFilePassword(uf,password);
        if (err!=UNZ_OK) {
            printf("error %d with zipfile in unzOpenCurrentFilePassword\n",err);
        }

        if ((overwrite==0) && (err==UNZ_OK)) {
            FILE* ftestexist = fopen(write_filename,"rb");
            if (ftestexist!=NULL) {
                fclose(ftestexist);
                skip = 1;
            }
        }

        if ((skip==0) && (err==UNZ_OK)) {
            fout=fopen(write_filename,"wb");

            /* some zipfile don't contain directory alone before file */
            if( (fout==NULL) && (filename_withoutpath!=(char*)filename_inzip) ) {
                char c=*(filename_withoutpath-1);
                *(filename_withoutpath-1)='\0';
                makedir(write_filename);
                *(filename_withoutpath-1)=c;
                fout=fopen(write_filename,"wb");
            }

            if( fout == NULL ) {
                printf("error opening %s\n",write_filename);
            }
        }

        if (fout!=NULL)
        {
            printf(" extracting: %s\n",write_filename);
            do {
                err = unzReadCurrentFile(uf,buf,size_buf);
                if( err < 0 ) {
                    printf("error %d with zipfile in unzReadCurrentFile\n",err);
                    break;
                }
                if( err > 0 ) {
                    if (fwrite(buf,err,1,fout)!=1) {
                        printf("error in writing extracted file\n");
                        err=UNZ_ERRNO;
                        break;
                    }
                }
            }while( err > 0 );
            if( fout ) fclose(fout);
        }

        if(err == UNZ_OK) {
            err = unzCloseCurrentFile (uf);
            if( err != UNZ_OK ) {
                printf("error %d with zipfile in unzCloseCurrentFile\n",err);
            }
        }else{
            unzCloseCurrentFile(uf); /* don't lose the error */
        }
    }

    free(buf);
    return 1;
}
Exemplo n.º 28
0
/******************************************************************************
*** Description
***     Load a file in a zip file into memory.
***
*** Arguments
***     zipName     - Name of zip file
***     fileName    - Name of file insize zipfile to load
***     size        - Output of size of file
***
*** Return
***     Pointer to allocate memory buffer with file content or NULL on
***     failure.
***
*******************************************************************************
*/
void* _zipLoadFile(const char* zipName, const char* fileName, int* size, zlib_filefunc_def* filefunc)
{
    void* buf;
    char name[256];
    unzFile zip;
    unz_file_info info;

    *size = 0;

    if (fileName[0] == '*') {
        strcpy(name, zipName);
        name[strlen(zipName) - 3] = fileName[strlen(fileName) - 3];
        name[strlen(zipName) - 2] = fileName[strlen(fileName) - 2];
        name[strlen(zipName) - 1] = fileName[strlen(fileName) - 1];
    }
    else {
        strcpy(name, fileName);
    }

    zip = unzOpen2(zipName, filefunc);
    if (!zip) {
        return NULL;
    }

#ifdef __APPLE__
    // Most OS X installs are on a case-insensitive FS
    if (unzLocateFile(zip, name, 2) == UNZ_END_OF_LIST_OF_FILE) {
#else
    if (unzLocateFile(zip, name, 1) == UNZ_END_OF_LIST_OF_FILE) {
#endif
        unzClose(zip);
        return NULL;
    }

    if (unzOpenCurrentFile(zip) != UNZ_OK) {
        return NULL;
    }

    unzGetCurrentFileInfo(zip,&info,NULL,0,NULL,0,NULL,0);

    buf = malloc(info.uncompressed_size);
    *size = info.uncompressed_size;

    if (!buf) {
        unzCloseCurrentFile(zip);
        unzClose(zip);
        return NULL;
    }

    unzReadCurrentFile(zip, buf, info.uncompressed_size);
    unzCloseCurrentFile(zip);
    unzClose(zip);

    return buf;
}


/******************************************************************************
*** Description
***     Read cache to speed-up reading multiple files from one zip.
***
******************************************************************************/

static char *cacheData = NULL, cacheFile[512];
static zlib_filefunc_def cacheFilefunc;

void* zipLoadFile(const char* zipName, const char* fileName, int* size)
{
    if (strncmp(zipName, "mem", 3) == 0) {
        return memFileLoad(zipName, fileName, size);
    }
    if( cacheData != NULL && *cacheFile != '\0' && 0==strcmp(cacheFile, zipName) ) {
        return _zipLoadFile(cacheData, fileName, size, &cacheFilefunc);
    }else{
        return _zipLoadFile(zipName, fileName, size, NULL);
    }
}

void zipCacheReadOnlyZip(const char* zipName)
{
    if (zipName != NULL && strncmp(zipName, "mem", 3) == 0) {
        return;
    }

    *cacheFile = '\0';
    if( cacheData != NULL ) {
        free(cacheData);
        cacheData = NULL;
        free_fopen_memfunc(&cacheFilefunc);
    }
    if( zipName != NULL ) {
        FILE *file;
        file = fopen(zipName, "rb");
        if( file != NULL ) {
            unsigned int filesize;
            fseek(file, 0, SEEK_END);
            filesize = ftell(file);
            fill_fopen_memfunc(&cacheFilefunc, filesize);
            fseek(file, 0, SEEK_SET);
            cacheData = malloc(filesize);
            if( cacheData != NULL ) {
                size_t size = fread(cacheData, 1, filesize, file);
                if( size == filesize ) {
                    strcpy(cacheFile, zipName);
                }
            }
            fclose(file);
        }
    }
}


/******************************************************************************
*** Description
***     Load a file in a zip file into memory.
***
*** Arguments
***     zipName     - Name of zip file
***     fileName    - Name of file insize zipfile to save
***     buffer      - Buffer to save
***     size        - Size of buffer to save
***
*******************************************************************************
*/
int zipSaveFile(const char* zipName, const char* fileName, int append, void* buffer, int size)
{
    zipFile zip;
    zip_fileinfo zi;
    int err;

    if (strncmp(zipName, "mem", 3) == 0) {
        return memFileSave(zipName, fileName, append, buffer, size);
    }

    zip = zipOpen(zipName, append ? 2 : 0);
    if (zip == NULL) {
        return 0;
    }

    memset(&zi, 0, sizeof(zi));

    err = zipOpenNewFileInZip(zip, fileName, &zi,
                              NULL, 0, NULL, 0, NULL,
                              Z_DEFLATED, Z_DEFAULT_COMPRESSION);
    if (err == ZIP_OK) {
        err = zipWriteInFileInZip(zip, buffer, size);
    }

    zipClose(zip, NULL);

    return err >= 0;
}
Exemplo n.º 29
0
int UnCompressZip::unzOpenCurrentFile3 (unzFile file, int* method, int* level, int raw, const char* password)
{
  int err=UNZ_OK;
  uInt iSizeVar;
  unz64_s* s;
  file_in_zip64_read_info_s* pfile_in_zip_read_info;
  ZPOS64_T offset_local_extrafield;  /* offset of the local extra field */
  uInt  size_local_extrafield;    /* size of the local extra field */

  if (file==NULL)
    return UNZ_PARAMERROR;
  s=(unz64_s*)file;
  if (!s->current_file_ok)
    return UNZ_PARAMERROR;

  if (s->pfile_in_zip_read != NULL)
    unzCloseCurrentFile(file);

  if (unz64local_CheckCurrentFileCoherencyHeader(s,&iSizeVar, &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK)
    return UNZ_BADZIPFILE;

  pfile_in_zip_read_info = (file_in_zip64_read_info_s*)ALLOC(sizeof(file_in_zip64_read_info_s));
  if (pfile_in_zip_read_info==NULL)
    return UNZ_INTERNALERROR;

  pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE);
  pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield;
  pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield;
  pfile_in_zip_read_info->pos_local_extrafield=0;
  pfile_in_zip_read_info->raw=raw;

  if (pfile_in_zip_read_info->read_buffer==NULL)
  {
    TRYFREE(pfile_in_zip_read_info);
    return UNZ_INTERNALERROR;
  }

  pfile_in_zip_read_info->stream_initialised=0;

  if (method!=NULL)
    *method = (int)s->cur_file_info.compression_method;

  if (level!=NULL)
  {
    *level = 6;
    switch (s->cur_file_info.flag & 0x06)
    {
      case 6 : *level = 1; break;
      case 4 : *level = 2; break;
      case 2 : *level = 9; break;
    }
   }

  if ((s->cur_file_info.compression_method!=0) &&

      (s->cur_file_info.compression_method!=Z_BZIP2ED) &&

      (s->cur_file_info.compression_method!=Z_DEFLATED))

      err=UNZ_BADZIPFILE;

  pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc;
  pfile_in_zip_read_info->crc32=0;
  pfile_in_zip_read_info->total_out_64=0;
  pfile_in_zip_read_info->compression_method = s->cur_file_info.compression_method;
  pfile_in_zip_read_info->filestream=s->filestream;
  pfile_in_zip_read_info->z_filefunc=s->z_filefunc;
  pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile;

  pfile_in_zip_read_info->stream.total_out = 0;

  if ((s->cur_file_info.compression_method==Z_BZIP2ED) && (!raw))
    pfile_in_zip_read_info->raw=1;
  else if ((s->cur_file_info.compression_method==Z_DEFLATED) && (!raw))
  {
    pfile_in_zip_read_info->stream.zalloc = (alloc_func)0;
    pfile_in_zip_read_info->stream.zfree = (free_func)0;
    pfile_in_zip_read_info->stream.opaque = (voidpf)0;
    pfile_in_zip_read_info->stream.next_in = 0;
    pfile_in_zip_read_info->stream.avail_in = 0;

    err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS);
    if (err == Z_OK)
      pfile_in_zip_read_info->stream_initialised=Z_DEFLATED;
    else
    {
      TRYFREE(pfile_in_zip_read_info);
      return err;
    }
  }
  pfile_in_zip_read_info->rest_read_compressed = s->cur_file_info.compressed_size ;
  pfile_in_zip_read_info->rest_read_uncompressed = s->cur_file_info.uncompressed_size ;

  pfile_in_zip_read_info->pos_in_zipfile = s->cur_file_info_internal.offset_curfile + 
    SIZEZIPLOCALHEADER + iSizeVar;

  pfile_in_zip_read_info->stream.avail_in = (uInt)0;

  s->pfile_in_zip_read = pfile_in_zip_read_info;
  s->encrypted = 0;
  
  return UNZ_OK;

}
Exemplo n.º 30
0
bool ThemeLoader::extractFileInZip( unzFile file, const string &rootDir,
                                    bool isWsz )
{
    // Read info for the current file
    char filenameInZip[256];
    unz_file_info fileInfo;
    if( unzGetCurrentFileInfo( file, &fileInfo, filenameInZip,
                               sizeof( filenameInZip), NULL, 0, NULL, 0 )
        != UNZ_OK )
    {
        return false;
    }

    // Convert the file name to lower case, because some winamp skins
    // use the wrong case...
    if( isWsz )
        for( size_t i = 0; i < strlen( filenameInZip ); i++ )
            filenameInZip[i] = tolower( filenameInZip[i] );

    // Allocate the buffer
    void *pBuffer = malloc( ZIP_BUFFER_SIZE );
    if( !pBuffer )
        return false;

    // Get the path of the file
    OSFactory *pOsFactory = OSFactory::instance( getIntf() );
    string fullPath = rootDir
        + pOsFactory->getDirSeparator()
        + fixDirSeparators( filenameInZip );
    string basePath = getFilePath( fullPath );

    // Extract the file if is not a directory
    if( basePath != fullPath )
    {
        if( unzOpenCurrentFile( file ) )
        {
            free( pBuffer );
            return false;
        }
        makedir( basePath.c_str() );
        FILE *fout = fopen( fullPath.c_str(), "wb" );
        if( fout == NULL )
        {
            msg_Err( getIntf(), "error opening %s", fullPath.c_str() );
            free( pBuffer );
            return false;
        }

        // Extract the current file
        int n;
        do
        {
            n = unzReadCurrentFile( file, pBuffer, ZIP_BUFFER_SIZE );
            if( n < 0 )
            {
                msg_Err( getIntf(), "error while reading zip file" );
                free( pBuffer );
                return false;
            }
            else if( n > 0 )
            {
                if( fwrite( pBuffer, n , 1, fout) != 1 )
                {
                    msg_Err( getIntf(), "error while writing %s",
                             fullPath.c_str() );
                    free( pBuffer );
                    return false;
                }
            }
        } while( n > 0 );

        fclose(fout);

        if( unzCloseCurrentFile( file ) != UNZ_OK )
        {
            free( pBuffer );
            return false;
        }
    }

    free( pBuffer );
    return true;
}