Пример #1
0
void nuiZipWriter::Open(CreateFlag flag)
{
  mpFileFuncDef = new zlib_filefunc_def;
  mpFileFuncDef->opaque = mpStream;
  mpFileFuncDef->zopen_file  = &::zOpen;
  mpFileFuncDef->zread_file  = &::zRead;
  mpFileFuncDef->zwrite_file = &::zWrite;
  mpFileFuncDef->ztell_file  = &::zTell;
  mpFileFuncDef->zseek_file  = &::zSeek;
  mpFileFuncDef->zclose_file = &::zClose;
  mpFileFuncDef->zerror_file = &::zError;
  
  int append = 0;
  switch (flag)
  {
    case OverWrite: append = APPEND_STATUS_CREATE; break;
    case AppendToStream: append = APPEND_STATUS_CREATEAFTER; break;
    case AppendToZip: append = APPEND_STATUS_ADDINZIP; break;
  }
  
  char* comment = NULL;
 
  mpZip = zipOpen2("", append, NULL, mpFileFuncDef);
  
  if (comment)
    free(comment);
}
Пример #2
0
bool QuaZip::open(Mode mode, zlib_filefunc_def* ioApi)
{
  p->zipError=UNZ_OK;
  if(isOpen()) {
    qWarning("QuaZip::open(): ZIP already opened");
    return false;
  }
  QIODevice *ioDevice = p->ioDevice;
  if (ioDevice == NULL) {
    if (p->zipName.isEmpty()) {
      qWarning("QuaZip::open(): set either ZIP file name or IO device first");
      return false;
    } else {
      ioDevice = new QFile(p->zipName);
    }
  }
  switch(mode) {
    case mdUnzip:
      p->unzFile_f=unzOpen2(ioDevice, ioApi);
      if(p->unzFile_f!=NULL) {
        p->mode=mode;
        p->ioDevice = ioDevice;
        return true;
      } else {
        p->zipError=UNZ_OPENERROR;
        if (!p->zipName.isEmpty())
          delete ioDevice;
        return false;
      }
    case mdCreate:
    case mdAppend:
    case mdAdd:
      p->zipFile_f=zipOpen2(ioDevice,
          mode==mdCreate?APPEND_STATUS_CREATE:
          mode==mdAppend?APPEND_STATUS_CREATEAFTER:
          APPEND_STATUS_ADDINZIP,
          NULL,
          ioApi);
      if(p->zipFile_f!=NULL) {
        p->mode=mode;
        p->ioDevice = ioDevice;
        return true;
      } else {
        p->zipError=UNZ_OPENERROR;
        if (!p->zipName.isEmpty())
          delete ioDevice;
        return false;
      }
    default:
      qWarning("QuaZip::open(): unknown mode: %d", (int)mode);
      if (!p->zipName.isEmpty())
        delete ioDevice;
      return false;
      break;
  }
}
Пример #3
0
		zipFile OpenForZipping(const std::string& file_name_utf8, int append_flag) 
		{
			zlib_filefunc_def* zip_func_ptrs = NULL;
			zlib_filefunc_def zip_funcs;
			fill_win32_filefunc(&zip_funcs);
			zip_funcs.zopen_file = ZipOpenFunc;
			zip_func_ptrs = &zip_funcs;
			return zipOpen2(file_name_utf8.c_str(),
				append_flag,
				NULL,  // global comment
				zip_func_ptrs);
		}
Пример #4
0
		void*					ZipIOBase::__openZip(const char* pathname, bool append)
		{
			zlib_filefunc_def_s s;
			s.opaque=this;
			s.zopen_file=&___open_file_func;
			s.zread_file=&___read_file_func;
			s.zwrite_file=&___write_file_func;
			s.ztell_file=&___tell_file_func;
			s.zseek_file=&___seek_file_func;
			s.zclose_file=&___close_file_func;
			s.zerror_file=&___testerror_file_func;

			return zipOpen2(pathname,append?APPEND_STATUS_ADDINZIP:APPEND_STATUS_CREATE,0,&s);
		}
Пример #5
0
struct ExecutionLogging* InitExecutionLogging(const char*pathZip)
{
    struct ExecutionLogging* pEL;

    pEL = (struct ExecutionLogging*)malloc(sizeof(struct ExecutionLogging));
    if (pEL==NULL)
        return NULL;

