Exemplo n.º 1
0
static int hb_zipStoreFileHandle( zipFile hZip, HB_FHANDLE hFile, const char * szName, const char * szPassword, const char * szComment )
{
   char *       szZipName;
   HB_SIZE      nLen;
   zip_fileinfo zfi;
   int          iResult;
   HB_BOOL      fText;
   HB_U32       ulCRC;

   if( hFile == FS_ERROR || szName == NULL )
      return -200;

   /* change path separators to '/' */
   szZipName = hb_strdup( szName );

   nLen = strlen( szZipName );
   while( nLen-- )
   {
      if( szZipName[ nLen ] == '\\' )
         szZipName[ nLen ] = '/';
   }

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

   zfi.external_fa      = 0x81B60020;
   zfi.tmz_date.tm_sec  = 0;
   zfi.tmz_date.tm_min  = 0;
   zfi.tmz_date.tm_hour = 0;
   zfi.tmz_date.tm_mday = 1;
   zfi.tmz_date.tm_mon  = 0;
   zfi.tmz_date.tm_year = 0;

   ulCRC = 0;
   fText = HB_FALSE;
   if( szPassword && hb_zipGetFileInfoFromHandle( hFile, &ulCRC, &fText ) )
      zfi.internal_fa = fText ? 1 : 0;
   else
      /* TODO: zip.exe test: 0 for binary file, 1 for text. Does not depend on
         extension. We should analyse content of file to determine this??? */
      zfi.internal_fa = 0;

   iResult = zipOpenNewFileInZip3( hZip, szZipName, &zfi, NULL, 0, NULL, 0, szComment,
                                   Z_DEFLATED, Z_DEFAULT_COMPRESSION, 0,
                                   -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
                                   szPassword, ulCRC );
   if( iResult == 0 )
   {
      char * pString = ( char * ) hb_xgrab( HB_Z_IOBUF_SIZE );
      hb_fsSeek( hFile, 0, FS_SET );
      while( ( nLen = hb_fsReadLarge( hFile, pString, HB_Z_IOBUF_SIZE ) ) > 0 )
         zipWriteInFileInZip( hZip, pString, ( unsigned ) nLen );
      hb_xfree( pString );

      zipCloseFileInZip( hZip );
   }

   hb_xfree( szZipName );
   return iResult;
}
Exemplo n.º 2
0
extern MINIZIP_EXPORT int zipOpenNewFileInZip2(zipFile file,const char* filename,const zip_fileinfo* zipfi,
                                               const void* extrafield_local,uInt size_extrafield_local,
                                               const void* extrafield_global,uInt size_extrafield_global,
                                               const char* comment,int method,int level,int raw)

