void
CZipIOAccess::Close( void )
{GUCEF_TRACE;

    zzip_file_close( m_zzipFile );
    m_zzipFile = NULL;
}
Example #2
0
/** => zzip_fopen
 *
 * This function receives an additional argument pointing to
 * a ZZIP_FILE* being already in use. If this extra argument is
 * null then this function is identical with calling => zzip_fopen
 *
 * Per default, the old file stream is closed and only the internal
 * structures associated with it are kept. These internal structures
 * may be reused for the return value, and this is a lot quicker when
 * the filename matches a zipped file that is incidently in the very
 * same zip arch as the old filename wrapped in the stream struct.
 *
 * That's simply because the zip arch's central directory does not 
 * need to be read again. As an extension for this function, if the 
 * mode-string contains a "q" then the old stream is not closed but
 * left untouched, instead it is only given as a hint that a new
 * file handle may share/copy the zip arch structures of the old file
 * handle if that is possible, i.e when they are in the same zip arch.
 *
 * This function returns a new zzip-handle (use => zzip_close to return
 * it). On error this function will return null setting => errno(3).
 */ 
ZZIP_FILE*
zzip_freopen(zzip_char_t* filename, zzip_char_t* mode, ZZIP_FILE* stream)
{
    int o_flags = 0;
    int o_modes = 0664;
    if (! mode) mode = "rb";

#   ifndef O_BINARY
#   define O_BINARY 0
#   endif
#   ifndef O_NOCTTY
#   define O_NOCTTY 0
#   endif
#   ifndef O_SYNC
#   define O_SYNC 0
#   endif
#   ifndef O_NONBLOCK
#   define O_NONBLOCK 0
#   endif

    for(; *mode; mode++) 
    {
        switch (*mode)
        {
	case '0': case '1': case '2': case '3': case '4': 
	case '5': case '6': case '7': case '8': case '9':
	    continue; /* ignore if not attached to other info */
        case 'r': o_flags |= mode[1] == '+' ? O_RDWR : O_RDONLY; break;
        case 'w': o_flags |= mode[1] == '+' ? O_RDWR : O_WRONLY; 
                  o_flags |= O_TRUNC; break;
        case 'b': o_flags |= O_BINARY; break;
        case 'f': o_flags |= O_NOCTTY; break;
        case 'i': o_modes |= ZZIP_CASELESS; break;
        case '*': o_modes |= ZZIP_NOPATHS; break;
        case 'x': o_flags |= O_EXCL; break;
        case 's': o_flags |= O_SYNC; break;
        case 'n': o_flags |= O_NONBLOCK; break;
	case 'o': o_modes &=~ 07; 
                  o_modes |= ((mode[1] - '0'))&07; continue;
	case 'g': o_modes &=~ 070; 
                  o_modes |= ((mode[1] - '0')<<3)&070; continue;
	case 'u': o_modes &=~ 0700; 
                  o_modes |= ((mode[1] - '0')<<6)&0700; continue;
	case 'q': o_modes |= ZZIP_FACTORY; break;
	case 'z': /* compression level */
	    continue; /* currently ignored, just for write mode */
        }
    }

    {
	ZZIP_FILE* fp = 
	    zzip_open_shared_io (stream, filename, o_flags, o_modes, 0, 0);

	if ( (!(o_modes&ZZIP_FACTORY)) && stream ) {
	    zzip_file_close (stream);
	}

	return fp;
    }
}
Example #3
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 #4
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);
}
CZipArchive::CZipFile::~CZipFile(){
	if(m_isOpen)
		close();
	if(m_zipfile){
		zzip_file_close(m_zipfile);
		m_zipfile=0;
	}
}
Example #6
0
/**                                                             
 * This function closes the given ZZIP_FILE handle. 
 *
 * If the ZZIP_FILE wraps a normal stat'fd then it is just that int'fd 
 * that is being closed and the otherwise empty ZZIP_FILE gets freed.
 */