    fill_afopen_filefunc(&(pEL->zlib_filefunc));
    pEL->zf=zipOpen2(pathZip,APPEND_STATUS_CREATE,NULL,&(pEL->zlib_filefunc));
    if (pEL->zf==NULL)
    {
        free(pEL);
        return NULL;
    }
    
    pEL->pAE_FileReading = InitArrayExpanding(sizeof(struct FileReadingInfoItem),0);
    pEL->pAE_FileToWrite = InitArrayExpanding(sizeof(struct FileToWriteInfoItem),0);

    pEL->pAE_StdOut = InitArrayExpanding(sizeof(char),0);
    pEL->pAE_StdErr = InitArrayExpanding(sizeof(char),0);
    pEL->pAE_FileReadList = InitArrayExpanding(sizeof(char),0);

    pEL->argc = 0;
    pEL->argv = NULL;

    pEL -> store_file_out_content = pEL -> store_list_file_out_content = 
    pEL -> store_file_in_content = pEL -> store_list_file_in_content = 0;
    pEL -> store_std_out_content = pEL -> store_std_err_content = 1;

    pEL->portion_ignore_pathname = NULL;

    if ((pEL->pAE_StdOut == NULL) || (pEL->pAE_StdErr == NULL) ||
        (pEL->pAE_FileReading == NULL) || (pEL->pAE_FileToWrite == NULL) ||
        (pEL->pAE_FileReadList == NULL))
    {
        FreeArrayExpanding(pEL->pAE_StdOut);
        FreeArrayExpanding(pEL->pAE_StdErr);
        FreeArrayExpanding(pEL->pAE_FileReading);
        FreeArrayExpanding(pEL->pAE_FileToWrite);
        FreeArrayExpanding(pEL->pAE_FileReadList);
        zipClose(pEL->zf,"");
        free(pEL);
        return NULL;
    }

