Example #1
0
    //-----------------------------------------------------------------------
    DataStreamPtr ZipArchive::open(const String& filename, bool readOnly) const
    {
        // zziplib is not threadsafe
        OGRE_LOCK_AUTO_MUTEX;
        String lookUpFileName = filename;

#if OGRE_RESOURCEMANAGER_STRICT
        const int flags = 0;
#else
        const int flags = ZZIP_CASELESS;
#endif

        // Format not used here (always binary)
        ZZIP_FILE* zzipFile =
            zzip_file_open(mZzipDir, lookUpFileName.c_str(), ZZIP_ONLYZIP | flags);

#if !OGRE_RESOURCEMANAGER_STRICT
        if (!zzipFile) // Try if we find the file
        {
            String basename, path;
            StringUtil::splitFilename(lookUpFileName, basename, path);
            const FileInfoListPtr fileNfo = findFileInfo(basename, true);
            if (fileNfo->size() == 1) // If there are more files with the same do not open anyone
            {
                Ogre::FileInfo info = fileNfo->at(0);
                lookUpFileName = info.path + info.basename;
                zzipFile = zzip_file_open(mZzipDir, lookUpFileName.c_str(), ZZIP_ONLYZIP | flags); // When an error happens here we will catch it below
            }
        }
#endif

        if (!zzipFile)
        {
            int zerr = zzip_error(mZzipDir);
            String zzDesc = getZzipErrorDescription((zzip_error_t)zerr);

            OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND,
                    mName+ " Cannot open file: " + lookUpFileName + " - "+zzDesc, "ZipArchive::open");
        }

        // Get uncompressed size too
        ZZIP_STAT zstat;
        zzip_dir_stat(mZzipDir, lookUpFileName.c_str(), &zstat, flags);

        // Construct & return stream
        return DataStreamPtr(OGRE_NEW ZipDataStream(lookUpFileName, zzipFile, static_cast<size_t>(zstat.st_size)));

    }
Example #2
0
size_t getEntry(const char *name, char *contentFile, char **ptr) {

  size_t size=0;
  ZZIP_DIR *dir;
  ZZIP_DIRENT entry;
  ZZIP_FILE *file;
  char *buf;

  dir = zzip_dir_open(name, 0);
  if (!dir) {
    fprintf(stderr, "failed to open %s\n", name);
    return 0;
  }

  zzip_dir_read(dir, &entry);

  file = zzip_file_open(dir, contentFile, 0);

  (void)zzip_seek(file, 0, SEEK_END);
  size = zzip_tell(file);
  (void)zzip_seek(file, 0, SEEK_SET);
  buf = (char *)malloc(size+1);
  (void)zzip_read(file, buf, size);
  buf[size] = '\0';
  *ptr = buf;

  zzip_file_close(file);
  zzip_dir_close(dir);

  return size;
}
Example #3
0
File: utils.c Project: azuwis/cview
static void extract_zip_file_into_loader(GdkPixbufLoader * loader,
        const char *archname,
        const char *archpath)
{
    if (loader == NULL)
        return;
    ZZIP_DIR *dir = zzip_dir_open(archname, 0);
    ZZIP_FILE *fp = zzip_file_open(dir, archpath, 0);
    if (fp) {
        guchar buf[ZIPBUFSIZE];
        GError *error = NULL;
        zzip_ssize_t len;
        while ((len = zzip_file_read(fp, buf, ZIPBUFSIZE))) {
            gdk_pixbuf_loader_write(loader, buf, len, &error);
            if (error != NULL) {
                g_warning("load image in zip failed: %s\n",
                          error->message);
                g_error_free(error);
                zzip_dir_close(dir);
                return;
            }
        }
        zzip_file_close(fp);
    }
    zzip_dir_close(dir);
}
Example #4
0
    //-----------------------------------------------------------------------
	DataStreamPtr ZipArchive::open(const String& filename) const
    {

        // Format not used here (always binary)
        ZZIP_FILE* zzipFile = 
            zzip_file_open(mZzipDir, filename.c_str(), ZZIP_ONLYZIP | ZZIP_CASELESS);
        if (!zzipFile)
		{
            int zerr = zzip_error(mZzipDir);
            String zzDesc = getZzipErrorDescription((zzip_error_t)zerr);
            LogManager::getSingleton().logMessage(
                mName + " - Unable to open file " + filename + ", error was '" + zzDesc + "'");
                
			// return null pointer
			return DataStreamPtr();
		}

		// Get uncompressed size too
		ZZIP_STAT zstat;
		zzip_dir_stat(mZzipDir, filename.c_str(), &zstat, ZZIP_CASEINSENSITIVE);

        // Construct & return stream
        return DataStreamPtr(new ZipDataStream(filename, zzipFile, static_cast<size_t>(zstat.st_size)));

    }