int 
zzip_fclose(ZZIP_FILE * fp)
{
    if (! fp) return 0;
    if (! fp->dir) 
      { int r = fp->io->close(fp->fd); free(fp); return r; } /* stat fd */
    else return zzip_file_close(fp);
}
Example #7
0
/**
 * This function will rewind a real/zipped file.
 *
 * It seeks to the beginning of this file's data in the zip,
 * or the beginning of the file for a stat'fd.
 */
int
zzip_rewind(ZZIP_FILE *fp)
{
    ZZIP_DIR *dir;
    int err;

    if (! fp)
        return -1;

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

    dir = fp->dir;
    /*
     * If this is other handle than previous, save current seek pointer
     */
    if (dir->currentfp != fp)
    {
        if (zzip_file_saveoffset(dir->currentfp) < 0)
        {
            dir->errcode = ZZIP_DIR_SEEK;
            return -1;
        }
        else
        {
            dir->currentfp = fp;
        }
    }

    /* seek to beginning of this file */
    if (fp->io->fd.seeks(dir->fd, fp->dataoffset, SEEK_SET) < 0)
        return -1;

    /* reset the inflate init stuff */
    fp->restlen = fp->usize;
    fp->offset = fp->dataoffset;

    if (fp->method)
    {   /* method == 8, deflate */
        err = inflateReset(&fp->d_stream);
        if (err != Z_OK) {
            goto error;
        }

        /* start over at next inflate with a fresh read() */
        fp->d_stream.avail_in = 0;
        fp->crestlen = fp->csize;
    }

    return 0;

error:
    if (fp) zzip_file_close(fp);
    return err;
}
Example #8
0
 //-----------------------------------------------------------------------
 void ZipDataStream::close(void)
 {
     if (mZzipFile != 0)
     {
         zzip_file_close(mZzipFile);
         mZzipFile = 0;
     }
     mCache.clear();
 }
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);
    }
}
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);
	}
}
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 #12
0
/**
 *  call => inflateInit and setup fp's iterator variables, 
 *  used by lowlevel => _open functions.
 */
static int 
zzip_inflate_init(ZZIP_FILE * fp, struct zzip_dir_hdr* hdr)
{
    int err;
    fp->method = hdr->d_compr;
    fp->restlen = hdr->d_usize;
    
    if (fp->method)
    {
        memset(&fp->d_stream, 0, sizeof(fp->d_stream));
  
        err = inflateInit2(&fp->d_stream, -MAX_WBITS);
        if (err != Z_OK) { goto error; }

        fp->crestlen = hdr->d_csize;
    }
    return 0;
error:
    if (fp) zzip_file_close(fp);
    return err;
}
Example #13
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 #14
0
 //-----------------------------------------------------------------------
 void ZipDataStream::close(void)
 {
     zzip_file_close(mZzipFile);
 }
Example #15
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 #16
0
bool ZipStream::close()
{
	return zzip_file_close(handle) == ZZIP_NO_ERROR;
}
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 #18
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;
}
Example #19
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 #20
0
/**
 * open an => ZZIP_FILE from an already open => ZZIP_DIR handle. Since
 * we have a chance to reuse a cached => buf32k and => ZZIP_FILE memchunk
 * this is the best choice to unpack multiple files.
 *
 * Note: the zlib supports 2..15 bit windowsize, hence we provide a 32k
 *       memchunk here... just to be safe.
 *
 * On error it returns null and sets errcode in the ZZIP_DIR.
 */
