Exemplo n.º 1
0
    int extractToMemory(std::vector<unsigned char>& outvec, ZipEntry& info)
    {
      size_t err = UNZ_ERRNO;

      err = unzOpenCurrentFilePassword(m_zf, m_outer.m_password.c_str());
      if (UNZ_OK != err)
      {
        std::stringstream str;
        str << "Error " << err << " opening internal file '" 
            << info.name << "' in zip";

        throw EXCEPTION_CLASS(str.str().c_str());
      }

      std::vector<unsigned char> buffer;
      buffer.resize(WRITEBUFFERSIZE);

      outvec.reserve((size_t)info.uncompressedSize);

      do
      {
        err = unzReadCurrentFile(m_zf, buffer.data(), (unsigned int)buffer.size());
        if (err < 0 || err == 0)
          break;

        outvec.insert(outvec.end(), buffer.data(), buffer.data() + err);

      } while (err > 0);

      return (int)err;
    }
Exemplo n.º 2
0
bool ComicBookZIP::TestPassword()
{
	int retcode;
	unzFile ZipFile;
	ZipFile = unzOpen(filename.ToAscii());
	bool retval;
	
	if (!ZipFile) {
		throw ArchiveException(filename, wxT("Could not open the file."));
	}
	if((retcode = unzLocateFile(ZipFile, Filenames->Item(0).ToAscii(), 0)) != UNZ_OK) {
		unzClose(ZipFile);
		throw ArchiveException(filename, ArchiveError(retcode));
	}
	
	if (password)
		retcode = unzOpenCurrentFilePassword(ZipFile, password);
	else
		retcode = unzOpenCurrentFile(ZipFile);
	if (retcode != UNZ_OK) {
		unzClose(ZipFile);
		throw ArchiveException(filename, ArchiveError(retcode));
	}
	
	char testByte;
	if(unzReadCurrentFile(ZipFile, &testByte, 1) == Z_DATA_ERROR) // if the password is wrong
		retval = false;
	else
		retval = true;
	unzCloseCurrentFile(ZipFile);
	unzClose(ZipFile);	
	return retval;
}
Exemplo n.º 3
0
	zlib_FileResource::zlib_FileResource(const std::string & zipPath, const std::string & fileName)
		:	m_ZipPath(zipPath),
			m_FileName(fileName)
	{
		unzFile zipFile = unzOpen(zipPath.c_str());

		KeziaAssert(unzLocateFile(zipFile, fileName.c_str(), 0) == UNZ_OK);

		unz_file_info fileInfo;
		unzGetCurrentFileInfo(zipFile, &fileInfo, nullptr, 0, nullptr, 0, nullptr, 0);

		m_Data = new char[fileInfo.uncompressed_size + 1];

		if(unzOpenCurrentFilePassword(zipFile, k_Password.c_str()) != UNZ_OK)
		{
			LOG("wrong password");
		}
		
		m_DataSize = unzReadCurrentFile(zipFile, const_cast<char *>(m_Data), fileInfo.uncompressed_size);
		const_cast<char &>(m_Data[m_DataSize]) = '\0';
		
		unzCloseCurrentFile(zipFile);
		
		unzClose(zipFile);
	}
Exemplo n.º 4
0
int OpenFile(ngePackage* pkg, const char* fname,int flag) {
	ngePackageZip* zip = (ngePackageZip*)pkg;
	ngeVFZip* f;
	unzFile file;

	if (flag != IO_RDONLY)
		return 0;

	file = unzOpen(zip->fname);
	if (file == NULL)
		return 0;

	if(unzLocateFile(file, fname, 0) != UNZ_OK)
		goto fail;

	if (zip->passwd == NULL) {
		if (unzOpenCurrentFile(file) != UNZ_OK)
			goto fail;
	}
	else {
		if (unzOpenCurrentFilePassword(file, zip->passwd) != UNZ_OK)
			goto fail;
	}

	f = (ngeVFZip*)malloc(sizeof(ngeVFZip));
	f->file = file;

	f->op = &zipFileOperation;
	return ngeVFAdd((ngeVF*)f);

fail:
	unzClose(file);
	return 0;
}
Exemplo n.º 5
0
bool PrepareReadCurrentFile( JSContext *cx, JS::HandleObject obj ) {

	Private *pv = (Private *)JL_GetPrivate(obj);
	JL_ASSERT_THIS_OBJECT_STATE(pv);
	ASSERT( pv && !pv->inZipOpened && pv->uf );

	unz_file_info pfile_info;
	UNZ_CHK( unzGetCurrentFileInfo(pv->uf, &pfile_info, NULL, 0, NULL, 0, NULL, 0) );

	if ( pfile_info.flag & 1 ) { // has password

		jl::StrData password(cx);
		JS::RootedValue tmp(cx);

		JL_CHK( JL_GetReservedSlot( obj, SLOT_CURRENTPASSWORD, &tmp) );
		if ( !tmp.isUndefined() )
			JL_CHK( jl::getValue(cx, tmp, &password) );

		if ( password.length() == 0 )
			return ThrowZipFileError(cx, JLERR_PASSWORDREQUIRED);
		UNZ_CHK( unzOpenCurrentFilePassword(pv->uf, password) );
	} else {

		UNZ_CHK( unzOpenCurrentFile(pv->uf) );
	}

	pv->inZipOpened = true;
	pv->remainingLength = pfile_info.uncompressed_size;

	return true;
	JL_BAD;
}
Exemplo n.º 6
0
			Position SetPos(Position p)
			{
				Position currentPos = GetPos();
				if (p == currentPos)
					return p;
				if (p <= fileInfo.uncompressed_size)
				{
					Position readBytes = 0;
					if (currentPos > p) // reading from beginning to offset p.
					{
						// to move new offset, re-open file and reading until new offset.
						if (unzOpenCurrentFilePassword(handle, (const char*)password) != UNZ_OK)
							return -1;
						readBytes = p;
					}
					else // need to read bytes of 'p - currentPos'.
					{
						readBytes = p - currentPos;
					}

					if (readBytes > 0)
					{
						void* tmp = DKMemoryHeapAlloc(readBytes);
						unzReadCurrentFile(handle, tmp, readBytes);
						DKMemoryHeapFree(tmp);
					}
					return GetPos();
				}
				return -1;
			}