{
  return zipOpenNewFileInZip3 (file, filename, zipfi,
                               extrafield_local, size_extrafield_local,
                               extrafield_global, size_extrafield_global,
                               comment, method, level, raw,
                               -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
                               0, 0);
}
Exemplo n.º 3
0
int RSAZCryptor::zipToFile(unsigned contentLength, void const *content, const char* fileToBeZipped, const char* fileOut)
{
    unsigned len=(int)strlen(fileOut);
    char* filename_try = (char*)malloc(len+16);
   if (filename_try==NULL)
   {
        return ZIP_INTERNALERROR;
   }

    strcpy(filename_try, fileOut);

    bool dot_found = false;
    for (unsigned i=0; i<len; i++)
    {
        if (filename_try[i]=='.')
        {
             dot_found=true;
             break;
        }
    }

    if (!dot_found)
        strcat(filename_try,".zip");

    zipFile zf;
    int opt_overwrite=0; //?1

#ifdef USEWIN32IOAPI
    zlib_filefunc_def ffunc;
    fill_win32_filefunc(&ffunc);
    zf = zipOpen2(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc);
#else
    zf = zipOpen(filename_try,(opt_overwrite==2) ? 2 : 0);
#endif

    int err=0;
    if (zf == NULL)
    {
        printf("error opening %s\n",filename_try);
        err= ZIP_ERRNO;
    }

    zip_fileinfo zi;
    zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
    zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
    zi.dosDate = 0;
    zi.internal_fa = 0;
    zi.external_fa = 0;

    err = zipOpenNewFileInZip3(zf,fileToBeZipped,&zi,
                            NULL,0,NULL,0,NULL /* comment*/,
                            Z_DEFLATED,
                            Z_DEFAULT_COMPRESSION,0,
                            /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */
                            -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
                            NULL, 0);

    if (err != ZIP_OK)
        printf("error in opening %s in zipfile\n",fileToBeZipped);

    if (contentLength>0)
    {
        err = zipWriteInFileInZip (zf,content,contentLength);
        if (err<0)
        {
            printf("error in writing %s in the zipfile\n", fileToBeZipped);
        }
    }

    if (err<0)
        err=ZIP_ERRNO;
    else
    {
        err = zipCloseFileInZip(zf);
        if (err!=ZIP_OK)
            printf("error in closing %s in the zipfile\n", fileToBeZipped);
    }

    if (zipClose(zf,NULL) != ZIP_OK)
        printf("error in closing %s\n",filename_try);

    free(filename_try);
    return 0;
}
Exemplo n.º 4
0
int RSAZCryptor::zipToFile(const char* zipFileName, bool cleanFileListAfterUsed)
{
    unsigned len=(int)strlen(zipFileName);
    char* filename_try = (char*)malloc(len+16);
   if (filename_try==NULL)
   {
        return ZIP_INTERNALERROR;
   }

    strcpy(filename_try, zipFileName);

    bool dot_found = false;
    for (unsigned i=0; i<len; i++)
    {
        if (filename_try[i]=='.')
        {
             dot_found=true;
             break;
        }
    }

    if (!dot_found)
        strcat(filename_try,".zip");

    zipFile zf;
    int opt_overwrite=0; //?1

#ifdef USEWIN32IOAPI
    zlib_filefunc_def ffunc;
    fill_win32_filefunc(&ffunc);
    zf = zipOpen2(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc);
#else
    zf = zipOpen(filename_try,(opt_overwrite==2) ? 2 : 0);
#endif

    int err=0;
    if (zf == NULL)
    {
        printf("error opening %s\n",filename_try);
        err= ZIP_ERRNO;
    }

    unsigned count = 0;
    linkedlist_filetozip* pFileList = m_filesToBeZIP;
    while (pFileList && (err==ZIP_OK))
    {
        count++;

        unsigned contentLength = pFileList->content_length;
        void const *content = pFileList->file_content;
        char* fileName = NULL;
        char fileName0[16];

        if (pFileList->file_name)
            fileName = pFileList->file_name;
        else
        {
            sprintf(fileName0, "file%d", count);
            fileName = fileName0;
        }
        struct tm * ts = gmtime(&pFileList->file_time);

        zip_fileinfo zi;
        zi.tmz_date.tm_sec = ts->tm_sec;
        zi.tmz_date.tm_min = ts->tm_min;   
        zi.tmz_date.tm_hour = ts->tm_hour; 
        zi.tmz_date.tm_mday = ts->tm_mday;  
        zi.tmz_date.tm_mon = ts->tm_mon;
        zi.tmz_date.tm_year = ts->tm_year;  

        zi.dosDate = 0;
        zi.internal_fa = 0;
        zi.external_fa = 0;

        err = zipOpenNewFileInZip3(zf,fileName,&zi,
                                NULL,0,NULL,0,NULL /* comment*/,
                                Z_DEFLATED,
                                Z_DEFAULT_COMPRESSION,0,
                                /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */
                                -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
                                NULL, 0);

        if (err != ZIP_OK)
            printf("error in opening %s in zipfile\n",fileName);

        if (contentLength>0)
        {
            err = zipWriteInFileInZip (zf,content,contentLength);
            if (err<0)
            {
                printf("error in writing %s in the zipfile\n", fileName);
            }
        }

        if (err<0)
            err=ZIP_ERRNO;
        else
        {
            err = zipCloseFileInZip(zf);
            if (err!=ZIP_OK)
                printf("error in closing %s in the zipfile\n", fileName);
        }

        pFileList = pFileList->next_filetozip;
    }

    if (zipClose(zf,NULL) != ZIP_OK)
        printf("error in closing %s\n",filename_try);

    free(filename_try);

    if (cleanFileListAfterUsed)
    {
        cleanFileList(m_filesToBeZIP);
        m_filesToBeZIP = NULL;
    }
    return 0;
}
Exemplo n.º 5
0
CInt CScene::WriteZipFile(CChar* zipFileName, CChar* fileInZipName, CChar* fileInZipPath, const CChar* password )
{
    FILE * fin;
	fin = fopen(fileInZipPath,"rb");
    if (fin==NULL)
    {
		CChar temp[MAX_NAME_SIZE];
		sprintf(temp, "\n%s %s %s", "Error in opening",fileInZipPath, "for reading");
		PrintInfo( temp, COLOR_RED );
		return -1;
   }

    int size_buf=WRITEBUFFERSIZE;
    unsigned long crcFile=0;
    unsigned long size_read = 0;
    zip_fileinfo zi;
    int err=0;
    void* buf=NULL;
    buf = (void*)malloc(size_buf);
    if (buf==NULL)
    {
		PrintInfo("\nWriteZipFile: Error allocating memory", COLOR_RED);
        return -1;
    }
	zipFile zf;
	zf = zipOpen(zipFileName, 0);
    if (zf == NULL)
    {
		CChar temp[MAX_NAME_SIZE];
		sprintf(temp, "\n%s%s", "Error opening ",zipFileName);
		PrintInfo( temp, COLOR_RED );
		free(buf);
        return -1;
    }
    if (password != NULL)
		GetFileCrc(fileInZipPath,buf,size_buf,&crcFile);

    err = zipOpenNewFileInZip3(zf,fileInZipName,&zi,
                     NULL,0,NULL,0,NULL /* comment*/,
                     Z_DEFLATED,  Z_DEFAULT_COMPRESSION ,0,
                     -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
                     password,crcFile);
    if (err != ZIP_OK)
	{
		CChar temp[MAX_NAME_SIZE];
        sprintf(temp, "\n%s %s %s", "Error in opening",fileInZipPath, "in zipfile");
		zipCloseFileInZip(zf);
		zipClose(zipOpen, "Vanda Engine 1.4");
		free(buf);
		return -1;
	}
   // else
   // {
   //     fin = fopen(fileInZipPath,"rb");
   //     if (fin==NULL)
   //     {
			//CChar temp[MAX_NAME_SIZE];
			//sprintf(temp, "\n%s %s %s", "Error in opening",fileInZipPath, "for reading");
			//PrintInfo( temp, COLOR_RED );
			//zipCloseFileInZip(zf);
			//zipClose(zf, "Vanda Engine 1.4");
			//free(buf);
			//return -1;
   //     }
   // }
    do
    {
        err = ZIP_OK;
        size_read = (int)fread(buf,1,size_buf,fin);
        if (size_read < (unsigned long)size_buf)
		{
			if (feof(fin)==0)
			{
				CChar temp[MAX_NAME_SIZE];
				sprintf(temp, "\n%s%s", "Error in reading ",fileInZipPath);
				zipCloseFileInZip(zf);
				zipClose(zf, "Vanda Engine 1.4");
				free(buf);
				return -1;
			}
		}

        if (size_read>0)
        {
            err = zipWriteInFileInZip (zf,buf,size_read);
            if (err<0)
            {
				CChar temp[MAX_NAME_SIZE];

                sprintf( temp, "\n%s%s%s", "Error in writing ", fileInZipPath, " in the zipfile");
				zipCloseFileInZip(zf);
				zipClose(zf, "Vanda Engine 1.4");
				free(buf);
				return -1;
            }
        }
    } while ((err == ZIP_OK) && (size_read>0));

    if (fin)
        fclose(fin);
	zipCloseFileInZip(zf);
	zipClose(zf,"Vanda Engine 1.4");
    free(buf);
	return 1;
}
Exemplo n.º 6
0
/*
========================
idZipBuilder::CleanSourceFolder

this folder is assumed to be a path under FSPATH_BASE
========================
*/
bool idZipBuilder::AddFile( zipFile zf, idFile_Memory* src, bool deleteFile )
{
	// add each file to the zip file
	zip_fileinfo zi;
	memset( &zi, 0, sizeof( zip_fileinfo ) );
	
	
	src->MakeReadOnly();
	
	idLib::PrintfIf( zip_verbosity.GetBool(), "...Adding: '%s' ", src->GetName() );
	
	int compressionMethod = Z_DEFLATED;
	if( IsUncompressed( src->GetName() ) )
	{
		compressionMethod = Z_NO_COMPRESSION;
	}
	
	int errcode = zipOpenNewFileInZip3( zf, src->GetName(), &zi, NULL, 0, NULL, 0, NULL /* comment*/,
										compressionMethod,	DEFAULT_COMPRESSION_LEVEL, 0, -MAX_WBITS, DEF_MEM_LEVEL,
										Z_DEFAULT_STRATEGY, NULL /*password*/, 0 /*fileCRC*/ );
										
	if( errcode != ZIP_OK )
	{
		idLib::Warning( "Error opening file in zipfile!" );
		if( deleteFile )
		{
			src->Clear( true );
			delete src;
		}
		return false;
	}
	else
	{
		// copy the file data into the zip file
		idTempArray<byte> buffer( DEFAULT_WRITEBUFFERSIZE );
		size_t total = 0;
		while( size_t bytesRead = src->Read( buffer.Ptr(), buffer.Size() ) )
		{
			if( bytesRead > 0 )
			{
				errcode = zipWriteInFileInZip( zf, buffer.Ptr(), ( unsigned int )bytesRead );
				if( errcode != ZIP_OK )
				{
					idLib::Warning( "Error writing to zipfile (%lu bytes)!", bytesRead );
					continue;
				}
			}
			total += bytesRead;
		}
		assert( total == ( size_t )src->Length() );
	}
	
	errcode = zipCloseFileInZip( zf );
	if( errcode != ZIP_OK )
	{
		idLib::Warning( "Error zipping source file!" );
		if( deleteFile )
		{
			src->Clear( true );
			delete src;
		}
		return false;
	}
	idLib::PrintfIf( zip_verbosity.GetBool(), "\n" );
	if( deleteFile )
	{
		src->Clear( true );
		delete src;
	}
	return true;
}
Exemplo n.º 7
0
/*
========================
idZipBuilder::CreateZipFileFromFiles
========================
*/
bool idZipBuilder::CreateZipFileFromFiles( const idList< idFile_Memory* >& srcFiles )
{
	if( zipFileName.IsEmpty() )
	{
		idLib::Warning( "[%s] - invalid parameters!", __FUNCTION__ );
		return false;
	}
	
	// need to clear the filesystem's zip cache before we can open and write
	//fileSystem->ClearZipCache();
	
	idLib::Printf( "Building zip file: '%s'\n", zipFileName.c_str() );
	
	// do not allow overwrite as this should be a tempfile attempt to check the file out
	if( !Sys_IsFileWritable( zipFileName ) )
	{
		idLib::PrintfIf( zip_verbosity.GetBool(), "File %s not writable, cannot proceed.\n", zipFileName.c_str() );
		return false;
	}
	
	// open the zip file
	zipFile zf = zipOpen( zipFileName, 0 );
	if( zf == NULL )
	{
		idLib::Warning( "[%s] - error opening file '%s'!", __FUNCTION__, zipFileName.c_str() );
		return false;
	}
	
	// add the files to the zip file
	for( int i = 0; i < srcFiles.Num(); i++ )
	{
	
		// add each file to the zip file
		zip_fileinfo zi;
		memset( &zi, 0, sizeof( zip_fileinfo ) );
		
		idFile_Memory* src = srcFiles[i];
		src->MakeReadOnly();
		
		idLib::PrintfIf( zip_verbosity.GetBool(), "...Adding: '%s' ", src->GetName() );
		
		int compressionMethod = Z_DEFLATED;
		if( IsUncompressed( src->GetName() ) )
		{
			compressionMethod = 0;
		}
		
		int errcode = zipOpenNewFileInZip3( zf, src->GetName(), &zi, NULL, 0, NULL, 0, NULL /* comment*/,
											compressionMethod,	DEFAULT_COMPRESSION_LEVEL, 0, -MAX_WBITS, DEF_MEM_LEVEL,
											Z_DEFAULT_STRATEGY, NULL /*password*/, 0 /*fileCRC*/ );
											
		if( errcode != ZIP_OK )
		{
			idLib::Warning( "Error opening file in zipfile!" );
			continue;
		}
		else
		{
			// copy the file data into the zip file
			idTempArray<byte> buffer( DEFAULT_WRITEBUFFERSIZE );
			size_t total = 0;
			while( size_t bytesRead = src->Read( buffer.Ptr(), buffer.Size() ) )
			{
				if( bytesRead > 0 )
				{
					errcode = zipWriteInFileInZip( zf, buffer.Ptr(), ( unsigned int )bytesRead );
					if( errcode != ZIP_OK )
					{
						idLib::Warning( "Error writing to zipfile (%lu bytes)!", bytesRead );
						continue;
					}
				}
				total += bytesRead;
			}
			assert( total == ( size_t )src->Length() );
		}
		
		errcode = zipCloseFileInZip( zf );
		if( errcode != ZIP_OK )
		{
			idLib::Warning( "Error zipping source file!" );
			continue;
		}
		idLib::PrintfIf( zip_verbosity.GetBool(), "\n" );
	}
	
	// close the zip file
	int closeError = zipClose( zf, zipFileName );
	if( closeError != ZIP_OK )
	{
		idLib::Warning( "[%s] - error closing file '%s'!", __FUNCTION__, zipFileName.c_str() );
		return false;
	}
	
	idLib::PrintfIf( zip_verbosity.GetBool(), "Done.\n" );
	
	return true;
}
Exemplo n.º 8
0
/*
========================
idZipBuilder::CreateZipFile
========================
*/
bool idZipBuilder::CreateZipFile( bool appendFiles )
{
#if 0
//#ifdef ID_PC
	if( zipFileName.IsEmpty() || sourceFolderName.IsEmpty() )
	{
		idLib::Warning( "[%s] - invalid parameters!", __FUNCTION__ );
		return false;
	}
	
	// need to clear the filesystem's zip cache before we can open and write
	//fileSystem->ClearZipCache();
	
	idLib::Printf( "Building zip file: '%s'\n", zipFileName.c_str() );
	
	sourceFolderName.StripTrailing( "\\" );
	sourceFolderName.StripTrailing( "/" );
	
#if 0
	// attempt to check the file out
	if( !Sys_IsFileWritable( zipFileName ) )
	{
		if( ( idLib::sourceControl == NULL ) || !idLib::sourceControl->CheckOut( zipFileName ) )
		{
			idLib::Warning( "READONLY zip file couldn't be checked out: %s", zipFileName.c_str() );
		}
		else
		{
			idLib::Printf( "Checked out: %s\n", zipFileName.c_str() );
		}
	}
#endif
	
	// if not appending, set the file size to zero to "create it from scratch"
	if( !appendFiles )
	{
		idLib::PrintfIf( zip_verbosity.GetBool(), "Overwriting zip file: '%s'\n", zipFileName.c_str() );
		idFile* zipFile = fileSystem->OpenExplicitFileWrite( zipFileName );
		if( zipFile != NULL )
		{
			delete zipFile;
			zipFile = NULL;
		}
	}
	else
	{
		idLib::PrintfIf( zip_verbosity.GetBool(), "Appending to zip file: '%s'\n", zipFileName.c_str() );
	}
	
	// enumerate the files to zip up in the source folder
	idStrStatic< MAX_OSPATH > relPath;
	relPath =
		fileSystem->OSPathToRelativePath( sourceFolderName );
	idFileList* files = fileSystem->ListFilesTree( relPath, "*.*" );
	
	// check to make sure that at least one file will be added to the package
	int atLeastOneFilteredFile = false;
	for( int i = 0; i < files->GetNumFiles(); i++ )
	{
		idStr filename = files->GetFile( i );
		
		if( !IsFiltered( filename ) )
		{
			atLeastOneFilteredFile = true;
			break;
		}
	}
	if( !atLeastOneFilteredFile )
	{
		// although we didn't actually update/create a zip file, it's because no files would be added anyway, which would result in a corrupted zip
		idLib::Printf( "Skipping zip creation/modification, no additional changes need to be made...\n" );
		return true;
	}
	
	// open the zip file
	zipFile zf = zipOpen( zipFileName, appendFiles ? APPEND_STATUS_ADDINZIP : 0 );
	if( zf == NULL )
	{
		idLib::Warning( "[%s] - error opening file '%s'!", __FUNCTION__, zipFileName.c_str() );
		return false;
	}
	
	// add the files to the zip file
	for( int i = 0; i < files->GetNumFiles(); i++ )
	{
	
		// add each file to the zip file
		zip_fileinfo zi;
		memset( &zi, 0, sizeof( zip_fileinfo ) );
		
		idStr filename = files->GetFile( i );
		
		if( IsFiltered( filename ) )
		{
			idLib::PrintfIf( zip_verbosity.GetBool(), "...Skipping: '%s'\n", filename.c_str() );
			continue;
		}
		
		idStr filenameInZip = filename;
		filenameInZip.Strip( relPath );
		filenameInZip.StripLeading( "/" );
		
		idStrStatic< MAX_OSPATH > ospath;
		ospath = fileSystem->RelativePathToOSPath( filename );
		GetFileTime( ospath, &zi.dosDate );
		
		idLib::PrintfIf( zip_verbosity.GetBool(), "...Adding: '%s' ", filenameInZip.c_str() );
		
		int compressionMethod = Z_DEFLATED;
		if( IsUncompressed( filenameInZip ) )
		{
			compressionMethod = 0;
		}
		
		int errcode = zipOpenNewFileInZip3( zf, filenameInZip, &zi, NULL, 0, NULL, 0, NULL /* comment*/,
											compressionMethod,	DEFAULT_COMPRESSION_LEVEL, 0, -MAX_WBITS, DEF_MEM_LEVEL,
											Z_DEFAULT_STRATEGY, NULL /*password*/, 0 /*fileCRC*/ );
											
		if( errcode != ZIP_OK )
		{
			idLib::Warning( "Error opening file in zipfile!" );
			continue;
		}
		else
		{
			// open the source file
			idFile_Permanent src( filename, ospath, FS_READ );
			if( !src.IsOpen() )
			{
				idLib::Warning( "Error opening source file!" );
				continue;
			}
			
			// copy the file data into the zip file
			idTempArray<byte> buffer( DEFAULT_WRITEBUFFERSIZE );
			size_t total = 0;
			while( size_t bytesRead = src.Read( buffer.Ptr(), buffer.Size() ) )
			{
				if( bytesRead > 0 )
				{
					errcode = zipWriteInFileInZip( zf, buffer.Ptr(), ( unsigned int )bytesRead );
					if( errcode != ZIP_OK )
					{
						idLib::Warning( "Error writing to zipfile (%i bytes)!", bytesRead );
						continue;
					}
				}
				total += bytesRead;
			}
			assert( total == ( size_t )src.Length() );
		}
		
		errcode = zipCloseFileInZip( zf );
		if( errcode != ZIP_OK )
		{
			idLib::Warning( "Error zipping source file!" );
			continue;
		}
		idLib::PrintfIf( zip_verbosity.GetBool(), "\n" );
	}
	
	// free the file list
	if( files != NULL )
	{
		fileSystem->FreeFileList( files );
	}
	
	// close the zip file
	int closeError = zipClose( zf, NULL );
	if( closeError != ZIP_OK )
	{
		idLib::Warning( "[%s] - error closing file '%s'!", __FUNCTION__, zipFileName.c_str() );
		return false;
	}
	
	idLib::Printf( "Done.\n" );
	
	return true;
#else
	
	return false;
#endif
	
}
Exemplo n.º 9
0
int main__minizip(int argc,char *argv[])
{
    int i;
    int opt_overwrite=0;
    int opt_compress_level=Z_DEFAULT_COMPRESSION;
    int zipfilenamearg = 0;
    char filename_try[MAXFILENAME+16];
    int zipok;
    int err=0;
    int size_buf=0;
    void* buf=NULL;
    const char* password=NULL;


    do_banner__minizip();
    if (argc==1)
    {
        do_help__minizip();
        return 0;
    }
    else
    {
        for (i=1;i<argc;i++)
        {
            if ((*argv[i])=='-')
            {
                const char *p=argv[i]+1;

                while ((*p)!='\0')
                {
                    char c=*(p++);;
                    if ((c=='o') || (c=='O'))
                        opt_overwrite = 1;
                    if ((c=='a') || (c=='A'))
                        opt_overwrite = 2;
                    if ((c>='0') && (c<='9'))
                        opt_compress_level = c-'0';

                    if (((c=='p') || (c=='P')) && (i+1<argc))
                    {
                        password=argv[i+1];
                        i++;
                    }
                }
            }
            else
                if (zipfilenamearg == 0)
                    zipfilenamearg = i ;
        }
    }

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

    if (zipfilenamearg==0)
        zipok=0;
    else
    {
        int i,len;
        int dot_found=0;

        zipok = 1 ;
        strncpy(filename_try, argv[zipfilenamearg],MAXFILENAME-1);
        /* strncpy doesnt append the trailing NULL, of the string is too long. */
        filename_try[ MAXFILENAME ] = '\0';

        len=(int)strlen(filename_try);
        for (i=0;i<len;i++)
            if (filename_try[i]=='.')
                dot_found=1;

        if (dot_found==0)
            strcat(filename_try,".zip");

        if (opt_overwrite==2)
        {
            /* if the file don't exist, we not append file */
            if (check_exist_file__minizip(filename_try)==0)
                opt_overwrite=1;
        }
        else
        if (opt_overwrite==0)
            if (check_exist_file__minizip(filename_try)!=0)
            {
                char rep=0;
                do
                {
                    char answer[128];
                    int ret;
                    printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ",filename_try);
                    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')
                    zipok = 0;
                if (rep=='A')
                    opt_overwrite = 2;
            }
    }

    if (zipok==1)
    {
        zipFile zf;
        int errclose;
#        ifdef USEWIN32IOAPI
        zlib_filefunc_def ffunc;
        fill_win32_filefunc(&ffunc);
        zf = zipOpen2(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc);
#        else
        zf = zipOpen(filename_try,(opt_overwrite==2) ? 2 : 0);
#        endif

        if (zf == NULL)
        {
            printf("error opening %s\n",filename_try);
            err= ZIP_ERRNO;
        }
        else
            printf("creating %s\n",filename_try);

        for (i=zipfilenamearg+1;(i<argc) && (err==ZIP_OK);i++)
        {
            if (!((((*(argv[i]))=='-') || ((*(argv[i]))=='/')) &&
                  ((argv[i][1]=='o') || (argv[i][1]=='O') ||
                   (argv[i][1]=='a') || (argv[i][1]=='A') ||
                   (argv[i][1]=='p') || (argv[i][1]=='P') ||
                   ((argv[i][1]>='0') || (argv[i][1]<='9'))) &&
                  (strlen(argv[i]) == 2)))
            {
                FILE * fin;
                int size_read;
                const char* filenameinzip = argv[i];
                zip_fileinfo zi;
                unsigned long crcFile=0;

                zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
                zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
                zi.dosDate = 0;
                zi.internal_fa = 0;
                zi.external_fa = 0;
                filetime__minizip(filenameinzip,&zi.tmz_date,&zi.dosDate);

/*
                err = zipOpenNewFileInZip(zf,filenameinzip,&zi,
                                 NULL,0,NULL,0,NULL / * comment * /,
                                 (opt_compress_level != 0) ? Z_DEFLATED : 0,
                                 opt_compress_level);
*/
                if ((password != NULL) && (err==ZIP_OK))
                    err = getFileCrc__minizip(filenameinzip,buf,size_buf,&crcFile);

                err = zipOpenNewFileInZip3(zf,filenameinzip,&zi,
                                 NULL,0,NULL,0,NULL /* comment*/,
                                 (opt_compress_level != 0) ? Z_DEFLATED : 0,
                                 opt_compress_level,0,
                                 /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */
                                 -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
                                 password,crcFile);

                if (err != ZIP_OK)
                    printf("error in opening %s in zipfile\n",filenameinzip);
                else
                {
                    fin = fopen(filenameinzip,"rb");
                    if (fin==NULL)
                    {
                        err=ZIP_ERRNO;
                        printf("error in opening %s for reading\n",filenameinzip);
                    }
                }

                if (err == ZIP_OK)
                    do
                    {
                        err = ZIP_OK;
                        size_read = (int)fread(buf,1,size_buf,fin);
                        if (size_read < size_buf)
                            if (feof(fin)==0)
                        {
                            printf("error in reading %s\n",filenameinzip);
                            err = ZIP_ERRNO;
                        }

                        if (size_read>0)
                        {
                            err = zipWriteInFileInZip (zf,buf,size_read);
                            if (err<0)
                            {
                                printf("error in writing %s in the zipfile\n",
                                                 filenameinzip);
                            }

                        }
                    } while ((err == ZIP_OK) && (size_read>0));

                if (fin)
                    fclose(fin);

                if (err<0)
                    err=ZIP_ERRNO;
                else
                {
                    err = zipCloseFileInZip(zf);
                    if (err!=ZIP_OK)
                        printf("error in closing %s in the zipfile\n",
                                    filenameinzip);
                }
            }
        }
        errclose = zipClose(zf,NULL);
        if (errclose != ZIP_OK)
            printf("error in closing %s\n",filename_try);
    }
    else
    {
       do_help__minizip();
    }

    free(buf);
    return 0;
}
Exemplo n.º 10
0
static int hb_zipStoreFile( zipFile hZip, const char * szFileName, const char * szName, const char * szPassword, const char * szComment )
{
   char *       szZipName, * pString;
   HB_FHANDLE   hFile;
   HB_SIZE      nLen;
   HB_FATTR     ulExtAttr;
   zip_fileinfo zfi;
   int          iResult;
   HB_BOOL      fError;
   HB_BOOL      fText;
   HB_U32       ulCRC;

   if( szName )
   {
      /* change path separators to '/' */
      szZipName = hb_strdup( szName );

      nLen    = strlen( szZipName );
      pString = szZipName;
      while( nLen-- )
      {
         if( pString[ nLen ] == '\\' )
            pString[ nLen ] = '/';
      }
   }
   else
   {
      /* get file name */
      szZipName = hb_strdup( szFileName );

      nLen    = strlen( szZipName );
      pString = szZipName;

      while( nLen-- )
      {
         if( pString[ nLen ] == '/' || pString[ nLen ] == '\\' )
         {
            memmove( szZipName, &pString[ nLen + 1 ], strlen( szZipName ) - nLen );
            break;
         }
      }
   }

   memset( &zfi, 0, sizeof( zfi ) );
   fError    = HB_FALSE;
   ulExtAttr = 0;

#if defined( HB_OS_WIN )
   {
      LPTSTR  lpFileNameFree;
      LPCTSTR lpFileName = HB_FSNAMECONV( szFileName, &lpFileNameFree );
      DWORD   attr       = GetFileAttributes( lpFileName );

      if( attr != INVALID_FILE_ATTRIBUTES )
      {
         ulExtAttr = hb_translateExtAttr( szFileName, attr &
                                          ( FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN |
                                            FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_DIRECTORY |
                                            FILE_ATTRIBUTE_ARCHIVE ) );
      }
      else
         fError = HB_TRUE;

      if( lpFileNameFree )
         hb_xfree( lpFileNameFree );
   }
#elif defined( HB_OS_UNIX )
   {
      struct stat statbuf;
      struct tm   st;
      char *      pszFree;

      if( stat( hb_fsNameConv( szFileName, &pszFree ), &statbuf ) == 0 )
      {
         if( S_ISDIR( statbuf.st_mode ) )
         {
            ulExtAttr |= 0x40000000;
            ulExtAttr |= 0x10; /* FILE_ATTRIBUTE_DIRECTORY */
         }
         else
         {
            ulExtAttr |= 0x80000000;
            ulExtAttr |= 0x20; /* FILE_ATTRIBUTE_ARCHIVE */
         }

         ulExtAttr |= ( ( statbuf.st_mode & S_IXOTH ) ? 0x00010000 : 0 ) |
                      ( ( statbuf.st_mode & S_IWOTH ) ? 0x00020000 : 0 ) |
                      ( ( statbuf.st_mode & S_IROTH ) ? 0x00040000 : 0 ) |
                      ( ( statbuf.st_mode & S_IXGRP ) ? 0x00080000 : 0 ) |
                      ( ( statbuf.st_mode & S_IWGRP ) ? 0x00100000 : 0 ) |
                      ( ( statbuf.st_mode & S_IRGRP ) ? 0x00200000 : 0 ) |
                      ( ( statbuf.st_mode & S_IXUSR ) ? 0x00400000 : 0 ) |
                      ( ( statbuf.st_mode & S_IWUSR ) ? 0x00800000 : 0 ) |
                      ( ( statbuf.st_mode & S_IRUSR ) ? 0x01000000 : 0 );

#  if defined( HB_HAS_LOCALTIME_R )
         localtime_r( &statbuf.st_mtime, &st );
#  else
         st = *localtime( &statbuf.st_mtime );
#  endif

         zfi.tmz_date.tm_sec  = st.tm_sec;
         zfi.tmz_date.tm_min  = st.tm_min;
         zfi.tmz_date.tm_hour = st.tm_hour;
         zfi.tmz_date.tm_mday = st.tm_mday;
         zfi.tmz_date.tm_mon  = st.tm_mon;
         zfi.tmz_date.tm_year = st.tm_year;
      }
      else
         fError = HB_TRUE;

      if( pszFree )
         hb_xfree( pszFree );
   }
#elif defined( HB_OS_DOS )
   {
#  if defined( __DJGPP__ ) || defined( __RSX32__ ) || defined( __GNUC__ )
      int    attr;
      char * pszFree;

      attr = _chmod( hb_fsNameConv( szFileName, &pszFree ), 0, 0 );

      if( pszFree )
         hb_xfree( pszFree );

      if( attr != -1 )
#  else
      HB_FATTR attr;

      if( hb_fsGetAttr( szFileName, &attr ) )
#  endif
      {
         ulExtAttr = attr & ( HB_FA_READONLY | HB_FA_HIDDEN | HB_FA_SYSTEM |
                              HB_FA_DIRECTORY | HB_FA_ARCHIVE );

         ulExtAttr = hb_translateExtAttr( szFileName, ulExtAttr );
      }
      else
         fError = HB_TRUE;
   }
#elif defined( HB_OS_OS2 )
   {
      FILESTATUS3 fs3;
      APIRET      ulrc;
      HB_FATTR    ulAttr;
      char *      pszFree;

      ulrc = DosQueryPathInfo( ( PCSZ ) hb_fsNameConv( szFileName, &pszFree ), FIL_STANDARD, &fs3, sizeof( fs3 ) );

      if( pszFree )
         hb_xfree( pszFree );

      if( ulrc == NO_ERROR )
      {
         ulAttr = 0;
         if( fs3.attrFile & FILE_READONLY )
            ulAttr |= HB_FA_READONLY;
         if( fs3.attrFile & FILE_HIDDEN )
            ulAttr |= HB_FA_HIDDEN;
         if( fs3.attrFile & FILE_SYSTEM )
            ulAttr |= HB_FA_SYSTEM;
         if( fs3.attrFile & FILE_DIRECTORY )
            ulAttr |= HB_FA_DIRECTORY;
         if( fs3.attrFile & FILE_ARCHIVED )
            ulAttr |= HB_FA_ARCHIVE;

         ulExtAttr = hb_translateExtAttr( szFileName, ulAttr );

         zfi.tmz_date.tm_sec  = fs3.ftimeLastWrite.twosecs * 2;
         zfi.tmz_date.tm_min  = fs3.ftimeLastWrite.minutes;
         zfi.tmz_date.tm_hour = fs3.ftimeLastWrite.hours;
         zfi.tmz_date.tm_mday = fs3.fdateLastWrite.day;
         zfi.tmz_date.tm_mon  = fs3.fdateLastWrite.month;
         zfi.tmz_date.tm_year = fs3.fdateLastWrite.year + 1980;
      }
      else
         fError = HB_TRUE;
   }
#else
   {
      HB_FATTR attr;

      if( ! hb_fsGetAttr( szFileName, &attr ) )
         ulExtAttr = 0x81B60020;  /* FILE_ATTRIBUTE_ARCHIVE | rw-rw-rw- */
      else
      {
         ulExtAttr = attr & ( HB_FA_READONLY | HB_FA_HIDDEN | HB_FA_SYSTEM |
                              HB_FA_DIRECTORY | HB_FA_ARCHIVE );

         ulExtAttr = hb_translateExtAttr( szFileName, ulExtAttr );
      }
   }
#endif

   if( fError )
   {
      hb_xfree( szZipName );
      return -200;
   }

   fText = HB_FALSE;
   ulCRC = 0;

   zfi.external_fa = ulExtAttr;
   /* TODO: zip.exe test: 0 for binary file, 1 for text. Does not depend on
      extension. We should analyse content of file to determine this??? */
   zfi.internal_fa = 0;

   if( ulExtAttr & 0x40000000 )
   {
      iResult = zipOpenNewFileInZip3( hZip, szZipName, &zfi, NULL, 0, NULL, 0, szComment,
                                      Z_DEFLATED, Z_DEFAULT_COMPRESSION, 0,
                                      -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
                                      szPassword, ulCRC );
      if( iResult == 0 )
         zipCloseFileInZip( hZip );
   }
   else
   {
      hFile = hb_fsOpen( szFileName, FO_READ );

      if( hFile != FS_ERROR )
      {
#if defined( HB_OS_WIN )
         {
            FILETIME   ftutc, ft;
            SYSTEMTIME st;

            if( GetFileTime( ( HANDLE ) hb_fsGetOsHandle( hFile ), NULL, NULL, &ftutc ) &&
                FileTimeToLocalFileTime( &ftutc, &ft ) &&
                FileTimeToSystemTime( &ft, &st ) )
            {
               zfi.tmz_date.tm_sec  = st.wSecond;
               zfi.tmz_date.tm_min  = st.wMinute;
               zfi.tmz_date.tm_hour = st.wHour;
               zfi.tmz_date.tm_mday = st.wDay;
               zfi.tmz_date.tm_mon  = st.wMonth - 1;
               zfi.tmz_date.tm_year = st.wYear;
            }
         }
#endif
         if( szPassword )
         {
            if( hb_zipGetFileInfo( szFileName, &ulCRC, &fText ) )
               zfi.internal_fa = fText ? 1 : 0;
         }

         iResult = zipOpenNewFileInZip3( hZip, szZipName, &zfi, NULL, 0, NULL, 0, szComment,
                                         Z_DEFLATED, Z_DEFAULT_COMPRESSION, 0,
                                         -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
                                         szPassword, ulCRC );
         if( iResult == 0 )
         {
            pString = ( char * ) hb_xgrab( HB_Z_IOBUF_SIZE );
            while( ( nLen = hb_fsReadLarge( hFile, pString, HB_Z_IOBUF_SIZE ) ) > 0 )
               zipWriteInFileInZip( hZip, pString, ( unsigned ) nLen );

            hb_xfree( pString );

            zipCloseFileInZip( hZip );
         }
         hb_fsClose( hFile );
      }
      else
         iResult = -200 - hb_fsError();
   }
   hb_xfree( szZipName );
   return iResult;
}
Exemplo n.º 11
0
int thread_save(void *data)
{
	while (1)
	{
		SDL_SemWait(main_save->wait_iqueue);

		zipFile *zf = NULL;
		const char *zipname = NULL;

		while (1) {
			save_queue *q = pop_save();
			if (!q) {
				if (last_zipname) free(last_zipname);
				last_zipname = NULL; last_zf = NULL;
				break;
			}
			
			if (!zipname || strcmp(zipname, q->zfname)) {
				if (zf) {
					zipClose(zf, NULL);
					printf("Saved zipname %s\n", zipname);
					finish_zip(zipname);
					free((char*)zipname);
				} else {
					printf("Saving zipname %s\n", q->zfname);
				}
				zipname = strdup(q->zfname);
				zf = q->zf;
			}

//			printf("* %s<%s> : %ld\n", q->zfname, q->filename, q->payload_len);

			/* Init the zip entry */
			int err=0;
			int opt_compress_level = 4;
			zip_fileinfo zi;
			unsigned long crcFile=0;
			zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
			zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
			zi.dosDate = 0;
			zi.internal_fa = 0;
			zi.external_fa = 0;
			err = zipOpenNewFileInZip3(zf, q->filename, &zi,
				NULL,0,NULL,0,NULL /* comment*/,
				(opt_compress_level != 0) ? Z_DEFLATED : 0,
				opt_compress_level,0,
				-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
				NULL,crcFile);
			if (err == ZIP_OK)
			{
				zipWriteInFileInZip(zf, q->payload, q->payload_len);
				zipCloseFileInZip(zf);
			}

			free(q->payload);
			free(q->zfname);
			free(q->filename);
		}

		if (zf) {
			zipClose(zf, NULL);
			printf("Saved zipname %s\n", zipname);
			finish_zip(zipname);
			free((char*)zipname);
		}
	}
	return(0);
}