ZZIP_FILE *
zzip_file_open(ZZIP_DIR * dir, zzip_char_t* name, int o_mode)
{
    // JMW auto
    int self;
    zzip_error_t err = 0;
    struct zzip_file * fp = 0;
    struct zzip_dir_hdr * hdr = dir->hdr0;
    int (*cmp)(zzip_char_t*, zzip_char_t*);

    cmp = (o_mode & ZZIP_CASELESS)? dirsep_casecmp: strcmp;

    if (! dir) {
        return NULL;
    }
    if (! dir->fd || dir->fd == -1) {
        dir->errcode = EBADF;
        return NULL;
    }
    if (! hdr) {
        dir->errcode = ENOENT;
        return NULL;
    }

    if (o_mode & ZZIP_NOPATHS)
    {
        register zzip_char_t* n = dirsep_strrchr(name, '/');
        if (n)  name = n + 1;
    }

    while (1)
    {
        register zzip_char_t* hdr_name = hdr->d_name;
        if (o_mode & ZZIP_NOPATHS)
        {
            register zzip_char_t* n = dirsep_strrchr(hdr_name, '/');
            if (n)  hdr_name = n + 1;
        }

        HINT4("name='%s', compr=%d, size=%d\n",
              hdr->d_name, hdr->d_compr, hdr->d_usize);

        if (! cmp(hdr_name, name))
        {
            switch (hdr->d_compr)
            {
            case 0: /* store */
            case 8: /* inflate */
                break;
            default:
            {
                err = ZZIP_UNSUPP_COMPR;
                goto error;
            }
            }

            if (dir->cache.locked == NULL)
                dir->cache.locked = &self;

            if (dir->cache.locked == &self &&
                    dir->cache.fp)
            {
                fp = dir->cache.fp;
                dir->cache.fp = NULL;
                /* memset(zfp, 0, sizeof *fp); cleared in zzip_file_close() */
            } else
            {
                if (! (fp = (ZZIP_FILE *)calloc(1, sizeof(*fp))))
                {
                    err =  ZZIP_OUTOFMEM;
                    goto error;
                }
            }

            fp->dir = dir;
            fp->io = dir->io;
            dir->refcount++;

            if (dir->cache.locked == &self &&
                    dir->cache.buf32k)
            {
                fp->buf32k = dir->cache.buf32k;
                dir->cache.buf32k = NULL;
            }
            else
            {
                if (! (fp->buf32k = (char *)malloc(ZZIP_32K)))
                {
                    err = ZZIP_OUTOFMEM;
                    goto error;
                }
            }

            if (dir->cache.locked == &self)
                dir->cache.locked = NULL;
            /*
             * In order to support simultaneous open files in one zip archive
             * we'll fix the fd offset when opening new file/changing which
             * file to read...
             */

            if (zzip_file_saveoffset(dir->currentfp) < 0)
            {
                err = ZZIP_DIR_SEEK;
                goto error;
            }

            fp->offset = hdr->d_off;
            dir->currentfp = fp;

            if (dir->io->fd.seeks(dir->fd, hdr->d_off, SEEK_SET) < 0)
            {
                err = ZZIP_DIR_SEEK;
                goto error;
            }

            {   /* skip local header - should test tons of other info,
                * but trust that those are correct */
                zzip_ssize_t dataoff;
                struct zzip_file_header * p = (void*) fp->buf32k;

                dataoff = dir->io->fd.read(dir->fd, (void*)p, sizeof(*p));
                if (dataoff < (zzip_ssize_t)sizeof(*p))
                {
                    err = ZZIP_DIR_READ;
                    goto error;
                }
                if (! zzip_file_header_check_magic(p)) /* PK\3\4 */
                {
                    err = ZZIP_CORRUPTED;
                    goto error;
                }

                dataoff = zzip_file_header_sizeof_tail(p);

                if (dir->io->fd.seeks(dir->fd, dataoff, SEEK_CUR) < 0)
                {
                    err = ZZIP_DIR_SEEK;
                    goto error;
                }

                fp->dataoffset = dir->io->fd.tells(dir->fd);
                fp->usize = hdr->d_usize;
                fp->csize = hdr->d_csize;
            }

            err = zzip_inflate_init (fp, hdr);
            if (err) {
                goto error;
            }

            return fp;
        } else
        {
            if (hdr->d_reclen == 0)
                break;
            hdr = (struct zzip_dir_hdr *)((char *)hdr + hdr->d_reclen);
        }/*cmp name*/
    }/*forever*/
    dir->errcode = ZZIP_ENOENT;

    return NULL;
error:
    if (fp) zzip_file_close(fp);
    dir->errcode = err;
    return NULL;
}
Example #21
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 #22
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 #23
0
void msSHPDiskTreeClose(SHPTreeHandle disktree)
{
  zzip_file_close( disktree->fp );
  free( disktree );
}