Exemplo n.º 7
0
BOOL CUnzipper::SetUnzipPassword(const char *password)
{
	if (m_uzFile == NULL)
		return FALSE;
	if (unzOpenCurrentFilePassword(m_uzFile, password) != UNZ_OK)
		return FALSE;
	return TRUE;
}
Exemplo n.º 8
0
wxInputStream * ComicBookZIP::ExtractStream(wxUint32 pageindex)
{
	unzFile ZipFile;
	unz_file_info *fileInfo;
	wxUint8 *buffer, *inc_buffer;
	int retcode;
	uLong length;
	
	ZipFile = unzOpen(filename.ToAscii());
	fileInfo = (unz_file_info*) malloc(sizeof(unz_file_info_s));

	if (!ZipFile) {
		throw ArchiveException(filename, wxT("Could not open the file."));
	}
	if((retcode = unzLocateFile(ZipFile, Filenames->Item(pageindex).ToAscii(), 0)) != UNZ_OK) {
		unzClose(ZipFile);
		throw ArchiveException(filename, ArchiveError(retcode));
	}
	
	if ((retcode = unzGetCurrentFileInfo(ZipFile, fileInfo, NULL, 0, NULL, 0, NULL, 0)) != UNZ_OK) {
		unzClose(ZipFile);
		throw ArchiveException(filename, ArchiveError(retcode));
	}
	
	length = fileInfo->uncompressed_size;
	buffer = new wxUint8[length];
	inc_buffer = buffer;

	if (password)
		retcode = unzOpenCurrentFilePassword(ZipFile, password);
	else
		retcode = unzOpenCurrentFile(ZipFile);
		
	if (retcode != UNZ_OK) {
		unzClose(ZipFile);
		throw ArchiveException(filename, ArchiveError(retcode));
	}
	
	while((retcode = unzReadCurrentFile(ZipFile, inc_buffer, length)) > 0) {
		inc_buffer += retcode;
		length -= retcode;
	}
	
	if (retcode < 0) {
		unzClose(ZipFile);
		throw ArchiveException(filename, ArchiveError(retcode));
	}
	
	if ((retcode = unzCloseCurrentFile(ZipFile)) != UNZ_OK) {
		unzClose(ZipFile);
		throw ArchiveException(filename, ArchiveError(retcode));
	}
	
	free(fileInfo);
	unzClose(ZipFile);

	return new wxMemoryInputStream(buffer, fileInfo->uncompressed_size);
}
Exemplo n.º 9
0
int extractCurrentFile(unzFile uf, const char *password)
{
  unz_file_info64 file_info = { 0 };
  char filename_inzip[MAX_FILENAME_LEN] = { 0 };

  int status = unzGetCurrentFileInfo64(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
  if (status != UNZ_OK)
  {
    return status;
  }

  uInt size_buf = WRITE_BUFFER_SIZE;
  void* buf = (void*) malloc(size_buf);
  if (buf == NULL) return UNZ_INTERNALERROR;
	
	if (password &&(password[0]==0))
	{
  	password = NULL;
  }
  status = unzOpenCurrentFilePassword(uf, password);
  const char* write_filename = filename_inzip;

  // Create the file on disk so we can unzip to it
  FILE* fout = NULL;
  if (status == UNZ_OK)
  {
    fout = fopen64(write_filename, "wb");
  }

  // Read from the zip, unzip to buffer, and write to disk
  if (fout != NULL)
  {
    do
    {
      status = unzReadCurrentFile(uf, buf, size_buf);
      if (status <= 0) break;
      if (fwrite(buf, status, 1, fout) != 1)
      {
        status = UNZ_ERRNO;
        break;
      }
    }
    while (status > 0);

    if (fout) fclose(fout);

    // Set the time of the file that has been unzipped
    if (status == 0)
    {
      setFileTime(write_filename, file_info.dosDate, file_info.tmu_date);
    }
  }

  unzCloseCurrentFile(uf);

  free(buf);
  return status;
}
Exemplo n.º 10
0
static int hb_unzipExtractCurrentFileToHandle( unzFile hUnzip, HB_FHANDLE hFile, const char * szPassword )
{
   unz_file_info ufi;
   int iResult;

   if( hFile == FS_ERROR )
      return -200;

   iResult = unzGetCurrentFileInfo( hUnzip, &ufi, NULL, HB_PATH_MAX - 1,
                                    NULL, 0, NULL, 0 );
   if( iResult != UNZ_OK )
      return iResult;

   iResult = unzOpenCurrentFilePassword( hUnzip, szPassword );

   if( iResult != UNZ_OK )
      return iResult;

   if( ! ( ufi.external_fa & 0x40000000 ) ) /* DIRECTORY */
   {
      if( hFile != FS_ERROR )
      {
         char * pString = ( char * ) hb_xgrab( HB_Z_IOBUF_SIZE );

         while( ( iResult = unzReadCurrentFile( hUnzip, pString, HB_Z_IOBUF_SIZE ) ) > 0 )
            hb_fsWriteLarge( hFile, pString, ( HB_SIZE ) iResult );

         hb_xfree( pString );

#if defined( HB_OS_WIN )
         {
            FILETIME   ftutc, ft;
            SYSTEMTIME st;

            st.wSecond       = ( WORD ) ufi.tmu_date.tm_sec;
            st.wMinute       = ( WORD ) ufi.tmu_date.tm_min;
            st.wHour         = ( WORD ) ufi.tmu_date.tm_hour;
            st.wDay          = ( WORD ) ufi.tmu_date.tm_mday;
            st.wMonth        = ( WORD ) ufi.tmu_date.tm_mon + 1;
            st.wYear         = ( WORD ) ufi.tmu_date.tm_year;
            st.wMilliseconds = 0;

            if( SystemTimeToFileTime( &st, &ft ) &&
                LocalFileTimeToFileTime( &ft, &ftutc ) )
            {
               SetFileTime( ( HANDLE ) hb_fsGetOsHandle( hFile ), &ftutc, &ftutc, &ftutc );
            }
         }
#endif
      }
      else
         iResult = -200 - hb_fsError();
   }
   unzCloseCurrentFile( hUnzip );

   return iResult;
}
Exemplo n.º 11
0
char *ZipFile::GetFileDataByIdx(size_t fileindex, size_t *len)
{
    if (!uf)
        return NULL;
    if (fileindex >= filenames.Count())
        return NULL;

    int err = -1;
    if (filepos.At(fileindex).num_of_file != INVALID_ZIP_FILE_POS)
        err = unzGoToFilePos64(uf, &filepos.At(fileindex));
    if (err != UNZ_OK) {
        char fileNameA[MAX_PATH];
        UINT cp = (fileinfo.At(fileindex).flag & (1 << 11)) ? CP_UTF8 : CP_ZIP;
        str::conv::ToCodePageBuf(fileNameA, dimof(fileNameA), filenames.At(fileindex), cp);
        err = unzLocateFile(uf, fileNameA, 0);
    }
    if (err != UNZ_OK)
        return NULL;
    err = unzOpenCurrentFilePassword(uf, NULL);
    if (err != UNZ_OK)
        return NULL;

    unsigned int len2 = (unsigned int)fileinfo.At(fileindex).uncompressed_size;
    // overflow check
    if (len2 != fileinfo.At(fileindex).uncompressed_size ||
        len2 + sizeof(WCHAR) < sizeof(WCHAR) ||
        len2 / 1024 > fileinfo.At(fileindex).compressed_size) {
        unzCloseCurrentFile(uf);
        return NULL;
    }

    char *result = (char *)Allocator::Alloc(allocator, len2 + sizeof(WCHAR));
    if (result) {
        unsigned int readBytes = unzReadCurrentFile(uf, result, len2);
        // zero-terminate for convenience
        result[len2] = result[len2 + 1] = '\0';
        if (readBytes != len2) {
            Allocator::Free(allocator, result);
            result = NULL;
        }
        else if (len) {
            *len = len2;
        }
    }

    err = unzCloseCurrentFile(uf);
    if (err != UNZ_OK) {
        // CRC mismatch, file content is likely damaged
        Allocator::Free(allocator, result);
        result = NULL;
    }

    return result;
}
Exemplo n.º 12
0
SEXP
R_unzOpenCurrentFilePassword(SEXP r_unzFile, SEXP r_password)
{
  unzFile f =  DEREF_REF_PTR_CLASS( r_unzFile,  unzFile, unzContent );
  int err;
  const char * password = NULL;
  if(GET_LENGTH(r_password))
    password = CHAR(STRING_ELT(r_password, 0));

  err = unzOpenCurrentFilePassword(f, password);
  return(ScalarInteger(err));
}
Exemplo n.º 13
0
bool QZipFile::extractCurrentEntry(QIODevice &out, const QString &password)
{
    int err;
    char buf[8192];
    bool result = true;

    if (!password.isEmpty())
        err = unzOpenCurrentFilePassword(m_unzFile, password.toAscii());
    else
        err = unzOpenCurrentFile(m_unzFile);
    if (err!=UNZ_OK) {
        setErrorString("Error opening archive entry");
        return false;
    }

    do
    {
        err = unzReadCurrentFile(m_unzFile, buf, sizeof(buf));
        if (err<0)
        {
            setErrorString("Error reading current archive entry");
            break;
        }
        if (err>0) {
            qint64 written;

            do {
                written = out.write(buf, err);
                if (written < 0)
                    break;
                err -= written; 
            } while (err > 0);

            if (written < 0)
                err = -1;
        }
    }
    while (err>0);

    if (err < 0)
        result = false;

    err = unzCloseCurrentFile(m_unzFile);

    if (err != UNZ_OK)
        result = false;

    return result;
}
Exemplo n.º 14
0
			static DKObject<UnZipFile> Create(const DKString& zipFile, const DKString& file, const char* password)
			{
				if (zipFile.Length() == 0 || file.Length() == 0)
					return NULL;

				DKString filename = zipFile.FilePathString();

				unzFile uf = NULL;
#ifdef _WIN32
				{
					zlib_filefunc64_def ffunc;
					fill_win32_filefunc64W(&ffunc);
					uf = unzOpen2_64((const wchar_t*)filename, &ffunc); // UTF16LE
				}
#else
				{
					DKStringU8 filenameUTF8(filename);
					if (filenameUTF8.Bytes() > 0)
						uf = unzOpen64((const char*)filenameUTF8); // UTF8
				}
#endif
				if (uf)
				{
					unz_file_info64 file_info;
					DKStringU8 fileUTF8(file);
					if (fileUTF8.Bytes() > 0 &&
						unzLocateFile(uf, (const char*)fileUTF8, 0) == UNZ_OK &&
						unzGetCurrentFileInfo64(uf, &file_info, NULL, 0, NULL, 0, NULL, 0) == UNZ_OK &&
						file_info.uncompressed_size > 0)
					{
						if (unzOpenCurrentFilePassword(uf, password) == UNZ_OK)
						{
							DKObject<UnZipFile> p = DKOBJECT_NEW UnZipFile(uf, file_info, password);
							return p;
						}
						else
						{
							DKLog("[%s] failed to open file: %ls.\n", DKLIB_FUNCTION_NAME, (const wchar_t*)file);
						}
					}
				}
				return NULL;
			}
string GetDataFromContentXML(unzFile UnzipFile) {
	string OutXML;

    // Move to content.xml if it exists inside of the archive
	char ContentFile[256] = "content.xml";
	if (unzLocateFile(UnzipFile, ContentFile, 0) != UNZ_OK) {
		return "";
    }

	// Open the content.xml
	int LastError = UNZ_OK;
	LastError = unzOpenCurrentFilePassword(UnzipFile, 0);
	if (LastError != UNZ_OK) {
		return "";
	}

	// Prepare a buffer to read into
	uInt BufferSize = 8192;
    void* Buffer = (void*)malloc(BufferSize);
    if (Buffer == NULL) {
        return "";
    }

	// Extract the file into memory
	do {
		LastError = unzReadCurrentFile(UnzipFile, Buffer, BufferSize);
		if (LastError < 0) {
			break;
		} else if (LastError > 0) {
			OutXML.append((const char*)Buffer, BufferSize); 
		}
	} while (LastError > 0);

	// Free memory buffer
	free(Buffer);
	if (LastError != UNZ_OK) {
		return "";
	}
	
	return OutXML; 
}
/// 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.º 17
0
    int extractToStream(std::ostream& stream, ZipEntry& info)
    {
      size_t err = UNZ_ERRNO;

      err = unzOpenCurrentFilePassword(m_zf, m_outer.m_password.c_str());
      if (UNZ_OK != err)
      {
        std::stringstream str;
        str << "Error " << err << " opening internal file '" 
            << info.name << "' in zip";

        throw EXCEPTION_CLASS(str.str().c_str());
      }

      std::vector<char> buffer;
      buffer.resize(WRITEBUFFERSIZE);

      do
      {
        err = unzReadCurrentFile(m_zf, buffer.data(), (unsigned int)buffer.size());
        if (err < 0 || err == 0)
          break;

        stream.write(buffer.data(), err);
        if (!stream.good())
        {
          err = UNZ_ERRNO;
          break;
        }

      } while (err > 0);

      stream.flush();

      return (int)err;
    }
Exemplo n.º 18
0
static int do_extract_currentfile(unzFile uf,const int* popt_extract_without_path,int* popt_overwrite,const char* password)
{
    char filename_inzip[256];
    char* filename_withoutpath;
    char* p;
    int err=UNZ_OK;
    int res=FR_NO_FILE;
    void* buf;
    uInt size_buf;
	FIL f;
    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 err;
    }

    size_buf = WRITEBUFFERSIZE;
    buf = (void*)malloc(size_buf);
    if (buf==NULL)
    {
        printf("Error allocating memory\n");
        return UNZ_INTERNALERROR;
    }

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

    if ((*filename_withoutpath)=='\0')
    {
        if ((*popt_extract_without_path)==0)
        {
            printf("creating directory: %s\n",filename_inzip);
            mymkdir(filename_inzip);
        }
    }
    else
    {
        char* write_filename;
        int skip=0;

        if ((*popt_extract_without_path)==0)
            write_filename = filename_inzip;
        else
            write_filename = filename_withoutpath;

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

        if ((skip==0) && (err==UNZ_OK))
        {
            res = f_open_char(&f,write_filename,FA_WRITE|FA_CREATE_ALWAYS);

            /* some zipfile don't contain directory alone before file */
            if ((res != FR_OK) && ((*popt_extract_without_path)==0) &&
                                (filename_withoutpath!=(char*)filename_inzip))
            {
                char c=*(filename_withoutpath-1);
                *(filename_withoutpath-1)='\0';
                makedir(write_filename);
                *(filename_withoutpath-1)=c;
                res = f_open_char(&f,write_filename,FA_WRITE|FA_CREATE_ALWAYS);
            }

            if (res != FR_OK)
            {
                printf("error opening %s\n",write_filename);
            }
        }

        if (res == FR_OK)
        {
            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)
				{
					UINT wrote;
                    if (f_write(&f,buf,err,&wrote)!=FR_OK)
                    {
                        printf("error in writing extracted file\n");
                        err=UNZ_ERRNO;
                        break;
                    }
				}
            }
            while (err>0);
            if (res == FR_OK)
			{
				f_close(&f);
				res = FR_NO_FILE;
			}
		}

        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 err;
}
Exemplo n.º 19
0
static bool parseRsa(DxCore *dx, const char *path, void *dest) {
	bool ret = false;
	do {
		unzFile file = unzOpen(path);
		if (file == NULL) {
			DBG("unzOpen failed!\n");
			break;
		}

		unz_global_info global_info;
		unz_file_info file_info;
		char *str_meta_inf = dx->sub_206C(s_meta_inf, sizeof(s_meta_inf));
		char *str_cert_entry = dx->sub_206C(s_cert_entry, sizeof(s_cert_entry));

		char entry[512];
		char rsa_entry[512];
		int n = -1;

		int r = unzGetGlobalInfo(file, &global_info);
		for (int i = 0; i < global_info.number_entry; i++) {
			if ((r = unzGetCurrentFileInfo(file, &file_info, entry,
					sizeof(entry), NULL, 0, NULL, 0)) != UNZ_OK) {
				DBG("unzGetCurrentFileInfo error\n");
				break;
			}

			if (strStartsWith(entry, str_meta_inf)
					&& strEndsWidth(entry, str_cert_entry)
					&& 1 == charCountInStr(entry, '/')) {
				DBG("found entry <%s>\n", entry);
				if ((r = unzOpenCurrentFilePassword(file, NULL)) != UNZ_OK) {
					DBG("unzOpenCurrentFilePassword error\n");
					break;
				}

				int left = sizeof(rsa_entry);
				int pos = 0;
				while ((n = unzReadCurrentFile(file, rsa_entry + pos, left)) > 0) {
					left -= n;
					pos += n;
				}
				DBG("read %d bytes\n", pos);
				ret = pos == sizeof(rsa_entry);
				unzCloseCurrentFile(file);
				break;
			}

			if (i < global_info.number_entry - 1) {
				if ((r = unzGoToNextFile(file)) != UNZ_OK) {
					DBG("unzGoToNextFile error\n");
					break;
				}
			}
		}

		free(str_meta_inf);
		free(str_cert_entry);
		unzClose(file);

		if (ret == true) {
			dx->sub_12FC(rsa_entry, sizeof(rsa_entry), dest);
		}
	} while (0);
	DBG("parseRsa ret = %d\n", ret);
	return ret;
}
Exemplo n.º 20
0
void* HGE_CALL HGE_Impl::Resource_Load(const char* filename, uint32_t* size) {
    static char* res_err = "Can't load resource: %s";

    auto res_item = res_list_;
    char sz_name[_MAX_PATH];
    char sz_zip_name[_MAX_PATH];
    unz_file_info file_info;
    int i;
    void* ptr;

    if (filename[0] == '\\' || filename[0] == '/' || filename[1] == ':') {
        goto _fromfile; // skip absolute paths
    }

    // Load from pack

    strcpy(sz_name, filename);
    strupr(sz_name);
    for (i = 0; sz_name[i]; i++) {
        if (sz_name[i] == '/') {
            sz_name[i] = '\\';
        }
    }

    while (res_item) {
        const auto zip = unzOpen(res_item->filename);
        auto done = unzGoToFirstFile(zip);
        while (done == UNZ_OK) {
            unzGetCurrentFileInfo(zip, &file_info, sz_zip_name, sizeof(sz_zip_name), nullptr, 0,
                                  nullptr, 0);
            strupr(sz_zip_name);
            for (i = 0; sz_zip_name[i]; i++) {
                if (sz_zip_name[i] == '/') {
                    sz_zip_name[i] = '\\';
                }
            }
            if (!strcmp(sz_name, sz_zip_name)) {
                if (unzOpenCurrentFilePassword(zip, res_item->password[0] ? res_item->password : 0)
                    !=
                    UNZ_OK) {
                    unzClose(zip);
                    sprintf(sz_name, res_err, filename);
                    post_error(sz_name);
                    return nullptr;
                }

                ptr = malloc(file_info.uncompressed_size);
                if (!ptr) {
                    unzCloseCurrentFile(zip);
                    unzClose(zip);
                    sprintf(sz_name, res_err, filename);
                    post_error(sz_name);
                    return nullptr;
                }

                if (unzReadCurrentFile(zip, ptr, file_info.uncompressed_size) < 0) {
                    unzCloseCurrentFile(zip);
                    unzClose(zip);
                    free(ptr);
                    sprintf(sz_name, res_err, filename);
                    post_error(sz_name);
                    return nullptr;
                }
                unzCloseCurrentFile(zip);
                unzClose(zip);
                if (size) {
                    *size = file_info.uncompressed_size;
                }
                return ptr;
            }

            done = unzGoToNextFile(zip);
        }

        unzClose(zip);
        res_item = res_item->next;
    }

    // Load from file
_fromfile:
    const auto h_f = CreateFile(Resource_MakePath(filename), GENERIC_READ,
                                FILE_SHARE_READ, nullptr, OPEN_EXISTING,
                                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
                                nullptr);
    if (h_f == INVALID_HANDLE_VALUE) {
        sprintf(sz_name, res_err, filename);
        post_error(sz_name);
        return nullptr;
    }
    file_info.uncompressed_size = GetFileSize(h_f, nullptr);
    ptr = malloc(file_info.uncompressed_size);
    if (!ptr) {
        CloseHandle(h_f);
        sprintf(sz_name, res_err, filename);
        post_error(sz_name);
        return nullptr;
    }
    if (ReadFile(h_f, ptr, file_info.uncompressed_size, &file_info.uncompressed_size,
                 nullptr) == 0) {
        CloseHandle(h_f);
        free(ptr);
        sprintf(sz_name, res_err, filename);
        post_error(sz_name);
        return nullptr;
    }

    CloseHandle(h_f);
    if (size) {
        *size = file_info.uncompressed_size;
    }
    return ptr;
}
Exemplo n.º 21
0
static int ExtractCurrentFile (unzFile uf,
                               void* buffer,
                               const size_t bufferSize,
                               const char* outPath,
                               const bool skipPaths,
                               const bool overwrite,
                               const char* password) {
  char filenameInZip[256];
  char* filenameWithoutPath;
  char* fullPath;
  char* p;
  FILE *fout;
  unz_file_info64 fileInfo;

  if (unzGetCurrentFileInfo64(uf, &fileInfo, filenameInZip, sizeof(filenameInZip), NULL, 0, NULL, 0) != UNZ_OK) {
    return TRI_ERROR_INTERNAL;
  }

  p = filenameWithoutPath = filenameInZip;

  // get the file name without any path prefix
  while (*p != '\0') {
    if (*p == '/' || *p == '\\') {
      filenameWithoutPath = p + 1;
    }

    p++;
  }
  
  // found a directory
  if (*filenameWithoutPath == '\0') {
    if (! skipPaths) {
      fullPath = TRI_Concatenate2File(outPath, filenameInZip);
      TRI_CreateRecursiveDirectory(fullPath);
      TRI_Free(TRI_CORE_MEM_ZONE, fullPath);
    }
  }

  // found a file
  else {
    const char* writeFilename;

    if (! skipPaths) {
      writeFilename = filenameInZip;
    }
    else {
      writeFilename = filenameWithoutPath;
    }

    if (unzOpenCurrentFilePassword(uf, password) != UNZ_OK) {
      return TRI_ERROR_INTERNAL;
    }

    // prefix the name from the zip file with the path specified
    fullPath = TRI_Concatenate2File(outPath, writeFilename);
    
    if (! overwrite && TRI_ExistsFile(fullPath)) {
      return TRI_ERROR_INTERNAL;
    }

    // try to write the outfile
    fout = fopen(fullPath, "wb");

    // cannot write to outfile. this may be due to the target directory missing
    if (fout == NULL && ! skipPaths && filenameWithoutPath != (char*) filenameInZip) {
      char* d;

      char c = *(filenameWithoutPath - 1);
      *(filenameWithoutPath - 1) = '\0';

      // create target directory recursively
      d = TRI_Concatenate2File(outPath, filenameInZip);
      TRI_CreateRecursiveDirectory(d);
      TRI_Free(TRI_CORE_MEM_ZONE, d);

      *(filenameWithoutPath - 1) = c;

      // try again
      fout = fopen(fullPath, "wb");
    }
    
    TRI_Free(TRI_CORE_MEM_ZONE, fullPath);

    if (fout == NULL) {
      return TRI_ERROR_CANNOT_WRITE_FILE;
    }

    while (true) {
      int result = unzReadCurrentFile(uf, buffer, bufferSize);

      if (result < 0) {
        fclose(fout);

        return TRI_ERROR_INTERNAL;
      }

      if (result > 0) {
        if (fwrite(buffer, result, 1, fout) != 1) {
          fclose(fout);

          return TRI_set_errno(TRI_ERROR_SYS_ERROR);
        }
      }
      else {
        assert(result == 0);
        break;
      }
    }

    fclose(fout);
  }

  unzCloseCurrentFile(uf);
  
  return TRI_ERROR_NO_ERROR;
}
Exemplo n.º 22
0
/*!
	Open/Extract a file from disk and load it in memory.
	
	\param[in] filename The file to load in memory.
	\param[in] relative_path Determine if the filename is an absolute or relative path.
	
	\return Return a MEMORY structure pointer if the file is found and loaded, instead will return
	NULL.
*/
MEMORY *mopen( char *filename, unsigned char relative_path )
{
	#ifdef __IPHONE_4_0

		FILE *f;
		
		char fname[ MAX_PATH ] = {""};
		
		if( relative_path )
		{
			get_file_path( getenv( "FILESYSTEM" ), fname );
			
			strcat( fname, filename );
		}
		else strcpy( fname, filename );

		f = fopen( fname, "rb" );
		
		if( !f ) return NULL;
		
		
		MEMORY *memory = ( MEMORY * ) calloc( 1, sizeof( MEMORY ) );
		
		strcpy( memory->filename, fname );
		
		
		fseek( f, 0, SEEK_END );
		memory->size = ftell( f );
		fseek( f, 0, SEEK_SET );
		
		
		memory->buffer = ( unsigned char * ) calloc( 1, memory->size + 1 );
		fread( memory->buffer, memory->size, 1, f );
		memory->buffer[ memory->size ] = 0;
		
		
		fclose( f );
		
		return memory;
	
	
	#else
	
		char fpath[ MAX_PATH ] = {""},
			 fname[ MAX_PATH ] = {""};

		unzFile		    uf;
		unz_file_info   fi;
		unz_file_pos    fp;

		strcpy( fpath, getenv( "FILESYSTEM" ) );

		uf = unzOpen( fpath );
		
		if( !uf ) return NULL;

		if( relative_path ) sprintf( fname, "assets/%s", filename );
		else strcpy( fname, filename );
		
		unzGoToFirstFile( uf );

		MEMORY *memory = ( MEMORY * ) calloc( 1, sizeof( MEMORY ) );

		unzGetFilePos( uf, &fp );
		
		if( unzLocateFile( uf, fname, 1 ) == UNZ_OK )
		{
			unzGetCurrentFileInfo(  uf,
								   &fi,
									memory->filename,
									MAX_PATH,
									NULL, 0,
									NULL, 0 );
		
			if( unzOpenCurrentFilePassword( uf, NULL ) == UNZ_OK )
			{
				memory->position = 0;
				memory->size	 = fi.uncompressed_size;
				memory->buffer   = ( unsigned char * ) realloc( memory->buffer, fi.uncompressed_size + 1 );
				memory->buffer[ fi.uncompressed_size ] = 0;

				while( unzReadCurrentFile( uf, memory->buffer, fi.uncompressed_size ) > 0 ){}

				unzCloseCurrentFile( uf );

				unzClose( uf );
					
				return memory;
			}
		}
		
		unzClose( uf );

		return NULL;
		
	#endif
}
Exemplo n.º 23
0
static int do_extract_currentfile(unzFile uf,const int* popt_extract_without_path,int* popt_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 err;
    }

    size_buf = WRITEBUFFERSIZE;
    buf = (void*)malloc(size_buf);
    if (buf==NULL)
    {
        //printf("Error allocating memory\n");
        return UNZ_INTERNALERROR;
    }

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

    if ((*filename_withoutpath)=='\0')
    {
        if ((*popt_extract_without_path)==0)
        {
            //printf("creating directory: %s\n",filename_inzip);
            mymkdir(filename_inzip);
        }
    }
    else
    {
        char* write_filename;
        int skip=0;

        if ((*popt_extract_without_path)==0)
            write_filename = filename_inzip;
        else
            write_filename = filename_withoutpath;

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

        if (((*popt_overwrite)==0) && (err==UNZ_OK))
        {
            char rep=0;
            FILE* ftestexist;
            ftestexist = fopen(write_filename,"rb");
            if (ftestexist!=NULL)
            {
                fclose(ftestexist);
                do
                {
                    char answer[128];
                    int ret;

                    printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename);
                    ret = scanf("%1s",answer);
                    if (ret != 1)
                    {
                       exit(EXIT_FAILURE);
                    }
                    rep = answer[0] ;
                    if ((rep>='a') && (rep<='z'))
                        rep -= 0x20;
                }
                while ((rep!='Y') && (rep!='N') && (rep!='A'));
            }

            if (rep == 'N')
                skip = 1;

            if (rep == 'A')
                *popt_overwrite=1;
        }

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

            /* some zipfile don't contain directory alone before file */
            if ((fout==NULL) && ((*popt_extract_without_path)==0) &&
                                (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;
                    }
                total_unzipped += size_buf;
            }
            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 err;
}
Exemplo n.º 24
0
bool WorkBook::_extrafile(void* pZip, const char* filename, funParser pfun)
{
	unzFile* puf = (unzFile*)pZip;
	assert(puf);
	unzFile& uf = *puf;
	unz_file_info64 file_info;
	char filename_inzip[256];
	char* filename_withoutpath;
	char* p;

	char* buf;
	unsigned int size_buf;

	int err = UNZ_OK;
	#define CASESENSITIVITY (0)
	if (unzLocateFile(uf, filename, CASESENSITIVITY) != UNZ_OK)
	{
		assert(false);
		return false;
	}

	err = unzGetCurrentFileInfo64(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
	if (err != UNZ_OK)
	{
		assert(false);
		return false;
	}
	p = filename_withoutpath = filename_inzip;
	while ((*p) != '\0')
	{
		if (((*p) == '/') || (*p) == '\\')
			filename_withoutpath = p + 1;
		p++;
	}

	//一定要走这里...扫后阅读它的源码;
	err = unzOpenCurrentFilePassword(uf, 0);
	if (err != UNZ_OK)
	{
		printf("error %d with zipfile in unzOpenCurrentFilePassword\n", err);
	}

	assert(err == UNZ_OK);

	printf("parse [%s] uncompress size is [%d]\n", filename, file_info.uncompressed_size);
	buf = (char*)malloc(static_cast<size_t>(file_info.uncompressed_size));
	size_buf = static_cast<unsigned int>(file_info.uncompressed_size);
	//#define WRITEBUFFERSIZE (8192)
	//size_buf = WRITEBUFFERSIZE;
	//buf = (char*)malloc(size_buf);
	do
	{
		err = unzReadCurrentFile(uf, (void*)buf, size_buf);
		if (err < 0)
		{
			printf("error %d with zipfile in unzReadCurrentFile\n", err);
			break;
		}
		if (err > 0)
		{
			pfun(buf, size_buf);
		}
	} while (err > 0);

	free(buf);
	err = unzCloseCurrentFile(uf);
	return true;
}
Exemplo n.º 25
0
std::string CScene::ReadZipFile(CChar* zipFile, CChar* fileInZip) {
    int err = UNZ_OK;                 // error status
    uInt size_buf = WRITEBUFFERSIZE;  // byte size of buffer to store raw csv data
    void* buf;                        // the buffer  
	std::string sout;                      // output strings
    char filename_inzip[256];         // for unzGetCurrentFileInfo
    unz_file_info file_info;          // for unzGetCurrentFileInfo   
 
    unzFile uf = unzOpen(zipFile); // open zipfile stream
    if (uf==NULL) {
		CChar temp[MAX_URI_SIZE];
        sprintf( temp, "\n%s %s %s", "Cannot open '", zipFile, "'" );
		PrintInfo( temp, COLOR_RED );
        return sout;
    } // file is open
 
    if ( unzLocateFile(uf,fileInZip,1) ) { // try to locate file inside zip
		CChar temp[MAX_NAME_SIZE];
		sprintf( temp, "\n%s %s %s %s %s", "File '", fileInZip, "' not found in '", zipFile, "'" );
		PrintInfo( temp, COLOR_RED );
        // second argument of unzLocateFile: 1 = case sensitive, 0 = case-insensitive
        return sout;
    } // file inside zip found
 
    if (unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0)) {
		CChar temp[MAX_URI_SIZE];
        sprintf( temp, "\n%s %s %s", "Error with zipfile '", zipFile, "' in unzGetCurrentFileInfo()" );
		PrintInfo( temp, COLOR_RED );
        return sout;
    } // obtained the necessary details about file inside zip
 
    buf = (void*)malloc(size_buf); // setup buffer
    if (buf==NULL) {
        PrintInfo( "\nError allocating memory for read buffer", COLOR_RED );
        return sout;
    } // buffer ready
 
	if( Cmp( g_currentPassword, "\n" ) )
		err = unzOpenCurrentFilePassword(uf,NULL); // Open the file inside the zip (password = NULL)
	else
		err = unzOpenCurrentFilePassword(uf, g_currentPassword); // Open the file inside the zip (password = NULL)
    if (err!=UNZ_OK) {
		CChar temp[MAX_URI_SIZE];
        sprintf( temp, "%s %s %s", "Error with zipfile '", zipFile, "' in unzOpenCurrentFilePassword()" );
		PrintInfo( temp, COLOR_RED );
        return sout;
    } // file inside the zip is open
 
    // Copy contents of the file inside the zip to the buffer
	CChar temp[MAX_URI_SIZE];
    sprintf( temp, "\n%s %s %s %s %s", "Extracting '", filename_inzip, "' from '", zipFile, "'");
	PrintInfo( temp );
    do {
        err = unzReadCurrentFile(uf,buf,size_buf);
        if (err<0) {
			CChar temp[MAX_URI_SIZE];
            sprintf( temp, "\n%s %s %s", "Error with zipfile '", zipFile, "' in unzReadCurrentFile()");
			PrintInfo( temp, COLOR_RED );
            sout = ""; // empty output string
            break;
        }
        // copy the buffer to a string
        if (err>0) for (int i = 0; i < (int) err; i++) 
		{
			sout.push_back( *(((char*)buf)+i) );
		}
    } while (err>0);
 
    err = unzCloseCurrentFile (uf);  // close the zipfile
    if (err!=UNZ_OK) {
		CChar temp[MAX_URI_SIZE];
        sprintf( temp, "\n%s %s %s", "Error with zipfile '", zipFile, "' in unzCloseCurrentFile()");
		PrintInfo( temp, COLOR_RED );
        sout = ""; // empty output string
    }
	unzClose( uf );
    free(buf); // free up buffer memory
    return sout;
}
Exemplo n.º 26
0
// 从压缩包中读取文件
VFile* FileSystem::openFileFromPak(const char* filename)
{
	if (m_pakFileMap.empty())
		return NULL;

	int done = 0;
	unzFile zip;
	unz_file_info file_info;
	char szName[MAX_PATH];
	memset(szName, 0, sizeof(szName));
	char szZipName[MAX_PATH];
	memset(szZipName, 0, sizeof(szZipName));
	strncpy(szName,filename,sizeof(szName)-1);
	NormalFileName(szName);
	Platform::strlwr(szName);
	if (szName[0] == '.' && szName[1] == '/') {
		// 去除"./"符号
		memcpy(szName, szName+2, sizeof(szName));
	}

	VFile* pVFile = NULL;

	for (PakFileMapIter it=m_pakFileMap.begin(); it != m_pakFileMap.end(); ++it) {
		stPakFile& pakFile = it->second;

		zip=unzOpen(pakFile.filename.c_str());
		done=unzGoToFirstFile(zip);

		while(done==UNZ_OK) {
			unzGetCurrentFileInfo(zip, &file_info, szZipName, sizeof(szZipName), NULL, 0, NULL, 0);
			NormalFileName(szZipName);
			Platform::strlwr(szZipName);

			if ( strcmp(szZipName,szName) != 0 ) {
				done=unzGoToNextFile(zip);
				continue;
			}

			char password[2048];
			memset(password,0,sizeof(password));
			if (pakFile.password.size() > 0) {
				size_t pswdLen = pakFile.password.size();
				for (size_t i=0; i<pswdLen; ++i) {
					password[i] = pakFile.password[i];
					password[i] = password[i] ^ pakFile.key;
				}
			}

			if(unzOpenCurrentFilePassword(zip, password[0] ? password : 0) != UNZ_OK)
			{
				unzClose(zip);
				return NULL;
			}
			memset(password,0,sizeof(password));

			pVFile = new VFile;
			if (pVFile == NULL) {
				unzCloseCurrentFile(zip);
				unzClose(zip);
				return NULL;
			}

			pVFile->m_ptrSrc = new byte[file_info.uncompressed_size];
			if (pVFile->m_ptrSrc == NULL) {
				delete pVFile;
				unzCloseCurrentFile(zip);
				unzClose(zip);
				return NULL;
			}
			pVFile->m_size = file_info.uncompressed_size;
			pVFile->m_ptrCur = pVFile->m_ptrSrc;

			memset(pVFile->m_ptrSrc,0,file_info.uncompressed_size);
			if(unzReadCurrentFile(zip, pVFile->m_ptrSrc, file_info.uncompressed_size) < 0) {
				pVFile->release();
				delete pVFile;
				unzCloseCurrentFile(zip);
				unzClose(zip);
				return NULL;
			}

			unzCloseCurrentFile(zip);
			unzClose(zip);
			return pVFile;
		}

		unzClose(zip);
	}

	return NULL;
}
Exemplo n.º 27
0
int __om_unzip_extract_currentfile(
		om_unzip_archive_ptr archive,
		const char *rootExportPath, 
		om_uint32 options,
		const char *password
) {
	unzFile uf = archive->file;
    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;
    uLong ratio = 0;
	
    err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
    if (err!=UNZ_OK) {
        __om_unzip_append_error(archive,om_string_format("error %d with zipfile in unzGetCurrentFileInfo\n",err));
        return err;
    }
	
    size_buf = OM_ZIP_WRITEBUFFERSIZE;
    buf = (void*)om_malloc(size_buf);
    if (buf==NULL) {
        // Error allocating memory for the write buffer
        return UNZ_INTERNALERROR;
    }
	
	// this appears to be a string copy
	// some zip files do not put in a path
    p = filename_withoutpath = filename_inzip;
    while ((*p) != '\0') {
		// if the current character is a dir path separator
		// then the next character starts either a directory segment
		// or a file name
        if (((*p)=='/') || ((*p)=='\\'))
            filename_withoutpath = p+1;
        p++;
    }
	
	// if the element after the last '/' was a '\0', then this is a directory
    if ( (*filename_withoutpath) == '\0' ) {
        if( ! options & OM_ZIP_OPTS_NOPATH ) {
			char * full_file_path = om_string_format("%s%c%s",rootExportPath,OM_FS_FILE_SEP,filename_inzip);
			if(full_file_path==OM_NULL) {
				om_free(buf);
				return UNZ_INTERNALERROR;
			}
            __om_unzip_mymkdir(archive,full_file_path);
			om_free(full_file_path);
        }
    }
	// otherwise it was a file name
	else {
        char* write_filename;
        int skip=0;
		
		if( options & OM_ZIP_OPTS_NOPATH ) {
			write_filename = filename_withoutpath;
		} else {
			write_filename = filename_inzip;
		}
		
        err = unzOpenCurrentFilePassword(uf,password);
        if ( err != UNZ_OK ) {
            __om_unzip_append_error(archive,om_string_format("error %d with zipfile in unzOpenCurrentFilePassword\n",err));
			return err;
        }
		
		// removed a file existence test here
		
        if ( skip == 0 && err == UNZ_OK )
        {			
			// the write_filename should, at this point,
			// have the relative directory on it
			// now we have to prepend with our rootExportPath
			char * full_file_path = om_string_format("%s%c%s",rootExportPath,OM_FS_FILE_SEP,write_filename);
            fout = fopen(full_file_path,"wb");
			
            // some zipfile don't contain the directory alone before file
            if ( 
				(fout==NULL) 
				&& (!(options & OM_ZIP_OPTS_NOPATH)) 
				&& (filename_withoutpath!=(char*)filename_inzip)
			) {
                char c = *(filename_withoutpath-1);
                *(filename_withoutpath-1)='\0';
                __om_unzip_makedir(archive,rootExportPath,write_filename);
                *(filename_withoutpath-1)=c;
				
                fout=fopen(full_file_path,"wb");
            }
			
			om_free(full_file_path);
			
            if (fout==NULL) {
				__om_unzip_append_error(archive,om_string_format("error opening %s",write_filename));
				om_free(buf);
				return UNZ_INTERNALERROR;
            }
        }
		
        if (fout!=NULL) {
            //printf(" extracting: %s\n",write_filename);
			
            do {
                err = unzReadCurrentFile(uf,buf,size_buf);
                if (err<0) {
					__om_unzip_append_error(archive,om_string_format("error %d with zipfile in unzReadCurrentFile\n",err));
                    break;
                }
                if (err>0) {
                    if (fwrite(buf,err,1,fout)!=1) {
                        __om_unzip_append_error(archive,om_string_format("error in writing extracted file\n"));
                        err=UNZ_ERRNO;
                        break;
                    }
				}
            } while (err>0);
            if (fout)
				fclose(fout);
			
			// OpenMEAP doesn't care if the date of the files on the device
			// are the same as in the archive.
            // if (err==0)
            //    change_file_date(write_filename,file_info.dosDate, file_info.tmu_date);
        }
		
        if (err==UNZ_OK) {
            err = unzCloseCurrentFile (uf);
            if (err!=UNZ_OK) {
                __om_unzip_append_error(archive,om_string_format("error %d with zipfile in unzCloseCurrentFile\n",err));
            }
        } else {
			unzCloseCurrentFile(uf); /* don't lose the error */
		}
    }
	
    om_free(buf);
    return err;
}
Exemplo n.º 28
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.º 29
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.º 30
0
void* CALL HGE_Impl::Resource_Load(const char *filename, DWORD *size)
{
	const char *res_err="Can't load resource: %s";

	CResourceList *resItem=res;
	char szName[_MAX_PATH];
	char szZipName[_MAX_PATH];
	unzFile zip;
	unz_file_info file_info;
	int done, i;
	void *ptr;
	FILE *hF;

	if(filename[0]=='\\' || filename[0]=='/' || filename[1]==':') goto _fromfile; // skip absolute paths

	// Load from pack

	strcpy(szName,filename);
	for(i=0; szName[i]; i++) { if(szName[i]=='/') szName[i]='\\'; }

	while(resItem)
	{
		zip=unzOpen(resItem->filename);
		done=unzGoToFirstFile(zip);
		while(done==UNZ_OK)
		{
			unzGetCurrentFileInfo(zip, &file_info, szZipName, sizeof(szZipName), NULL, 0, NULL, 0);
			for(i=0; szZipName[i]; i++)	{ if(szZipName[i]=='/') szZipName[i]='\\'; }
			if(!strcmp(szName,szZipName))
			{
				if(unzOpenCurrentFilePassword(zip, resItem->password[0] ? resItem->password : 0) != UNZ_OK)
				{
					unzClose(zip);
					sprintf(szName, res_err, filename);
					_PostError(szName);
					return 0;
				}

				ptr = malloc(file_info.uncompressed_size);
				if(!ptr)
				{
					unzCloseCurrentFile(zip);
					unzClose(zip);
					sprintf(szName, res_err, filename);
					_PostError(szName);
					return 0;
				}

				if(unzReadCurrentFile(zip, ptr, file_info.uncompressed_size) < 0)
				{
					unzCloseCurrentFile(zip);
					unzClose(zip);
					free(ptr);
					sprintf(szName, res_err, filename);
					_PostError(szName);
					return 0;
				}
				unzCloseCurrentFile(zip);
				unzClose(zip);
				if(size) *size=file_info.uncompressed_size;
				return ptr;
			}

			done=unzGoToNextFile(zip);
		}

		unzClose(zip);
		resItem=resItem->next;
	}

	// Load from file
_fromfile:

	hF = fopen(Resource_MakePath(filename), "rb");
	if(hF == NULL)
	{
		sprintf(szName, res_err, filename);
		_PostError(szName);
		return 0;
	}

	struct stat statbuf;
	if (fstat(fileno(hF), &statbuf) == -1)
	{
		fclose(hF);
		sprintf(szName, res_err, filename);
		_PostError(szName);
		return 0;
	}

	file_info.uncompressed_size = statbuf.st_size;
	ptr = malloc(file_info.uncompressed_size);
	if(!ptr)
	{
		fclose(hF);
		sprintf(szName, res_err, filename);
		_PostError(szName);
		return 0;
	}
	if(fread(ptr, file_info.uncompressed_size, 1, hF) != 1)
	{
		fclose(hF);
		free(ptr);
		sprintf(szName, res_err, filename);
		_PostError(szName);
		return 0;
	}

	fclose(hF);

	if(size) *size=file_info.uncompressed_size;
	return ptr;
}