Beispiel #1
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;
    }
}
Beispiel #2
0
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);
}
CORE::UInt32
CZipIOAccess::Read( void *dest            ,
                    CORE::UInt32 esize    ,
                    CORE::UInt32 elements )
{GUCEF_TRACE;

    return (CORE::UInt32) zzip_file_read( m_zzipFile, (char*)dest, esize*elements );
}
Beispiel #4
0
/**                                                               
 * This function will read(2) data from a real/zipped file.
 *
 * the replacement for => read(2) will fill the given buffer with bytes from
 * the opened file. It will return the number of bytes read, so if the EOF
 * is encountered you will be prompted with the number of bytes actually read.
 * 
 * If the file-handle is wrapping a stat'able file then it will actually just
 * perform a normal => read(2)-call, otherwise => zzip_file_read is called
 * to decompress the data stream and any error is mapped to => errno(3).
 */
zzip_ssize_t
zzip_read(ZZIP_FILE * fp, char * buf, zzip_size_t len)
{
    if (! fp) return 0;
    if (! fp->dir) 
      { return fp->io->read(fp->fd, buf, len); } /* stat fd */
    else
    {   register zzip_ssize_t v;
        v = zzip_file_read(fp, buf, len);
        if (v == -1) { errno = zzip_errno(fp->dir->errcode); }
        return v;
    }
}
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);
	}
}
Beispiel #6
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);
    }
}
Beispiel #7
0
/** 读取指定数目的数据
@Param 存储数据的缓冲区指针
@Param 要读取数据的大小
*/
size_t FZipFileStream::Read( void* pBuf,size_t nSize )
{
    zzip_ssize_t ret = zzip_file_read( m_pZipFile,pBuf,nSize );

    if( ret < 0 )
    {
        ZZIP_DIR* dir = zzip_dirhandle( m_pZipFile );

        // 报告错误
        AString msg = zzip_strerror_of( dir );
        FLOG_ERRORF("FZipFileStream::Read, An exception is found when reading zip package! (%s)", msg.c_str());
    }

    return ret;
}
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;
	}
}
Beispiel #9
0
 //-----------------------------------------------------------------------
 size_t ZipDataStream::read(void* buf, size_t count)
 {
     size_t was_avail = mCache.read(buf, count);
     zzip_ssize_t r = 0;
     if (was_avail < count)
     {
         r = zzip_file_read(mZzipFile, (char*)buf + was_avail, count - was_avail);
         if (r<0) {
             ZZIP_DIR *dir = zzip_dirhandle(mZzipFile);
             String msg = zzip_strerror_of(dir);
             OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
                 mName+" - error from zziplib: "+msg,
                 "ZipDataStream::read");
         }
         mCache.cacheData((char*)buf + was_avail, (size_t)r);
     }
     return was_avail + (size_t)r;
 }
Beispiel #10
0
/**
 * This function will read(2) data from a real/zipped file.
 *
 * the replacement for => read(2) will fill the given buffer with bytes from
 * the opened file. It will return the number of bytes read, so if the EOF
 * is encountered you will be prompted with the number of bytes actually read.
 *
 * If the file-handle is wrapping a stat'able file then it will actually just
 * perform a normal => read(2)-call, otherwise => zzip_file_read is called
 * to decompress the data stream and any error is mapped to => errno(3).
 */
zzip_ssize_t
zzip_read(ZZIP_FILE * fp, void *buf, zzip_size_t len)
{
    if (! fp)
        return 0;
    if (! fp->dir)
        { return fp->io->fd.read(fp->fd, buf, len); }    /* stat fd */
    else
    {
        register zzip_ssize_t v;

        v = zzip_file_read(fp, buf, len);
#ifdef ZZIP_DISABLED
        if (v == -1)
            { errno = zzip_errno(fp->dir->errcode); }
#endif /* ZZIP_DISABLED */
        return v;
    }
}
Beispiel #11
0
 //-----------------------------------------------------------------------
 size_t ZipDataStream::read(void* buf, size_t count)
 {
     return zzip_file_read(mZzipFile, (char*)buf, count);
 }