Example #5
0
void checkFile(ZZIP_DIR* dir, ZZIP_DIRENT* dirent, const char* filename)
{
    if (strcmp(filename, dirent->d_name) != 0) return;

    int flags = 0;
    ZZIP_FILE* f1 = zzip_file_open(dir, dirent->d_name, flags);
    if (f1 == NULL) {
        fprintf(stderr, "zzip_file_open failed: %s\n", zzip_strerror_of(dir));
        return;
    }

    // read file
    char buf[4097];
    int total = dirent->st_size;
    int bytes = 0;
    printf("---------------------\n");
    while (bytes != total) {
        zzip_ssize_t size = zzip_file_read(f1, buf, 4096);
        bytes += size;
        buf[size] = 0;
        printf("%s", buf);
        //printf("read %4d  %6d/%d\n", size, bytes, total);
    }
    printf("\n---------------------\n");

    int err = zzip_file_close(f1);
    if (err != 0) {
        fprintf(stderr, "zzip_file_close failed: %s\n", zzip_strerror_of(dir));
        return;
    }
}
Example #6
0
    //-----------------------------------------------------------------------
    DataStreamPtr ZipArchive::open(const String& filename, bool readOnly)
    {
        // zziplib is not threadsafe
        OGRE_LOCK_AUTO_MUTEX;
        String lookUpFileName = filename;

        // Format not used here (always binary)
        ZZIP_FILE* zzipFile = 
            zzip_file_open(mZzipDir, lookUpFileName.c_str(), ZZIP_ONLYZIP | ZZIP_CASELESS);
        if (!zzipFile) // Try if we find the file
        {
            const Ogre::FileInfoListPtr fileNfo = findFileInfo(lookUpFileName, true);
            if (fileNfo->size() == 1) // If there are more files with the same do not open anyone
            {
                Ogre::FileInfo info = fileNfo->at(0);
                lookUpFileName = info.path + info.basename;
                zzipFile = zzip_file_open(mZzipDir, lookUpFileName.c_str(), ZZIP_ONLYZIP | ZZIP_CASELESS); // When an error happens here we will catch it below
            }
        }

        if (!zzipFile)
        {
            int zerr = zzip_error(mZzipDir);
            String zzDesc = getZzipErrorDescription((zzip_error_t)zerr);
            LogManager::getSingleton().logMessage(
                mName + " - Unable to open file " + lookUpFileName + ", error was '" + zzDesc + "'", LML_CRITICAL);
                
            // return null pointer
            return DataStreamPtr();
        }

        // Get uncompressed size too
        ZZIP_STAT zstat;
        zzip_dir_stat(mZzipDir, lookUpFileName.c_str(), &zstat, ZZIP_CASEINSENSITIVE);

        // Construct & return stream
        return DataStreamPtr(OGRE_NEW ZipDataStream(lookUpFileName, zzipFile, static_cast<size_t>(zstat.st_size)));

    }