    return pEL;
}
Пример #6
0
status_t WriteZipFile(DataIO & writeTo, const Message & msg, int compressionLevel, uint64 fileCreationTime)
{
   TCHECKPOINT;

   zlib_filefunc_def zdefs = {
      fopen_dataio_func,
      fread_dataio_func,
      fwrite_dataio_func,
      ftell_dataio_func,
      fseek_dataio_func,
      fclose_dataio_func,
      ferror_dataio_func,
      &writeTo
   };
   const char * comment = "";
   zipFile zf = zipOpen2(NULL, false, &comment, &zdefs);
   if (zf)
   {
      zip_fileinfo * fi = NULL;
      zip_fileinfo fileInfo;  
      {
         memset(&fileInfo, 0, sizeof(fileInfo));
         HumanReadableTimeValues v;
         if (GetHumanReadableTimeValues((fileCreationTime==MUSCLE_TIME_NEVER)?GetCurrentTime64(MUSCLE_TIMEZONE_LOCAL):fileCreationTime, v, MUSCLE_TIMEZONE_LOCAL) == B_NO_ERROR)
         {
            fi = &fileInfo;
            fileInfo.tmz_date.tm_sec  = v.GetSecond();
            fileInfo.tmz_date.tm_min  = v.GetMinute();
            fileInfo.tmz_date.tm_hour = v.GetHour();
            fileInfo.tmz_date.tm_mday = v.GetDayOfMonth()+1;
            fileInfo.tmz_date.tm_mon  = v.GetMonth();
            fileInfo.tmz_date.tm_year = v.GetYear();
         }
      }
      
      const status_t ret = WriteZipFileAux(zf, "", msg, compressionLevel, fi);
      zipClose(zf, NULL);
      return ret; 
   }
   else return B_ERROR;
}
Пример #7
0
bool QuaZip::open(Mode mode, zlib_filefunc_def* ioApi)
{
  zipError=UNZ_OK;
  if(isOpen()) {
    qWarning("QuaZip::open(): ZIP already opened");
    return false;
  }
  switch(mode) {
    case mdUnzip:
      unzFile_f=unzOpen2(QFile::encodeName(zipName).constData(), ioApi);
      if(unzFile_f!=NULL) {
        this->mode=mode;
        return true;
      } else {
        zipError=UNZ_OPENERROR;
        return false;
      }
    case mdCreate:
    case mdAppend:
    case mdAdd:
      zipFile_f=zipOpen2(QFile::encodeName(zipName).constData(),
          mode==mdCreate?APPEND_STATUS_CREATE:
          mode==mdAppend?APPEND_STATUS_CREATEAFTER:
          APPEND_STATUS_ADDINZIP,
          NULL,
          ioApi);
      if(zipFile_f!=NULL) {
        this->mode=mode;
        return true;
      } else {
        zipError=UNZ_OPENERROR;
        return false;
      }
    default:
      qWarning("QuaZip::open(): unknown mode: %d", (int)mode);
      return false;
      break;
  }
}
Пример #8
0
// Static.
MgByteReader * WriteKmz(const std::string& kml) 
{
  zlib_filefunc_def fdef;
  fill_memory_filefunc(&fdef);
  
  char buff[256];
  
  int outsize = kml.length() + 256;;
  char* outbuff = (char*)malloc(outsize);
   
  ourmemory_t *mem = (ourmemory_t *)malloc(sizeof(*mem)); 
  
  mem->base = outbuff;
  mem->size = outsize;
  mem->limit = 0;
  mem->cur_offset = 0;
   
  sprintf(buff,"%p",mem);
  zipFile zipfile_ = zipOpen2(buff, 0,0,&fdef);
  if (!zipfile_) {
    return false;
  }
  zipOpenNewFileInZip(zipfile_, "doc.kml", 0, 0, 0, 0, 0, 0, Z_DEFLATED,
                      Z_DEFAULT_COMPRESSION);
  //zipWriteInFileInZip(zipfile_, (void* const)kml.data(),
  zipWriteInFileInZip(zipfile_, static_cast<const void*>(kml.data()),
                      static_cast<unsigned int>(kml.size()));
  zipCloseFileInZip(zipfile_);
  zipClose(zipfile_, 0);
  
  
  MgByteReader *breader = new MgByteReader((unsigned char*)outbuff,mem->limit,MgMimeType::Kmz);
  
  free(outbuff);
  free(mem);
  
  return breader;
 
}
Пример #9
0
zipFile zipopen (const char* path, const char* filenameinzip, int append)
{
  zipFile zf = NULL;
  int err=ZIP_OK;

#ifdef USEWIN32IOAPI
    zlib_filefunc_def ffunc;
    fill_win32_filefunc(&ffunc);
    zf = zipOpen2(path,append,NULL,&ffunc);
#else
    zf = zipOpen(path, append);
#endif

    if (zf == NULL) return NULL;

    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;
    filetime(filenameinzip,&zi.tmz_date,&zi.dosDate);

    err = zipOpenNewFileInZip(zf,filenameinzip,&zi,
                     NULL,0,NULL,0,NULL,
                     Z_DEFLATED,
                     Z_DEFAULT_COMPRESSION);
  
    if (err != ZIP_OK)
    {
       zipClose(zf, NULL);
       return NULL;
    }

    return zf;
}
Пример #10
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;
}
Пример #11
0
extern MINIZIP_EXPORT zipFile zipOpen (const char *pathname,int append)
{
  return zipOpen2(pathname,append,0,0);
}
Пример #12
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;
}
Пример #13
0
Error EditorExportPlatformOSX::export_project(const String& p_path, bool p_debug, bool p_dumb) {

	String src_pkg;

	EditorProgress ep("export","Exporting for OSX",104);

	String pkg_path = EditorSettings::get_singleton()->get_settings_path()+"/templates/osx.zip";

	if (p_debug) {

		src_pkg=custom_debug_package!=""?custom_debug_package:pkg_path;
	} else {

		src_pkg=custom_release_package!=""?custom_release_package:pkg_path;

	}


	FileAccess *src_f=NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&src_f);

	ep.step("Creating app",0);

	unzFile pkg = unzOpen2(src_pkg.utf8().get_data(), &io);
	if (!pkg) {

		EditorNode::add_io_error("Could not find template app to export:\n"+src_pkg);
		return ERR_FILE_NOT_FOUND;
	}

	ERR_FAIL_COND_V(!pkg, ERR_CANT_OPEN);
	int ret = unzGoToFirstFile(pkg);

	zlib_filefunc_def io2=io;
	FileAccess *dst_f=NULL;
	io2.opaque=&dst_f;
	zipFile	dpkg=zipOpen2(p_path.utf8().get_data(),APPEND_STATUS_CREATE,NULL,&io2);

	String binary_to_use="godot_osx_"+String(p_debug?"debug":"release")+"."+String(use64?"64":"32");

	print_line("binary: "+binary_to_use);
	String pkg_name;
	if (app_name!="")
		pkg_name=app_name;
	else if (String(Globals::get_singleton()->get("application/name"))!="")
		pkg_name=String(Globals::get_singleton()->get("application/name"));
	else
		pkg_name="Unnamed";


	while(ret==UNZ_OK) {

		//get filename
		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0);

		String file=fname;

		print_line("READ: "+file);
		Vector<uint8_t> data;
		data.resize(info.uncompressed_size);

		//read
		unzOpenCurrentFile(pkg);
		unzReadCurrentFile(pkg,data.ptr(),data.size());
		unzCloseCurrentFile(pkg);

		//write

		file = file.replace_first("osx_template.app/","");


		if (file=="Contents/Info.plist") {
			print_line("parse plist");
			_fix_plist(data,pkg_name);
		}

		if (file.begins_with("Contents/MacOS/godot_")) {
			if (file!="Contents/MacOS/"+binary_to_use) {
				ret = unzGoToNextFile(pkg);
				continue; //ignore!
			}
			file="Contents/MacOS/"+pkg_name;
		}

		if (file=="Contents/Resources/icon.icns") {
			//see if there is an icon
			String iconpath = Globals::get_singleton()->get("application/icon");
			print_line("icon? "+iconpath);
			if (iconpath!="") {
				Image icon;
				icon.load(iconpath);
				if (!icon.empty()) {
					print_line("loaded?");
					_make_icon(icon,data);
				}
			}
			//bleh?
		}

		file=pkg_name+".app/"+file;

		if (data.size()>0) {
			print_line("ADDING: "+file+" size: "+itos(data.size()));

			zip_fileinfo fi;
			fi.tmz_date.tm_hour=info.tmu_date.tm_hour;
			fi.tmz_date.tm_min=info.tmu_date.tm_min;
			fi.tmz_date.tm_sec=info.tmu_date.tm_sec;
			fi.tmz_date.tm_mon=info.tmu_date.tm_mon;
			fi.tmz_date.tm_mday=info.tmu_date.tm_mday;
			fi.tmz_date.tm_year=info.tmu_date.tm_year;
			fi.dosDate=info.dosDate;
			fi.internal_fa=info.internal_fa;
			fi.external_fa=info.external_fa;

			int err = zipOpenNewFileInZip(dpkg,
				file.utf8().get_data(),
				&fi,
				NULL,
				0,
				NULL,
				0,
				NULL,
				Z_DEFLATED,
				Z_DEFAULT_COMPRESSION);

			print_line("OPEN ERR: "+itos(err));
			err = zipWriteInFileInZip(dpkg,data.ptr(),data.size());
			print_line("WRITE ERR: "+itos(err));
			zipCloseFileInZip(dpkg);
		}

		ret = unzGoToNextFile(pkg);
	}


	ep.step("Making PKG",1);

	String pack_path=EditorSettings::get_singleton()->get_settings_path()+"/tmp/data.pck";
	FileAccess *pfs = FileAccess::open(pack_path,FileAccess::WRITE);
	Error err = save_pack(pfs);
	memdelete(pfs);

	if (err) {
		zipClose(dpkg,NULL);
		unzClose(pkg);
		return err;

	}

	{
		//write datapack

		int err = zipOpenNewFileInZip(dpkg,
			(pkg_name+".app/Contents/Resources/data.pck").utf8().get_data(),
			NULL,
			NULL,
			0,
			NULL,
			0,
			NULL,
			Z_DEFLATED,
			Z_DEFAULT_COMPRESSION);


		FileAccess *pf = FileAccess::open(pack_path,FileAccess::READ);
		ERR_FAIL_COND_V(!pf,ERR_CANT_OPEN);
		const int BSIZE = 16384;
		uint8_t buf[BSIZE];

		while(true) {

			int r = pf->get_buffer(buf,BSIZE);
			if (r<=0)
				break;
			zipWriteInFileInZip(dpkg,buf,r);

		}
		zipCloseFileInZip(dpkg);
		memdelete(pf);

	}

	zipClose(dpkg,NULL);
	unzClose(pkg);

	return OK;
}
Пример #14
0
extern zipFile ZEXPORT zipOpen (
    const char *pathname,
    int append)
{
    return zipOpen2(pathname,append,NULL,NULL);
}
Пример #15
0
///////////////////////////////////////////////////////////////
//
// CResourceChecker::ReplaceFilesInZIP
//
// Based on example at http://www.winimage.com/zLibDll/minizip.html
// by Ivan A. Krestinin
//
///////////////////////////////////////////////////////////////
int CResourceChecker::ReplaceFilesInZIP( const string& strOrigZip, const string& strTempZip, const vector < string >& pathInArchiveList, const vector < string >& m_upgradedFullPathList )
{
    // open source and destination file
    zlib_filefunc_def ffunc;
    #ifdef WIN32
    fill_win32_filefunc(&ffunc);
    #else
    fill_fopen_filefunc(&ffunc);
    #endif

    zipFile szip = unzOpen2(strOrigZip.c_str(), &ffunc);
    if (szip==NULL) { /*free(tmp_name);*/ return 0; }
    zipFile dzip = zipOpen2(strTempZip.c_str(), APPEND_STATUS_CREATE, NULL, &ffunc);
    if (dzip==NULL) { unzClose(szip); /*free(tmp_name);*/ return 0; }

    // get global commentary
    unz_global_info glob_info;
    if (unzGetGlobalInfo(szip, &glob_info) != UNZ_OK) { zipClose(dzip, NULL); unzClose(szip); /*free(tmp_name);*/ return 0; }

    char* glob_comment = NULL;
    if (glob_info.size_comment > 0)
    {
        glob_comment = (char*)malloc(glob_info.size_comment+1);
        if ((glob_comment==NULL)&&(glob_info.size_comment!=0)) { zipClose(dzip, NULL); unzClose(szip); /*free(tmp_name);*/ return 0; }

        if ((unsigned int)unzGetGlobalComment(szip, glob_comment, glob_info.size_comment+1) != glob_info.size_comment)  { zipClose(dzip, NULL); unzClose(szip); free(glob_comment); /*free(tmp_name);*/ return 0; }
    }

    // copying files
    int n_files = 0;

    int rv = unzGoToFirstFile(szip);
    while (rv == UNZ_OK)
    {
        // get zipped file info
        unz_file_info unzfi;
        char dos_fn[MAX_PATH];
        if (unzGetCurrentFileInfo(szip, &unzfi, dos_fn, MAX_PATH, NULL, 0, NULL, 0) != UNZ_OK) break;
        char fn[MAX_PATH];
        #ifdef WIN32
        OemToChar(dos_fn, fn);
        #endif

        // See if file should be replaced
        string fullPathReplacement;
        for ( unsigned long i = 0 ; i < pathInArchiveList.size () ; i++ )
            if ( stricmp ( fn, pathInArchiveList[i].c_str () ) == 0 )
                fullPathReplacement = m_upgradedFullPathList[i];

        // Replace file in zip
        if ( fullPathReplacement.length () )
        {
            void* buf = NULL;
            unsigned long ulLength = 0;

            // Get new file into a buffer
            if ( FILE* pFile = File::Fopen ( fullPathReplacement.c_str (), "rb" ) )
            {
                // Get the file size,
                fseek( pFile, 0, SEEK_END );
                ulLength = ftell( pFile );
                fseek( pFile, 0, SEEK_SET );

                // Load file into a buffer
                buf = malloc( ulLength );
                if ( fread ( buf, 1, ulLength, pFile ) != ulLength )
                {
                    free( buf );
                    buf = NULL;
                }

                // Clean up
                fclose ( pFile );
            }

            if( !buf )
                break;

            // open destination file
            zip_fileinfo zfi;
            memcpy (&zfi.tmz_date, &unzfi.tmu_date, sizeof(tm_unz));
            zfi.dosDate = unzfi.dosDate;
            zfi.internal_fa = unzfi.internal_fa;
            zfi.external_fa = unzfi.external_fa;

            char* extrafield = NULL;
            char* commentary = NULL;
            int size_local_extra = 0;
            void* local_extra = NULL;
            int unzfi_size_file_extra = 0;
            int method = Z_DEFLATED;
            int level = Z_DEFAULT_COMPRESSION;


            if (zipOpenNewFileInZip(dzip, dos_fn, &zfi, local_extra, size_local_extra, extrafield, unzfi_size_file_extra, commentary, method, level )!=UNZ_OK)
                {free(extrafield); free(commentary); free(local_extra); free(buf); break;}

            // write file
            if (zipWriteInFileInZip(dzip, buf, ulLength)!=UNZ_OK)
                {free(extrafield); free(commentary); free(local_extra); free(buf); break;}

            if (zipCloseFileInZip(dzip/*, unzfi.uncompressed_size, unzfi.crc*/)!=UNZ_OK)
                {free(extrafield); free(commentary); free(local_extra); free(buf); break;}

            free( buf );
        }

        // Copy file in zip
        if ( !fullPathReplacement.length () )
        {
            char* extrafield = (char*)malloc(unzfi.size_file_extra);
            if ((extrafield==NULL)&&(unzfi.size_file_extra!=0)) break;
            char* commentary = (char*)malloc(unzfi.size_file_comment);
            if ((commentary==NULL)&&(unzfi.size_file_comment!=0)) {free(extrafield); break;}

            if (unzGetCurrentFileInfo(szip, &unzfi, dos_fn, MAX_PATH, extrafield, unzfi.size_file_extra, commentary, unzfi.size_file_comment) != UNZ_OK) {free(extrafield); free(commentary); break;}

            // open file for RAW reading
            int method;
            int level;
            if (unzOpenCurrentFile2(szip, &method, &level, 1)!=UNZ_OK) {free(extrafield); free(commentary); break;}

            int size_local_extra = unzGetLocalExtrafield(szip, NULL, 0);
            if (size_local_extra<0) {free(extrafield); free(commentary); break;}
            void* local_extra = malloc(size_local_extra);
            if ((local_extra==NULL)&&(size_local_extra!=0)) {free(extrafield); free(commentary); break;}
            if (unzGetLocalExtrafield(szip, local_extra, size_local_extra)<0) {free(extrafield); free(commentary); free(local_extra); break;}

            // this malloc may fail if file very large
            void* buf = malloc(unzfi.compressed_size);
            if ((buf==NULL)&&(unzfi.compressed_size!=0)) {free(extrafield); free(commentary); free(local_extra); break;}

            // read file
            int sz = unzReadCurrentFile(szip, buf, unzfi.compressed_size);
            if ((unsigned int)sz != unzfi.compressed_size) {free(extrafield); free(commentary); free(local_extra); free(buf); break;}

            // open destination file
            zip_fileinfo zfi;
            memcpy (&zfi.tmz_date, &unzfi.tmu_date, sizeof(tm_unz));
            zfi.dosDate = unzfi.dosDate;
            zfi.internal_fa = unzfi.internal_fa;
            zfi.external_fa = unzfi.external_fa;

            if (zipOpenNewFileInZip2(dzip, dos_fn, &zfi, local_extra, size_local_extra, extrafield, unzfi.size_file_extra, commentary, method, level, 1)!=UNZ_OK) {free(extrafield); free(commentary); free(local_extra); free(buf); break;}

            // write file
            if (zipWriteInFileInZip(dzip, buf, unzfi.compressed_size)!=UNZ_OK) {free(extrafield); free(commentary); free(local_extra); free(buf); break;}

            if (zipCloseFileInZipRaw(dzip, unzfi.uncompressed_size, unzfi.crc)!=UNZ_OK) {free(extrafield); free(commentary); free(local_extra); free(buf); break;}

            if (unzCloseCurrentFile(szip)==UNZ_CRCERROR) {free(extrafield); free(commentary); free(local_extra); free(buf); break;}
            free(commentary);
            free(buf);
            free(extrafield);
            free(local_extra);

            n_files ++;
        }

        rv = unzGoToNextFile(szip);
    }

    zipClose(dzip, glob_comment);
    unzClose(szip);

    free(glob_comment);

    return rv==UNZ_END_OF_LIST_OF_FILE;
}
Пример #16
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;
}
Пример #17
0
Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {

	String src_pkg_name;

	EditorProgress ep("export", "Exporting for OSX", 3);

	if (p_debug)
		src_pkg_name = p_preset->get("custom_package/debug");
	else
		src_pkg_name = p_preset->get("custom_package/release");

	if (src_pkg_name == "") {
		String err;
		src_pkg_name = find_export_template("osx.zip", &err);
		if (src_pkg_name == "") {
			EditorNode::add_io_error(err);
			return ERR_FILE_NOT_FOUND;
		}
	}

	FileAccess *src_f = NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&src_f);

	ep.step("Creating app", 0);

	unzFile src_pkg_zip = unzOpen2(src_pkg_name.utf8().get_data(), &io);
	if (!src_pkg_zip) {

		EditorNode::add_io_error("Could not find template app to export:\n" + src_pkg_name);
		return ERR_FILE_NOT_FOUND;
	}

	ERR_FAIL_COND_V(!src_pkg_zip, ERR_CANT_OPEN);
	int ret = unzGoToFirstFile(src_pkg_zip);

	String binary_to_use = "godot_osx_" + String(p_debug ? "debug" : "release") + ".";
	int bits_mode = p_preset->get("application/bits_mode");
	binary_to_use += String(bits_mode == 0 ? "fat" : bits_mode == 1 ? "64" : "32");

	print_line("binary: " + binary_to_use);
	String pkg_name;
	if (p_preset->get("application/name") != "")
		pkg_name = p_preset->get("application/name"); // app_name
	else if (String(ProjectSettings::get_singleton()->get("application/config/name")) != "")
		pkg_name = String(ProjectSettings::get_singleton()->get("application/config/name"));
	else
		pkg_name = "Unnamed";

	Error err = OK;
	String tmp_app_path_name = "";
	zlib_filefunc_def io2 = io;
	FileAccess *dst_f = NULL;
	io2.opaque = &dst_f;
	zipFile dst_pkg_zip = NULL;

	if (use_dmg()) {
		// We're on OSX so we can export to DMG, but first we create our application bundle
		tmp_app_path_name = EditorSettings::get_singleton()->get_cache_dir().plus_file(pkg_name + ".app");
		print_line("Exporting to " + tmp_app_path_name);
		DirAccess *tmp_app_path = DirAccess::create_for_path(tmp_app_path_name);
		if (!tmp_app_path) {
			err = ERR_CANT_CREATE;
		}

		// Create our folder structure or rely on unzip?
		if (err == OK) {
			print_line("Creating " + tmp_app_path_name + "/Contents/MacOS");
			err = tmp_app_path->make_dir_recursive(tmp_app_path_name + "/Contents/MacOS");
		}

		if (err == OK) {
			print_line("Creating " + tmp_app_path_name + "/Contents/Resources");
			err = tmp_app_path->make_dir_recursive(tmp_app_path_name + "/Contents/Resources");
		}
	} else {
		// Open our destination zip file
		dst_pkg_zip = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, NULL, &io2);
		if (!dst_pkg_zip) {
			err = ERR_CANT_CREATE;
		}
	}

	// Now process our template
	bool found_binary = false;
	int total_size = 0;

	while (ret == UNZ_OK && err == OK) {
		bool is_execute = false;

		//get filename
		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(src_pkg_zip, &info, fname, 16384, NULL, 0, NULL, 0);

		String file = fname;

		print_line("READ: " + file);
		Vector<uint8_t> data;
		data.resize(info.uncompressed_size);

		//read
		unzOpenCurrentFile(src_pkg_zip);
		unzReadCurrentFile(src_pkg_zip, data.ptr(), data.size());
		unzCloseCurrentFile(src_pkg_zip);

		//write

		file = file.replace_first("osx_template.app/", "");

		if (file == "Contents/Info.plist") {
			print_line("parse plist");
			_fix_plist(p_preset, data, pkg_name);
		}

		if (file.begins_with("Contents/MacOS/godot_")) {
			if (file != "Contents/MacOS/" + binary_to_use) {
				ret = unzGoToNextFile(src_pkg_zip);
				continue; //ignore!
			}
			found_binary = true;
			is_execute = true;
			file = "Contents/MacOS/" + pkg_name;
		}

		if (file == "Contents/Resources/icon.icns") {
			//see if there is an icon
			String iconpath;
			if (p_preset->get("application/icon") != "")
				iconpath = p_preset->get("application/icon");
			else
				iconpath = ProjectSettings::get_singleton()->get("application/config/icon");
			print_line("icon? " + iconpath);
			if (iconpath != "") {
				Ref<Image> icon;
				icon.instance();
				icon->load(iconpath);
				if (!icon->empty()) {
					print_line("loaded?");
					_make_icon(icon, data);
				}
			}
			//bleh?
		}

		if (data.size() > 0) {
			print_line("ADDING: " + file + " size: " + itos(data.size()));
			total_size += data.size();

			if (use_dmg()) {
				// write it into our application bundle
				file = tmp_app_path_name + "/" + file;

				// write the file, need to add chmod
				FileAccess *f = FileAccess::open(file, FileAccess::WRITE);
				if (f) {
					f->store_buffer(data.ptr(), data.size());
					f->close();
					if (is_execute) {
						// Chmod with 0755 if the file is executable
						f->_chmod(file, 0755);
					}
					memdelete(f);
				} else {
					err = ERR_CANT_CREATE;
				}
			} else {
				// add it to our zip file
				file = pkg_name + ".app/" + file;

				zip_fileinfo fi;
				fi.tmz_date.tm_hour = info.tmu_date.tm_hour;
				fi.tmz_date.tm_min = info.tmu_date.tm_min;
				fi.tmz_date.tm_sec = info.tmu_date.tm_sec;
				fi.tmz_date.tm_mon = info.tmu_date.tm_mon;
				fi.tmz_date.tm_mday = info.tmu_date.tm_mday;
				fi.tmz_date.tm_year = info.tmu_date.tm_year;
				fi.dosDate = info.dosDate;
				fi.internal_fa = info.internal_fa;
				fi.external_fa = info.external_fa;

				int zerr = zipOpenNewFileInZip(dst_pkg_zip,
						file.utf8().get_data(),
						&fi,
						NULL,
						0,
						NULL,
						0,
						NULL,
						Z_DEFLATED,
						Z_DEFAULT_COMPRESSION);

				print_line("OPEN ERR: " + itos(zerr));
				zerr = zipWriteInFileInZip(dst_pkg_zip, data.ptr(), data.size());
				print_line("WRITE ERR: " + itos(zerr));
				zipCloseFileInZip(dst_pkg_zip);
			}
		}

		ret = unzGoToNextFile(src_pkg_zip);
	}

	// we're done with our source zip
	unzClose(src_pkg_zip);

	if (!found_binary) {
		ERR_PRINTS("Requested template binary '" + binary_to_use + "' not found. It might be missing from your template archive.");
		err = ERR_FILE_NOT_FOUND;
	}

	if (err == OK) {
		ep.step("Making PKG", 1);

		if (use_dmg()) {
			String pack_path = tmp_app_path_name + "/Contents/Resources/" + pkg_name + ".pck";
			err = save_pack(p_preset, pack_path);

			// see if we can code sign our new package
			String identity = p_preset->get("codesign/identity");
			if (err == OK && identity != "") {
				ep.step("Code signing bundle", 2);

				// the order in which we code sign is important, this is a bit of a shame or we could do this in our loop that extracts the files from our ZIP

				// start with our application
				err = _code_sign(p_preset, tmp_app_path_name + "/Contents/MacOS/" + pkg_name);

				///@TODO we should check the contents of /Contents/Frameworks for frameworks to sign
			}

			if (err == OK && identity != "") {
				// we should probably loop through all resources and sign them?
				err = _code_sign(p_preset, tmp_app_path_name + "/Contents/Resources/icon.icns");
			}

			if (err == OK && identity != "") {
				err = _code_sign(p_preset, pack_path);
			}

			if (err == OK && identity != "") {
				err = _code_sign(p_preset, tmp_app_path_name + "/Contents/Info.plist");
			}

			// and finally create a DMG
			if (err == OK) {
				ep.step("Making DMG", 3);
				err = _create_dmg(p_path, pkg_name, tmp_app_path_name);
			}

			// Clean up temporary .app dir
			OS::get_singleton()->move_to_trash(tmp_app_path_name);
		} else {

			String pack_path = EditorSettings::get_singleton()->get_cache_dir().plus_file(pkg_name + ".pck");
			Error err = save_pack(p_preset, pack_path);

			if (err == OK) {
				zipOpenNewFileInZip(dst_pkg_zip,
						(pkg_name + ".app/Contents/Resources/" + pkg_name + ".pck").utf8().get_data(),
						NULL,
						NULL,
						0,
						NULL,
						0,
						NULL,
						Z_DEFLATED,
						Z_DEFAULT_COMPRESSION);

				FileAccess *pf = FileAccess::open(pack_path, FileAccess::READ);
				if (pf) {
					const int BSIZE = 16384;
					uint8_t buf[BSIZE];

					while (true) {

						int r = pf->get_buffer(buf, BSIZE);
						if (r <= 0)
							break;
						zipWriteInFileInZip(dst_pkg_zip, buf, r);
					}
					zipCloseFileInZip(dst_pkg_zip);
					memdelete(pf);
				} else {
					err = ERR_CANT_OPEN;
				}
			}
		}
	}

	if (dst_pkg_zip) {
		zipClose(dst_pkg_zip, NULL);
	}

	return OK;
}