int CZipArchive::CZipFile::read(void*_data,size_t _size){
	return zzip_file_read(m_zipfile,(char*)(_data),_size);
}
Beispiel #13
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 */
}
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;
}
Beispiel #15
0
int64 ZipStream::read(void* buf, uint64 len) const
{
	return zzip_file_read(handle, buf, (zzip_size_t) len);
}
Beispiel #16
0
/**
 * This function will perform a => lseek(2) operation on a real/zipped file
 *
 * It will try to seek to the offset specified by offset, relative to whence,
 * which is one of SEEK_SET, SEEK_CUR or SEEK_END.
 *
 * If the file-handle is wrapping a stat'able file then it will actually just
 * perform a normal => lseek(2)-call. Otherwise the relative offset
 * is calculated, negative offsets are transformed into positive ones
 * by rewinding the file, and then data is read until the offset is
 * reached.  This can make the function terribly slow, but this is
 * how gzio implements it, so I'm not sure there is a better way
 * without using the internals of the algorithm.
 */
zzip_off_t
zzip_seek(ZZIP_FILE * fp, zzip_off_t offset, int whence)
{
    zzip_off_t cur_pos, rel_ofs, read_size, ofs;
    ZZIP_DIR *dir;

    if (! fp)
        return -1;

    if (! fp->dir)
    {   /* stat fd */
        return fp->io->fd.seeks(fp->fd, offset, whence);
    }

    cur_pos = zzip_tell(fp);

    /* calculate relative offset */
    switch (whence)
    {
    case SEEK_SET: /* from beginning */
        rel_ofs = offset - cur_pos;
        break;
    case SEEK_CUR: /* from current */
        rel_ofs = offset;
        break;
    case SEEK_END: /* from end */
        rel_ofs = fp->usize + offset - cur_pos;
        break;
    default: /* something wrong */
        return -1;
    }

    if (rel_ofs == 0)
        return cur_pos; /* don't have to move */

    if (rel_ofs < 0)
    {   /* convert backward into forward */
        if (zzip_rewind(fp) == -1)
            return -1;

        read_size = cur_pos + rel_ofs;
        cur_pos = 0;
    } else
    {   /* amount to read is positive relative offset */
        read_size = rel_ofs;
    }

    if (read_size < 0) /* bad offset, before beginning of file */
        return -1;

    if (read_size + cur_pos > (zzip_off_t)fp->usize) /* bad offset, past EOF */
        return -1;

    if (read_size == 0) /* nothing to read */
        return cur_pos;

    dir = fp->dir;
    /*
     * If this is other handle than previous, save current seek pointer
     * and read the file position of `this' handle.
     */
    if (dir->currentfp != fp)
    {
        if (zzip_file_saveoffset(dir->currentfp) < 0
                || dir->currentfp->io->fd.seeks(dir->fd, fp->offset, SEEK_SET) < 0)
        {
            dir->errcode = ZZIP_DIR_SEEK;
            return -1;
        }
        else
        {
            dir->currentfp = fp;
        }
    }

    if (fp->method == 0)
    {   /* unstore, just lseek relatively */
        ofs = fp->io->fd.tells(dir->fd);
        ofs = fp->io->fd.seeks(dir->fd,read_size,SEEK_CUR);
        if (ofs > 0)
        {   /* readjust from beginning of file */
            ofs -= fp->dataoffset;
            fp->restlen = fp->usize - ofs;
        }
        return ofs;
    } else
    {   /* method == 8, inflate */
        char *buf;
        /*FIXME: use a static buffer! */
        buf = (char *)malloc(ZZIP_32K);
        if (! buf) return -1;

        while (read_size > 0)
        {
            zzip_off_t size = ZZIP_32K;
            if (read_size < size/*32K*/) size = read_size;

            size = zzip_file_read(fp, buf, (zzip_size_t)size);
            if (size <= 0) {
                free(buf);
                return -1;
            }

            read_size -= size;
        }

        free (buf);
    }

    return zzip_tell(fp);
}
static int reader_zzip_read(reader_t*reader, void* data, int len) 
{
    return zzip_file_read((ZZIP_FILE*)reader->internal, data, len);
}
Beispiel #18
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;
}
Beispiel #19
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;
}
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;
}
Beispiel #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;
}