Example #7
0
File: luazip.c Project: msva/luazip
static int f_open (lua_State *L) {
  ZZIP_DIR* uf = tofile(L, 1);
  const char *filename = luaL_checkstring(L, 2);
  /*const char *mode = luaL_optstring(L, 3, "r");*/
  ZZIP_FILE** inf = newinternalfile(L);

  *inf = zzip_file_open(uf, filename, 0);
  if (*inf)
    return 1;

  lua_pushnil(L);
  lua_pushfstring(L, "could not open file `%s'", filename);
  return 2;
}
std::future<void*> ResourceManager::LoadSound(const char* filepath, void* _fSystem)
{
#ifdef _CACH_PARSED_DATA_
	for (std::map<const char*, SoundData*>::iterator it = mSoundResource.begin(); it != mSoundResource.end(); it++)
	{
		if (it->first == filepath)
			return mThreadPool.AddTask<LoadSoundTask>(it->second->buffer, it->second->bufferSize, &mGlLock, _fSystem);
	}
#endif

	unsigned int bufferSize;
	unsigned char* buffer;

	switch (mAssetPacketExtension)
	{
	case PACA:
		bufferSize = mPacaReader.GetResourceSize(filepath);
		buffer = new unsigned char[bufferSize];
		if (mPacaReader.GetResource(filepath, buffer, bufferSize))
		{
#ifdef _CACH_PARSED_DATA_
			SoundData* sd = new SoundData();
			sd->buffer = buffer;
			sd->bufferSize = bufferSize;
			mSoundResource.insert(std::pair<const char*, SoundData*>(filepath, sd));
#endif
			return mThreadPool.AddTask<LoadSoundTask>(buffer, bufferSize, &mGlLock, _fSystem);
		}
		break;

	case ZIP:
		ZZIP_FILE* fp = zzip_file_open(mDir, filepath, 0);
		zzip_seek(fp, 0, SEEK_END);
		bufferSize = zzip_tell(fp);
		zzip_rewind(fp);

		buffer = new unsigned char[bufferSize];
		bufferSize = zzip_file_read(fp, buffer, static_cast<int>(bufferSize));

		zzip_file_close(fp);

#ifdef _CACH_PARSED_DATA_
		SoundData* sd = new SoundData();
		sd->buffer = buffer;
		sd->bufferSize = bufferSize;
		mSoundResource.insert(std::pair<const char*, SoundData*>(filepath, sd));
#endif
		return mThreadPool.AddTask<LoadSoundTask>(buffer, bufferSize, &mGlLock, _fSystem);
	}
}
Example #9
0
static void unzzip_cat_file(ZZIP_DIR* disk, char* name, FILE* out)
{
    ZZIP_FILE* file = zzip_file_open (disk, name, 0);
    if (file) 
    {
	char buffer[1024]; int len;
	while ((len = zzip_file_read (file, buffer, 1024))) 
	{
	    fwrite (buffer, 1, len, out);
	}
	
	zzip_file_close (file);
    }
}
TextureResource* ResourceManager::LoadTexture( const char* file)
{	
#ifdef _CACH_PARSED_DATA_
	for (std::map<const char*, TextureResource*>::iterator it = mTextureResource.begin(); it != mTextureResource.end(); it++)
	{
		if (it->first == file)
			return it->second;
	}
#endif

	unsigned int bufferSize;
	unsigned char* buffer;

	switch ( mAssetPacketExtension )
	{
		case PACA:
			bufferSize	= mPacaReader.GetResourceSize(file);
			buffer		= new unsigned char[bufferSize];
			if ( mPacaReader.GetResource(file, buffer, bufferSize ) )
			{
				TextureResource* textureResource = new TextureResource();
				textureResource->future = mThreadPool.AddTask<LoadTextureTask>(buffer, bufferSize, &mGlLock);
#ifdef _CACH_PARSED_DATA_
				mTextureResource.insert(std::pair<const char*, TextureResource*>(file, textureResource));
#endif
				return textureResource;
			}
			break;

		case ZIP:
			ZZIP_FILE* fp = zzip_file_open( mDir, file, 0 );
			zzip_seek( fp, 0, SEEK_END );
			bufferSize = zzip_tell( fp );
			zzip_rewind( fp );

			buffer = new unsigned char[bufferSize];
			bufferSize = zzip_file_read( fp, buffer, static_cast<int>( bufferSize ) );

			zzip_file_close( fp );

			TextureResource* textureResource = new TextureResource();
			textureResource->future = mThreadPool.AddTask<LoadTextureTask>(buffer, bufferSize, &mGlLock);
#ifdef _CACH_PARSED_DATA_
			mTextureResource.insert(std::pair<const char*, TextureResource*>(file, textureResource));
#endif
			return textureResource;
	}
}
Example #11
0
size_t getEntry(const char *name, char *contentFile, char **ptr) {

  size_t size=0;
  ZZIP_DIR *dir;
  ZZIP_DIRENT entry;
  ZZIP_FILE *file;
  zzip_error_t error;
  char *buf;

  o_log(DEBUGM, "opening %s", name);

  dir = zzip_dir_open(name, &error);
  if (!dir) {
    o_log(ERROR, "failed to open %s", name);
    return 0;
  }

  while(zzip_dir_read(dir, &entry)) {

    if( 0 == strcmp(entry.d_name, contentFile) ) {

      file = zzip_file_open(dir, contentFile, O_RDONLY);

      (void)zzip_seek(file, 0, SEEK_END);
      size = zzip_tell(file);
      (void)zzip_seek(file, 0, SEEK_SET);

      buf = (char *)malloc(size+1);
      (void)zzip_read(file, buf, size);
      buf[size] = '\0';
      *ptr = buf;

      zzip_file_close(file);
    }
  }
  zzip_dir_close(dir);

  return size;
}
Example #12
0
/** 打开一个ZIP文件
@Param 文件的名字
*/
FVFileStream* FZipFilePack::Open( const AString& filename )
{
    ZZIP_FILE* pFile = zzip_file_open( m_pZipDir,filename.c_str(),
        ZZIP_ONLYZIP|ZZIP_CASELESS );

    if( !pFile )
    {
        AString errDesc;
        int zipError = zzip_error( m_pZipDir );
        if( zipError != ZZIP_NO_ERROR )
        {
            GetZipErrorDesc( zipError,errDesc );
            FLOG_WARNINGF( "FZipFilePack::Open(), Open file (%s) from ZIP package(%s) failed!",filename.c_str(),m_sName.c_str() );
        }

        return NULL;
    }

    ZZIP_STAT zipStat;
    zzip_dir_stat( m_pZipDir,filename.c_str(),&zipStat,ZZIP_CASEINSENSITIVE );

    // 创建一个ZIP文件流
    return new FZipFileStream( filename,pFile,zipStat.st_size );
}
Example #13
0
static int zipread_showfile(request_rec *r, const char *fname)
{
    char *zipfile, *name;
    ZZIP_DIR *dir;
    unsigned int itnum;

    if (!r->path_info) return HTTP_NOT_FOUND;

    zipfile = r->filename;

    if (!fname || !*fname)
    {
	name = apr_pstrdup(r->pool, r->path_info);
    }
    else
    {
	name = apr_pstrcat(r->pool, r->path_info, fname, NULL);
    }

    r->content_type = zipread_getcontenttype(r, name);
    if (*name == '/') name++;

    // ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "mod_zipread showfile: %s - %s - %s", zipfile, fname, name);

    for(itnum = 0; itnum < 5; itnum++)
    {
	dir = zzip_dir_open(zipfile, 0);
	if (dir)
	{
	    ZZIP_STAT st;

	    // fetch stat info of filename, before opening it
	    if (zzip_dir_stat(dir, name, &st, 0) != 0)
	    {
		// check if a directory entry is available for that name.
		name = apr_pstrcat(r->pool, name, "/", NULL);
	    
		if (zzip_dir_stat(dir, name, &st, 0) != 0)
		{
		    zzip_dir_close(dir);

		    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "mod_zipread showfile stat failed: %d - %s",
				  zzip_error(dir), zzip_strerror(zzip_error(dir)));

		    return HTTP_NOT_FOUND;
		}

		// found a directory entry, do an external redirect to get the
		// links in the directory listing right.
	    
		name = apr_pstrcat(r->pool, r->uri, "/", NULL);

		apr_table_setn(r->headers_out, "Location", name);

		// ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "mod_zipread showfile directory entry.");

		return HTTP_MOVED_PERMANENTLY;
	    }

	    ap_set_content_length(r, st.st_size);

	    // cannot check last-modified date of the file itself here, because
	    // zziplib doesnt extract it. instead we use the zip file's date
	    r->mtime = r->finfo.mtime;
	    ap_set_last_modified(r);

	    if (!r->header_only)
	    {
		ZZIP_FILE *fp = zzip_file_open(dir, name, 0);
		if (fp)
		{
		    int len;
		    char buf[32769];
		    while ((len = zzip_file_read (fp, buf, 32768)))
		    {
			ap_rwrite(buf, len, r);
		    }
		    zzip_file_close(fp);

		    zzip_dir_close(dir);
		    return OK;
		}
		else
		{
		    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "mod_zipread showfile file open failed: %d - %s.",
				  zzip_error(dir), zzip_strerror(zzip_error(dir)));

		    if (zzip_dir_stat(dir, name, &st, 0) != 0)
		    {
			ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "mod_zipread showfile after stat failed: %d - %s",
				      zzip_error(dir), zzip_strerror(zzip_error(dir)));

			break;
		    }

		    zzip_dir_close(dir);

		    continue;
		}
	    }

	    zzip_dir_close(dir);
	    return OK;
	}
	else
	{
	    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "mod_zipread showfile zip file not open.");
		
	    return HTTP_NOT_FOUND;
	}
    }

    zzip_dir_close (dir);

    return HTTP_NOT_FOUND;
}
Example #14
0
//从zip文件中读取全部文件内容到文件中或者内存中, 
//zip文件必须是通过addPatchFile加入的patch文件,
bool Updater::_readContentsFromZip(const char* szZipFile, const char* szFileName, 
					const char* szDiskFileName, char** ppMemoryBuf, unsigned int& nFileSize)
{
	//参数检查
	assert(szZipFile && szFileName && (szDiskFileName || ppMemoryBuf) );
	if(!szZipFile || szZipFile[0]==0 || !szFileName || szFileName[0]==0 || (!szDiskFileName && !ppMemoryBuf))
	{
		setLastError(AXP_ERR_PARAM);
		return false;
	}

	//搜索加入的zip文件
	PATCHFILE_MAP::iterator itPatch = 
		m_mapPatchFile.find(normaliseName(szZipFile));

	//无法找到zip文件
	assert(itPatch != m_mapPatchFile.end());
	if(itPatch == m_mapPatchFile.end()) 
	{
		setLastError(AXP_ERR_PARAM, "%s not inserted", szZipFile);
		return false;
	}

	//获得ZIP句柄
	ZZIP_DIR* mZzipDir = (ZZIP_DIR*)(itPatch->second);
	assert(mZzipDir);

	std::string norFileName = normaliseName(szFileName, false, true);

	//得到文件信息
	ZZIP_STAT zstat;
	memset(&zstat, 0, sizeof(ZZIP_STAT));

	//打开文件,如果打不开,是空文件
	ZZIP_FILE* zzipFile = zzip_file_open(mZzipDir, norFileName.c_str(), ZZIP_ONLYZIP | ZZIP_CASELESS);
	if(zzipFile)
	{
		int zip_err = zzip_dir_stat(mZzipDir, norFileName.c_str(), &zstat, ZZIP_CASEINSENSITIVE);
		if(zip_err!=0)
		{
			zzip_file_close(zzipFile);

			setLastError(AXP_ERR_ZIPFILE, "ziperr=%d", mZzipDir->errcode);
			return false;
		}
	}

	//如果需要写入文件
	if(szDiskFileName)
	{
		//确认文件所在目录存在
		char szDiskFilePath[MAX_PATH] = {0};
		strncpy(szDiskFilePath, szDiskFileName, MAX_PATH);
		PathRemoveFileSpec(szDiskFilePath);
		if(szDiskFilePath[0]!=0 && !forceCreatePath(szDiskFilePath))
		{
			if(zzipFile)zzip_file_close(zzipFile);

			setLastError(AXP_ERR_FILE_ACCESS, "Path=%s, WinErr=%d", szDiskFilePath, ::GetLastError());
			return false;
		}

		//创建该文件
		HANDLE hDiskFile = ::CreateFile(szDiskFileName, 
							GENERIC_READ|GENERIC_WRITE,
							FILE_SHARE_READ|FILE_SHARE_WRITE,
							0,
							CREATE_ALWAYS,
							FILE_ATTRIBUTE_ARCHIVE,
							0);

		if(hDiskFile == INVALID_HANDLE_VALUE)
		{
			if(zzipFile)zzip_file_close(zzipFile);

			setLastError(AXP_ERR_FILE_ACCESS, "File=%s, WinErr=%d", szDiskFileName, ::GetLastError());
			return false;
		}

		if(zstat.st_size > 0)
		{
			const int MAX_BUFFER_SIZE = 4096;
			char buffer[MAX_BUFFER_SIZE] = {0};

			zzip_seek(zzipFile, 0, SEEK_SET);
			zzip_ssize_t zReadSize = zzip_file_read(zzipFile, buffer, sizeof(buffer));
		
			//实际已经写入的尺寸
			unsigned int nActWriteSize = 0;

			//分块读写文件内容
			do
			{
				//文件结束
				if(zReadSize==0) break;

				//写入磁盘文件
				DWORD dwBytesWrite;
				if(!WriteFile(hDiskFile, buffer, (DWORD)zReadSize, &dwBytesWrite, 0) || 
					dwBytesWrite != (DWORD)zReadSize)
				{
					zzip_file_close(zzipFile);
					CloseHandle(hDiskFile);

					setLastError(AXP_ERR_FILE_WRITE, "File=%s, WinErr: %d", szDiskFileName, GetLastError());
					return false;
				}

				//文件结束
				if(zzip_tell(zzipFile) >=zstat.st_size) break;

				zReadSize = zzip_file_read(zzipFile, buffer, sizeof(buffer));
			}while(true);
		}
		//关闭句柄
		CloseHandle(hDiskFile); hDiskFile=0;
	}

	//如果需要读入内存
	if(ppMemoryBuf)
	{
		//所需要的内存
		unsigned int nMemoryNeed = (unsigned int)zstat.st_size+1;
		while(nMemoryNeed%4)nMemoryNeed++;	//upbound 4

		//扩大静态内存大小
		static std::vector< unsigned char > s_autoMemory;
		if(s_autoMemory.size() < nMemoryNeed) 
		{
			s_autoMemory.resize(nMemoryNeed);
		}
		s_autoMemory.assign(s_autoMemory.size(), 0);

		//读入文件内容
		if(zstat.st_size > 0)
		{
			zzip_seek(zzipFile, 0, SEEK_SET);
			zzip_ssize_t nZipSize = zzip_file_read(zzipFile, (char*)&(s_autoMemory[0]), zstat.st_size);
			if(nZipSize != zstat.st_size)
			{
				zzip_file_close(zzipFile);
				setLastError(AXP_ERR_ZIPFILE, "ziperr=%d", mZzipDir->errcode);
				return false;
			}
		}
		//返回内容
		*ppMemoryBuf = (char *)(&(s_autoMemory[0]));
	}

	//关闭句柄
	if(zzipFile)zzip_file_close(zzipFile);	zzipFile=0;

	nFileSize = (unsigned int)zstat.st_size;
	return true;
}
Example #15
0
ZZIP_FILE*
zzip_open_shared_io (ZZIP_FILE* stream,
                     zzip_char_t* filename, int o_flags, int o_modes,
                     zzip_strings_t* ext, zzip_plugin_io_t io)
{
    if (stream && stream->dir)
    {
        if (! ext) ext = stream->dir->fileext;
        if (! io) io = stream->dir->io;
    }
    if (! io) io = zzip_get_default_io ();

    if (o_modes & (ZZIP_PREFERZIP|ZZIP_ONLYZIP)) goto try_zzip;
try_real:
    /* prefer an existing real file */
    {
        zzip_plugin_io_t os = (o_modes & ZZIP_ALLOWREAL)
                              ?  zzip_get_default_io () : io;
        int fd = os->fd.open(filename, o_flags); /* io->fd.open */
        if (fd != -1)
        {
#if !defined(WINDOWSPC) || defined(__MINGW32__)
            struct stat st; // JMW
#endif
            ZZIP_FILE* fp = calloc (1, sizeof(ZZIP_FILE));
            if (! fp) {
                os->fd.close(fd);
                return 0;
            } /* io->fd.close */

            fp->dir = NULL;
            fp->fd = fd;
            fp->io = os;

#if !defined(WINDOWSPC) || defined(__MINGW32__)
            if (stat(filename,&st) >=0)
                fp->usize = st.st_size;
#else
            fp->usize = os->fd.filesize(fd);
#endif
            return fp;
        }
        if (o_modes & ZZIP_PREFERZIP) {
            return 0;
        }
    }
try_zzip:

    /* if the user had it in place of a normal xopen, then
     * we better defend this lib against illegal usage */
    if (o_flags & (O_CREAT|O_WRONLY))     {
        errno = EINVAL;
        return 0;
    }
    if (o_flags & (O_RDWR)) {
        o_flags ^= O_RDWR;
        o_flags |= O_RDONLY;
    }

    /* this is just for backward compatibility -and strictly needed to
     * prepare ourselves for more options and more options later on... */
    /*# if (o_modes & ZZIP_CASELESS) { o_flags |= ZZIP_CASEINSENSITIVE; } */
    /*# if (o_modes & ZZIP_NOPATHS)  { o_flags |= ZZIP_IGNOREPATH; } */

    /* see if we can open a file that is a zip file */
    {   char basename[PATH_MAX];
        char* p;
        int filename_len = strlen (filename);

        if (filename_len >= PATH_MAX) {
#ifdef ENAMETOOLONG
            errno = ENAMETOOLONG;
#endif
            return 0;
        }
        memcpy (basename, filename, filename_len+1);

        /* see if we can share the same zip directory */
        if (stream && stream->dir && stream->dir->realname)
        {
            zzip_size_t len = strlen (stream->dir->realname);
            if (! memcmp (filename, stream->dir->realname, len) &&
                    ((filename[len] == '/') || (filename[len] == '\\'))
                    && filename[len+1])
            {
                ZZIP_FILE* fp =
                    zzip_file_open (stream->dir, filename+len+1, o_modes);
                if (! fp) {
                    errno = zzip_errno (stream->dir->errcode);
                }
                return fp;
            }
        }

        /* per each slash in filename, check if it there is a zzip around */

        while ((p = strrchr (basename, '/')) || (p = strrchr (basename, '\\')))
        {
            zzip_error_t e = 0;
            ZZIP_DIR* dir;
            ZZIP_FILE* fp;
            int fd;

            *p = '\0'; /* cut at path separator == possible zipfile basename */
            fd = __zzip_try_open (basename, o_flags|O_RDONLY|O_BINARY, ext, io);

            if (fd == -1) {
                continue;
            }

            /*    found: */
            /* found zip-file, now try to parse it */
            dir = zzip_dir_fdopen_ext_io(fd, &e, ext, io);
            if (e) {
                errno = zzip_errno(e);
                io->fd.close(fd);
                return 0;
            }

            /* (p - basename) is the lenghtof zzip_dir part of the filename */
            fp = zzip_file_open(dir, filename + (p - basename) +1, o_modes);
            if (! fp) {
                errno = zzip_errno(dir->errcode);
            }
            else {
                if (! dir->realname) dir->realname = strdup (basename);
            }

            zzip_dir_close(dir);
            /* note: since (fp) is attached that (dir) will survive */
            /* but (dir) is implicitly closed on next zzip_close(fp) */

            return fp;
        } /*again*/

        if (o_modes & ZZIP_PREFERZIP) goto try_real;
        errno = ENOENT;
        return 0;
    }
}
bool CZipArchive::loadArchive(){
	static  mchar tempBuff[128];
	if(!m_zipDir){
		zzip_error_t err;
		//m_file=gFileSystem.openFile(getName());
		//if(!m_file || !m_file->getFD())return 0;
		
		//m_zipDir = zzip_dir_fdopen(m_file->getFD()->_file,&err);
		core::stringc fileName;
		core::string_to_char(getName(),fileName);
		m_zipDir = zzip_dir_open(fileName.c_str(),&err);
		if(checkForError(err,mT(" loadArchive()")))return false;

		ZZIP_DIRENT zipEntry;
		sFileEntry entry;
		core::string tstr;
		core::string zipName;
		core::stringc tmpc;
		while(zzip_dir_read(m_zipDir,&zipEntry)){
			zipName=zipEntry.d_name;
			zipName.replaceChar('\\','/');
			int x=zipName.findlast('/');
			if(x==zipName.length()){
// 				entry.dirPath=zipName;
// 				entry.filePath=zipName;
				entry.dirPath=mT("");
				entry.filePath=mT("");
				zipName[zipName.length()]='\0';
				x=zipName.findlast('/');
				tstr=zipName.substr(x,zipName.length()-x+1);
				entry.fileName=tstr;
				entry.isfolder=true;
				entry.fileData=0;
			}else{
				//entry.filePath=zipName;
				entry.dirPath=mT("");
				entry.filePath=mT("");

				tstr=zipName.substr(x+1,zipName.length());
				entry.fileName=tstr;

				core::string_to_char(zipName,tmpc);
				
				zzip_file*zipFile=zzip_file_open(m_zipDir,tmpc.c_str(),ZZIP_ONLYZIP | ZZIP_CASELESS);
				if(!zipFile){
					int zerr = zzip_error(m_zipDir);
					checkForError(zerr,mT("open zip file"));
					entry.fileData=0;
				}else{
					ZZIP_STAT zstate;
					zzip_dir_stat(m_zipDir,tmpc.c_str(),&zstate,ZZIP_CASEINSENSITIVE);

					entry.fileData=new CZipFile(entry.fileName.c_str(),zipFile,zstate.st_size);
				}

				int s=zipName.find('/');
				tstr=zipName.substr(s+1,x-s);
				entry.dirPath=tstr;
				entry.filePath=tstr+entry.fileName;
				entry.isfolder=false;
				

			}

			entry.compressSize=zipEntry.d_csize;
			entry.uncompressSize=zipEntry.st_size;


			m_files.push_back(entry);
		}
	}
	return 1;
}
Example #17
0
void process_zip(char *pPath) {
#ifdef HAVE_LIBZZIP
	ZZIP_DIR *dir;
	ZZIP_FILE *fp;
	ZZIP_DIRENT dirent;
	char buf[BUF_SIZE];	
	int nRead;
	long depth = 0;
	int ret = 0;
	
	dir = zzip_dir_open(pPath, 0);

	if (!dir) { return; }

	while (zzip_dir_read(dir, &dirent)) {
		fp = zzip_file_open(dir, dirent.d_name, 0);
		if (fp) {
			// pull the data and scan
			while ((nRead = zzip_file_read(fp, buf, BUF_SIZE)) > 0) {
				depth += nRead;
				if (is_match(buf,nRead)) {
					ret = 1;
					if (!LogTotalMatches) {
						send_match(hit,pPath);
						break;
					}
				}
				bzero(buf, sizeof(buf));
				if ((ScanDepth != 0) && (depth >= (ScanDepth * 1024))) {
					break;
				}

			}
			zzip_file_close(fp);
		}
	}

	if ((LogTotalMatches && TotalMatches) || ret) {
		send_match(hit, pPath);
	}

	zzip_dir_close(dir);
#else
#ifdef HAVE_LIBZIP
  struct zip *za;
  int err, ret = 0, nRead;
  char errstr[1024],
       buf[BUF_SIZE];
  long depth;

  if ((za = zip_open(pPath, 0, &err)) == NULL) {
    return;
  }

while ((nRead = zip_fread(za, &buf, BUF_SIZE)) > 0) {
  depth += nRead;
  if (is_match(buf,nRead)) {
    ret = 1;
    if (!LogTotalMatches) {
      send_match(hit,pPath);
      zip_close(za);
      return;
    }
  }
  bzero(buf, sizeof(buf));
  if ((ScanDepth != 0) && (depth >= (ScanDepth * 1024))) {
    break;
   }
 }

 if ((LogTotalMatches && TotalMatches) || ret) {
   send_match(hit, pPath);
 }
 
 zip_close(za);
#endif /* HAVE_LIBZIP */
	return;
#endif /* HAVE_ZZIP */
}
Example #18
0
bool ZipStream::open()
{
	handle = zzip_file_open(dir, path.c_str(), ZZIP_ONLYZIP);
	return handle != nullptr;
}
ModelFileParser* ResourceManager::LoadModel(const char* file)
{
#ifdef _CACH_PARSED_DATA_
	for (std::map<const char*, ModelFileParser*>::iterator it = mModelFileParsers.begin(); it != mModelFileParsers.end(); it++)
	{
		if (it->first == file)
			return it->second;
	}
#endif

	unsigned int bufferSize;
	char* buffer;

	switch ( mAssetPacketExtension )
	{
		case PACA:
		{
			bufferSize	= mPacaReader.GetResourceSize( file );
			buffer		= new char[bufferSize];
			if ( !mPacaReader.GetResource( file, buffer, bufferSize ) )
				return nullptr;
			break;
		}
		break;

		case ZIP:
		{
			ZZIP_FILE* fp = zzip_file_open( mDir, file, 0 );
			zzip_seek( fp, 0, SEEK_END );
			bufferSize = zzip_tell( fp );
			zzip_rewind( fp );

			buffer = new char[bufferSize];
			bufferSize = zzip_file_read( fp, buffer, bufferSize );

			zzip_file_close( fp );
		}
		break;
	}
	addToMemCount(bufferSize);

	ModelFileParser* mParser;
	std::string fileString;
	fileString = std::string(file);
	if (fileString.substr(fileString.find_last_of(".") + 1) == "mesh")
	{
		mParser = new MeshParser();
		addToMemCount(sizeof(mParser));
	}
	else if (fileString.substr(fileString.find_last_of(".") + 1) == "obj")
	{
		mParser = new ObjParser();
		addToMemCount(sizeof(mParser));
	}
	else
	{
		delete[] buffer;
		addToMemCount(-bufferSize);
		return NULL;
	}

	mParser->Load(buffer, bufferSize);
	addToMemCount(mParser->memory);
	delete[] buffer;
	addToMemCount(-bufferSize);

#ifdef _CACH_PARSED_DATA_
	mModelFileParsers.insert(std::pair<const char*, ModelFileParser*>(file, mParser));
#endif

	return mParser;
}
Example #20
0
/** Creates a buffer of all the data in the SRTM file. The uncompressed version is used if available.
  *
  * \returns The length of the side of the data (e.g. 1201 or 3601)
  * \note The buffer returned is owned by the caller of this function and _must_ be freed after usage.
  */
int SrtmZipFile::getData(QString filename, qint16 **buffer)
{
    *buffer = 0;
    
    QFileInfo fi(filename);
    QString uncompressedFile = fi.path()+'/'+fi.completeBaseName();

    int size = 0;
    if (QFileInfo(uncompressedFile).exists()) {
        QFile file(uncompressedFile);
        if (!file.open(QIODevice::ReadOnly)) {
            qCritical() << "ZIP(Uncompressed): Could not open file" << uncompressedFile << file.errorString();
            return 0;
        }
        size = sqrt(file.size()/2);
        if (size*size*2 != file.size()) {
            qCritical() << "ZIP(Uncompressed): Invalid data: Not a square!";
        }
        *buffer = new qint16[file.size()/2];
        if (!*buffer) {
            qCritical() << "ZIP(Uncompressed): Could not allocate buffer.";
            return 0;
        }
        if (file.read((char *)*buffer, file.size()) != file.size()) {
            qCritical() << "ZIP(Uncompressed): Could not read all bytes.";
        }
        file.close();
    } else {
        ZZIP_DIR* dir = zzip_dir_open(filename.toAscii(), 0);
        if (!dir) {
            qCritical() << "ZIP: Could not open zip file" << filename;
            return 0;
        }
        ZZIP_FILE* fp = zzip_file_open(dir, fi.completeBaseName().toAscii(), 0);
        if (!fp) {
            qCritical() << "ZIP: Could not find" <<  fi.completeBaseName() << "in" << filename;
            return 0;
        }
        ZZIP_STAT stat;
        if (zzip_file_stat(fp, &stat) == -1) {
            qCritical() << "ZIP: Could not get info about" << uncompressedFile;
            return 0;
        }
        
        size = sqrt(stat.st_size/2);
        if (size*size*2 != stat.st_size) {
            qCritical() << "ZIP: Invalid data: Not a square!";
        }
        *buffer = new qint16[stat.st_size/2];

        if (zzip_file_read(fp, *buffer, stat.st_size) != stat.st_size) {
            qCritical() << "ZIP: Could not read all bytes.";
            delete *buffer;
            *buffer = 0;
            return 0;
        }

        //store uncompressed content on disk?
        if (false) {
            QFile file(uncompressedFile);
            if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
                qCritical() << "ZIP(Writing): Could not open file" << uncompressedFile << file.errorString();
            } else {
                file.write((char *)*buffer, stat.st_size);
                file.close();
            }
        }
        zzip_file_close(fp);
        zzip_dir_close(dir);
    }
    return size;
}
Example #21
0
bool ExtractFileFromZip(AXP::IUpdater* pUpdater, const char* szZipFile, const char* szFileInZip, const char* szFileInDisk)
{
	//打开zip文件
	zzip_error_t zzipError;
	ZZIP_DIR* mZzipDir = zzip_dir_open_ext_io(szZipFile, &zzipError, 0, 
		(zzip_plugin_io_t)(pUpdater->getEncryptZipPluginIO(szZipFile)));
	if (zzipError != ZZIP_NO_ERROR) 
	{
		return false;
	}

	//得到文件信息
	ZZIP_STAT zstat;
	memset(&zstat, 0, sizeof(ZZIP_STAT));

	//打开文件,如果打不开,是空文件
	ZZIP_FILE* zzipFile = zzip_file_open(mZzipDir, szFileInZip, ZZIP_ONLYZIP | ZZIP_CASELESS);
	if(!zzipFile)
	{
		zzip_dir_close(mZzipDir);
		return false;
	}

	//获得文件信息
	int zip_err = zzip_dir_stat(mZzipDir, szFileInZip, &zstat, ZZIP_CASEINSENSITIVE);
	if(zip_err!=0)
	{
		zzip_file_close(zzipFile);
		zzip_dir_close(mZzipDir);
		return false;
	}

	//创建该文件
	HANDLE hDiskFile = ::CreateFile(szFileInDisk, 
		GENERIC_READ|GENERIC_WRITE,
		FILE_SHARE_READ|FILE_SHARE_WRITE,
		0,
		CREATE_ALWAYS,
		FILE_ATTRIBUTE_ARCHIVE,
		0);

	if(hDiskFile == INVALID_HANDLE_VALUE)
	{
		zzip_file_close(zzipFile);
		zzip_dir_close(mZzipDir);
		return false;
	}

	if(zstat.st_size > 0)
	{
		const int MAX_BUFFER_SIZE = 4096;
		char buffer[MAX_BUFFER_SIZE] = {0};

		zzip_seek(zzipFile, 0, SEEK_SET);
		zzip_ssize_t zReadSize = zzip_file_read(zzipFile, buffer, sizeof(buffer));

		//实际已经写入的尺寸
		unsigned int nActWriteSize = 0;

		//分块读写文件内容
		do
		{
			//文件结束
			if(zReadSize==0) break;

			//写入磁盘文件
			DWORD dwBytesWrite;
			if(!WriteFile(hDiskFile, buffer, (DWORD)zReadSize, &dwBytesWrite, 0) || 
				dwBytesWrite != (DWORD)zReadSize)
			{
				zzip_file_close(zzipFile);
				zzip_dir_close(mZzipDir);
				CloseHandle(hDiskFile);
				return false;
			}

			//文件结束
			if(zzip_tell(zzipFile) >=zstat.st_size) break;

			zReadSize = zzip_file_read(zzipFile, buffer, sizeof(buffer));
		}while(true);
	}
	//关闭句柄
	CloseHandle(hDiskFile); hDiskFile=0;
	zzip_file_close(zzipFile);	zzipFile=0;
	zzip_dir_close(mZzipDir); mZzipDir=0;

	return true;
}