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; }
bool OdinPatcher::Impl::processContents() { archive_entry *entry; int laRet; int mzRet; zipFile zf = MinizipUtils::ctxGetZipFile(zOutput); while ((laRet = archive_read_next_header(aInput, &entry)) == ARCHIVE_OK) { if (cancelled) return false; const char *name = archive_entry_pathname(entry); if (!name) { continue; } updateDetails(name); if (strcmp(name, "boot.img") == 0) { LOGD("Handling boot.img"); // Boot images should never be over about 30 MiB. This check is here // so the patcher won't try to read a multi-gigabyte system image // into RAM la_int64_t size = archive_entry_size(entry); if (size > 30 * 1024 * 1024) { LOGE("Boot image exceeds 30 MiB: %" PRId64, size); error = ErrorCode::BootImageTooLargeError; return false; } std::vector<unsigned char> data; if (size > 0) { data.reserve(size); } char buf[10240]; la_ssize_t n; while ((n = archive_read_data(aInput, buf, sizeof(buf))) > 0) { data.insert(data.end(), buf, buf + n); } if (n != 0) { LOGE("libarchive: Failed to read data: %s", archive_error_string(aInput)); error = ErrorCode::ArchiveReadDataError; return false; } if (!MultiBootPatcher::patchBootImage(pc, info, &data, &error)) { return false; } auto errorRet = MinizipUtils::addFile(zf, name, data); if (errorRet != ErrorCode::NoError) { error = errorRet; return false; } continue; } else if (!StringUtils::starts_with(name, "cache.img") && !StringUtils::starts_with(name, "system.img")) { LOGD("Skipping %s", name); if (archive_read_data_skip(aInput) != ARCHIVE_OK) { LOGE("libarchive: Failed to skip data: %s", archive_error_string(aInput)); error = ErrorCode::ArchiveReadDataError; return false; } continue; } LOGD("Handling %s", name); std::string zipName(name); if (StringUtils::ends_with(name, ".ext4")) { zipName.erase(zipName.size() - 5); } zipName += ".sparse"; // Ha! I'll be impressed if a Samsung firmware image does NOT need zip64 int zip64 = archive_entry_size(entry) > ((1ll << 32) - 1); zip_fileinfo zi; memset(&zi, 0, sizeof(zi)); // Open file in output zip mzRet = zipOpenNewFileInZip2_64( zf, // file zipName.c_str(), // filename &zi, // zip_fileinfo nullptr, // extrafield_local 0, // size_extrafield_local nullptr, // extrafield_global 0, // size_extrafield_global nullptr, // comment Z_DEFLATED, // method Z_DEFAULT_COMPRESSION, // level 0, // raw zip64 // zip64 ); if (mzRet != ZIP_OK) { LOGE("minizip: Failed to open new file in output zip: %s", MinizipUtils::zipErrorString(mzRet).c_str()); error = ErrorCode::ArchiveWriteHeaderError; return false; } la_ssize_t nRead; char buf[10240]; while ((nRead = archive_read_data(aInput, buf, sizeof(buf))) > 0) { if (cancelled) return false; mzRet = zipWriteInFileInZip(zf, buf, nRead); if (mzRet != ZIP_OK) { LOGE("minizip: Failed to write %s in output zip: %s", zipName.c_str(), MinizipUtils::zipErrorString(mzRet).c_str()); error = ErrorCode::ArchiveWriteDataError; zipCloseFileInZip(zf); return false; } } if (nRead != 0) { LOGE("libarchive: Failed to read %s: %s", name, archive_error_string(aInput)); error = ErrorCode::ArchiveReadDataError; zipCloseFileInZip(zf); return false; } // Close file in output zip mzRet = zipCloseFileInZip(zf); if (mzRet != ZIP_OK) { LOGE("minizip: Failed to close file in output zip: %s", MinizipUtils::zipErrorString(mzRet).c_str()); error = ErrorCode::ArchiveWriteDataError; return false; } } if (laRet != ARCHIVE_EOF) { LOGE("libarchive: Failed to read header: %s", archive_error_string(aInput)); error = ErrorCode::ArchiveReadHeaderError; return false; } if (cancelled) return false; return true; }
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; }
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; }
static int compress_one_file(zipFile archive, const string& src, const string& dst) { FILE * srcf = fopen(src.c_str(),"rb"); if(!srcf) return errno; zip_fileinfo fi = { 0 }; //http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute fi.external_fa = 0100777 << 16; time_t t; time(&t); struct tm * our_time = localtime(&t); if(our_time) { fi.tmz_date.tm_sec = our_time->tm_sec ; fi.tmz_date.tm_min = our_time->tm_min ; fi.tmz_date.tm_hour = our_time->tm_hour; fi.tmz_date.tm_mday = our_time->tm_mday; fi.tmz_date.tm_mon = our_time->tm_mon ; fi.tmz_date.tm_year = our_time->tm_year + 1900; } int r = zipOpenNewFileInZip (archive,dst.c_str(), &fi, // mod dates, etc?? NULL,0, NULL,0, NULL, // comment Z_DEFLATED, Z_DEFAULT_COMPRESSION); if(r != 0) { fclose(srcf); return r; } char buf[1024]; while(!feof(srcf)) { int rd = fread(buf,1,sizeof(buf),srcf); if(rd) { r = zipWriteInFileInZip(archive,buf,rd); if(r != 0) { fclose(srcf); return r; } } else break; } fclose(srcf); r = zipCloseFileInZip(archive); return r; }
bool ReleaseDialog::ZipAddFile(zipFile zf, QString lpszFileNameInZip, QString lpszFilePath, QString password, bool bUtf8) { zip_fileinfo FileInfo; ZeroMemory(&FileInfo, sizeof(FileInfo)); QTextCodec *codec = QTextCodec::codecForName("GBK"); QByteArray nameInZip = codec->fromUnicode(lpszFileNameInZip); ///gbk // QByteArray nameInZip = lpszFileNameInZip.toLocal8Bit(); ///utf-8 QByteArray pwd = password.toLocal8Bit(); if (bUtf8) { if (zipOpenNewFileInZip4(zf, nameInZip.data(), &FileInfo, NULL, 0, NULL, 0, NULL, Z_DEFLATED, 9, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, pwd.data(), 0, 0, ZIP_GPBF_LANGUAGE_ENCODING_FLAG) != ZIP_OK) { return FALSE; } } else { // QTextCodec *codec = QTextCodec::codecForName("GBK"); // QByteArray nameInZip = codec->fromUnicode(lpszFileNameInZip); if (zipOpenNewFileInZip(zf, nameInZip.data(), &FileInfo, NULL, 0, pwd.data(), 0, NULL, Z_DEFLATED, 9) != ZIP_OK) { return FALSE; } } LOKI_ON_BLOCK_EXIT(zipCloseFileInZip, zf); const qint64 BUFFER_SIZE = 4096; char *buffer = new char[BUFFER_SIZE]; QFile file(lpszFilePath); if(!file.open(QIODevice::ReadOnly)) return false; QDataStream in(&file); in.setVersion(QDataStream::Qt_5_4); qint64 size = file.size(); bar->setHidden(false); bar->setRange(0, size); bar->setValue(0); qint64 readCount = 0; qint64 index = size; qint64 total = 0; while (index > 0) { qint64 dwSizeToRead = index > BUFFER_SIZE ? BUFFER_SIZE : (size-total); memset(buffer,0,sizeof(char)*BUFFER_SIZE); readCount = in.readRawData(buffer, dwSizeToRead); if (zipWriteInFileInZip(zf, buffer, readCount)) { return FALSE; } total += readCount; index -= readCount; file.seek(total); bar->setValue(total); } bar->setHidden(true); delete []buffer; file.close(); return TRUE; }
bool DialogPackage::AddFileToPackage(const WCHAR* filePath, const WCHAR* zipPath) { std::string zipPathUTF8 = StringUtil::NarrowUTF8(zipPath); for (size_t i = 0, isize = zipPathUTF8.length(); i < isize; ++i) { if ((zipPathUTF8[i] & 0x80) != 0) { // UTF-8 lead bit is not zero so the string is non-ASCII. if (!m_AllowNonAsciiFilenames) { return false; } } if (zipPathUTF8[i] == '\\') { zipPathUTF8[i] = '/'; } } const uLong ZIP_UTF8_FLAG = 1 << 11; zip_fileinfo fi = {0}; if (zipOpenNewFileInZip4( m_ZipFile, zipPathUTF8.c_str(), &fi, nullptr, 0, nullptr, 0, nullptr, Z_DEFLATED, Z_DEFAULT_COMPRESSION, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, NULL, 0, 0, ZIP_UTF8_FLAG) != ZIP_OK) { return false; } bool result = true; if (filePath) { HANDLE file = CreateFile(filePath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) { result = false; } else { do { const DWORD bufferSize = 16 * 1024; BYTE buffer[bufferSize]; DWORD readSize; if (!ReadFile(file, buffer, bufferSize, &readSize, nullptr)) { result = false; } else if (readSize != 0) { result = zipWriteInFileInZip(m_ZipFile, buffer, (UINT)readSize) == ZIP_OK; } else { // EOF break; } } while (result); CloseHandle(file); } } else { // Directory entry, so nothing needs to be written. } return zipCloseFileInZip(m_ZipFile) == ZIP_OK && result; }
/* ======================== 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; }
long zipCompressFile( char **in, long in_count, char *out) { long status = 0; long i = 0; long size_read = 0; void* buf = NULL; FILE *in_ptr = NULL; long opt_compress_level = Z_DEFAULT_COMPRESSION; zipFile zf; zip_fileinfo zi; PRINT_INFO("LIBBMDZLIBINF Compressing file(s) to %s\n",out); /******************************/ /* walidacja parametrow */ /******************************/ if (in==NULL) { return ZLIB_DECOMP_NO_FILES_FOR_COMPRESSION; } for (i=0; i<in_count; i++) { if (in[i]==NULL) { return ZLIB_DECOMP_NO_FILES_FOR_COMPRESSION; } } if (out==NULL) { return ZLIB_DECOMP_NO_OUTPUT_FILE; } /******************************************/ /* ustawienie poziomu konmpresji (1-9) */ /******************************************/ opt_compress_level = 9; /************************************************/ /* sprawdzenie, czy pliki wejsciowe istnieja */ /************************************************/ for (i=0; i<in_count; i++) { in_ptr=fopen(in[i],"rb"); if (in_ptr==NULL) { return ZLIB_COMP_SRC_FILE_OPEN_ERROR; } else { fclose(in_ptr); } } buf=(void*)malloc(WRITEBUFFERSIZE); /************************************************/ /* otwarcie pliku zip do zapisu archiwum */ /************************************************/ zf=zipOpen(out,0); if (zf == NULL) { return ZLIB_COMP_DST_FILE_OPEN_ERROR; } /************************************************************/ /* dolaczenie wszystkich plikow z listy do archiwum */ /************************************************************/ for (i=0; i<in_count; i++) { /******************************************/ /* pobranie informacji o czasie pliku */ /******************************************/ zi.tmz_date.tm_sec = 0; zi.tmz_date.tm_min = 0; zi.tmz_date.tm_hour = 0; zi.tmz_date.tm_mday = 0; zi.tmz_date.tm_mon = 0; zi.tmz_date.tm_year = 0; zi.dosDate = 0; zi.internal_fa = 0; zi.external_fa = 0; filetime(in[i], &zi.tmz_date, &zi.dosDate); /******************************************/ /* stworzenie nowego pliku w archiwum */ /******************************************/ status=zipOpenNewFileInZip( zf, in[i], &zi, NULL, 0, NULL, 0, NULL, (opt_compress_level != 0) ? Z_DEFLATED : 0, opt_compress_level); if (status!=ZIP_OK) { continue; } /************************************************************/ /* otwarcie pliku zrodlowego dodawanego do archiwum */ /************************************************************/ in_ptr=fopen(in[i],"rb"); if (in_ptr==NULL) { continue; } do { status=ZIP_OK; /************************************/ /* odczyt z pliku zrodlowego */ /************************************/ size_read=(int)fread(buf,1,WRITEBUFFERSIZE,in_ptr); if (size_read < WRITEBUFFERSIZE) { if (feof(in_ptr)==0) { PRINT_ERROR("LIBBMDZLIBERR Error in reading file %s.\n\tError: .\n\tError=%i\n",in[i],-1); status=-1; } } /************************************/ /* zapis do pliku w archiwum zip */ /************************************/ if (size_read>0) { status=zipWriteInFileInZip(zf,buf,size_read); if (status<0) { PRINT_ERROR("LIBBMDZLIBERR Error in writing file %s to archive %s.\n\tError: .\n\tError=%i\n",in[i],out,-1); } } } while ((status==ZIP_OK) && (size_read>0)); /************************************************/ /* zamkniecie deskryptora pliku zrodlowego */ /************************************************/ fclose(in_ptr); if (status<0) { status=ZIP_ERRNO; } else { /******************************************/ /* zamkniecie pliku w archiwum zip */ /******************************************/ status=zipCloseFileInZip(zf); if (status!=ZIP_OK) { PRINT_ERROR("LIBBMDZLIBERR Error in closing file %s in archive.\n\tError: .\n\tError=%i\n",in[i],-1); } } } /************************************************************/ /* zamkniecie pliku zip calego spakowanego archiwum */ /************************************************************/ zipClose(zf,NULL); /******************/ /* porzadki */ /******************/ free(buf); return BMD_OK; }
/* ======================== 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 }
/* ======================== 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; }
void writeOutput(OutputState** state, char* ipsw) { OutputState* curFile; OutputState* next; zip_fileinfo info; struct tm* filedate; time_t tm_t; zipFile zip; tm_t = time(NULL); filedate = localtime(&tm_t); info.tmz_date.tm_sec = filedate->tm_sec; info.tmz_date.tm_min = filedate->tm_min; info.tmz_date.tm_hour = filedate->tm_hour; info.tmz_date.tm_mday = filedate->tm_mday; info.tmz_date.tm_mon = filedate->tm_mon ; info.tmz_date.tm_year = filedate->tm_year; info.dosDate = 0; info.internal_fa = 0; info.external_fa = 0; ASSERT(zip = zipOpen(ipsw, APPEND_STATUS_CREATE), "Cannot open output zip file"); next = *state; while(next != NULL) { curFile = next; next = next->next; printf("packing: %s (%ld)\n", curFile->fileName, (long) curFile->bufferSize); fflush(stdout); if(curFile->bufferSize > 0) { ASSERT(zipOpenNewFileInZip(zip, curFile->fileName, &info, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION) == 0, "error adding to zip"); if(curFile->tmpFileName == NULL) { ASSERT(zipWriteInFileInZip(zip, curFile->buffer, curFile->bufferSize) == 0, "error writing to zip"); } else { AbstractFile* tmpFile = createAbstractFileFromFile(fopen(curFile->tmpFileName, "rb")); char* buffer = malloc(DEFAULT_BUFFER_SIZE); size_t left = tmpFile->getLength(tmpFile); while(left > 0) { size_t toRead; if(left > DEFAULT_BUFFER_SIZE) toRead = DEFAULT_BUFFER_SIZE; else toRead = left; ASSERT(tmpFile->read(tmpFile, buffer, toRead) == toRead, "error reading data"); ASSERT(zipWriteInFileInZip(zip, buffer, toRead) == 0, "error writing to zip"); left -= toRead; } tmpFile->close(tmpFile); free(buffer); } } else { ASSERT(zipOpenNewFileInZip(zip, curFile->fileName, &info, NULL, 0, NULL, 0, NULL, 0, 0) == 0, "error adding to zip"); } ASSERT(zipCloseFileInZip(zip) == 0, "error closing file in zip"); if(curFile->tmpFileName) { unlink(curFile->tmpFileName); free(curFile->tmpFileName); } free(curFile->fileName); if(curFile->buffer) { free(curFile->buffer); } free(curFile); } zipClose(zip, NULL); }
static duk_ret_t dukzip_zip_add(duk_context *ctx) { zip_fileinfo zi = {0}; int res = ZIP_OK; zipFile archive = dukzip_zip_from_this(ctx); const char *filename = ""; duk_int_t level = Z_DEFAULT_COMPRESSION; duk_int_t method = Z_DEFLATED; const char *comment = ""; int datalen = 0; void *data = NULL; if (duk_is_object(ctx, 0)) { dukzip_zip_checkoptions(ctx, 0, &filename, &level, &method, &comment); duk_get_prop_string(ctx, 0, "data"); if (duk_is_string(ctx, -1)) { data = (void *)duk_get_lstring(ctx, -1, &datalen); } else if (duk_is_buffer(ctx, -1) || duk_is_object(ctx, -1)) { data = duk_require_buffer_data(ctx, -1, &datalen); } else { duk_error(ctx, DUK_ERR_TYPE_ERROR, "unable to write data to zip file (supported types: string, buffer)"); return -1; } } else { filename = duk_require_string(ctx, 0); if (duk_is_string(ctx, 1)) { data = (void *)duk_get_lstring(ctx, 1, &datalen); } else if (duk_is_buffer(ctx, 1) || duk_is_object(ctx, 1)) { data = duk_require_buffer_data(ctx, 1, &datalen); } else { duk_error(ctx, DUK_ERR_TYPE_ERROR, "unable to write argument to zip file (supported types: string, buffer)"); return -1; } if (duk_is_number(ctx, 2)) { level = duk_get_int(ctx, 2); } /* push dummy to normalize stack */ duk_push_string(ctx, "dummy"); } res = zipOpenNewFileInZip64(archive, filename, &zi, NULL, 0, NULL, 0, comment, method, level, 1); if (res != ZIP_OK) { goto error; } res = zipWriteInFileInZip(archive, data, datalen); if (res != ZIP_OK) { goto error; } res = zipCloseFileInZip(archive); duk_pop(ctx); /* pop buffer (or dummy) from stack */ if (res == ZIP_OK) { duk_push_true(ctx); } else { duk_push_false(ctx); } return 1; error: zipCloseFileInZip(archive); duk_error(ctx, DUK_ERR_INTERNAL_ERROR, "could not write file '%s'", filename); return -1; }
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; }
// This method compresses the files contained in the report and produces ZIP archive. BOOL CErrorReportSender::CompressReportFiles() { BOOL bStatus = FALSE; strconv_t strconv; zipFile hZip = NULL; CString sMsg; LONG64 lTotalSize = 0; LONG64 lTotalCompressed = 0; BYTE buff[1024]; DWORD dwBytesRead=0; HANDLE hFile = INVALID_HANDLE_VALUE; std::map<CString, FileItem>::iterator it; LARGE_INTEGER lFileSize; BOOL bGetSize = FALSE; if(m_bExport) m_Assync.SetProgress(_T("[exporting_report]"), 0, false); else m_Assync.SetProgress(_T("[compressing_files]"), 0, false); m_Assync.SetProgress(_T("Calculating total size of files to compress..."), 0, false); for(it=g_CrashInfo.m_FileItems.begin(); it!=g_CrashInfo.m_FileItems.end(); it++) { if(m_Assync.IsCancelled()) goto cleanup; CString sFileName = it->second.m_sSrcFile.GetBuffer(0); hFile = CreateFile(sFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL); if(hFile==INVALID_HANDLE_VALUE) { sMsg.Format(_T("Couldn't open file %s"), sFileName); m_Assync.SetProgress(sMsg, 0, false); continue; } bGetSize = GetFileSizeEx(hFile, &lFileSize); if(!bGetSize) { sMsg.Format(_T("Couldn't get file size of %s"), sFileName); m_Assync.SetProgress(sMsg, 0, false); CloseHandle(hFile); continue; } lTotalSize += lFileSize.QuadPart; CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; } sMsg.Format(_T("Total file size for compression is %I64d"), lTotalSize); m_Assync.SetProgress(sMsg, 0, false); if(m_bExport) m_sZipName = m_sExportFileName; else m_sZipName = g_CrashInfo.m_sErrorReportDirName + _T(".zip"); sMsg.Format(_T("Creating ZIP archive file %s"), m_sZipName); m_Assync.SetProgress(sMsg, 1, false); hZip = zipOpen(strconv.t2a(m_sZipName.GetBuffer(0)), APPEND_STATUS_CREATE); if(hZip==NULL) { m_Assync.SetProgress(_T("Failed to create ZIP file."), 100, true); goto cleanup; } for(it=g_CrashInfo.m_FileItems.begin(); it!=g_CrashInfo.m_FileItems.end(); it++) { if(m_Assync.IsCancelled()) goto cleanup; CString sDstFileName = it->second.m_sDestFile.GetBuffer(0); CString sFileName = it->second.m_sSrcFile.GetBuffer(0); CString sDesc = it->second.m_sDesc; sMsg.Format(_T("Compressing %s"), sDstFileName); m_Assync.SetProgress(sMsg, 0, false); HANDLE hFile = CreateFile(sFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL); if(hFile==INVALID_HANDLE_VALUE) { sMsg.Format(_T("Couldn't open file %s"), sFileName); m_Assync.SetProgress(sMsg, 0, false); continue; } BY_HANDLE_FILE_INFORMATION fi; GetFileInformationByHandle(hFile, &fi); SYSTEMTIME st; FileTimeToSystemTime(&fi.ftCreationTime, &st); zip_fileinfo info; info.dosDate = 0; info.tmz_date.tm_year = st.wYear; info.tmz_date.tm_mon = st.wMonth; info.tmz_date.tm_mday = st.wDay; info.tmz_date.tm_hour = st.wHour; info.tmz_date.tm_min = st.wMinute; info.tmz_date.tm_sec = st.wSecond; info.external_fa = FILE_ATTRIBUTE_NORMAL; info.internal_fa = FILE_ATTRIBUTE_NORMAL; int n = zipOpenNewFileInZip( hZip, strconv.t2a(sDstFileName), &info, NULL, 0, NULL, 0, strconv.t2a(sDesc), Z_DEFLATED, Z_DEFAULT_COMPRESSION); if(n!=0) { sMsg.Format(_T("Couldn't compress file %s"), sDstFileName); m_Assync.SetProgress(sMsg, 0, false); continue; } for(;;) { if(m_Assync.IsCancelled()) goto cleanup; BOOL bRead = ReadFile(hFile, buff, 1024, &dwBytesRead, NULL); if(!bRead || dwBytesRead==0) break; int res = zipWriteInFileInZip(hZip, buff, dwBytesRead); if(res!=0) { zipCloseFileInZip(hZip); sMsg.Format(_T("Couldn't write to compressed file %s"), sDstFileName); m_Assync.SetProgress(sMsg, 0, false); break; } lTotalCompressed += dwBytesRead; float fProgress = 100.0f*lTotalCompressed/lTotalSize; m_Assync.SetProgress((int)fProgress, false); } zipCloseFileInZip(hZip); CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; } if(lTotalSize==lTotalCompressed) bStatus = TRUE; cleanup: if(hZip!=NULL) zipClose(hZip, NULL); if(hFile!=INVALID_HANDLE_VALUE) CloseHandle(hFile); if(bStatus) m_Assync.SetProgress(_T("Finished compressing files...OK"), 100, true); else m_Assync.SetProgress(_T("File compression failed."), 100, true); if(m_bExport) { if(bStatus) m_Assync.SetProgress(_T("[end_exporting_report_ok]"), 100, false); else m_Assync.SetProgress(_T("[end_exporting_report_failed]"), 100, false); } else { m_Assync.SetProgress(_T("[end_compressing_files]"), 100, false); } return bStatus; }
bool MakeZip(TCHAR *tszSource, TCHAR *tszDest, TCHAR *dbname, HWND progress_dialog) { bool ret = false; HANDLE hSrc; zipFile hZip; SYSTEMTIME st; WIN32_FILE_ATTRIBUTE_DATA fad = { 0 }; zip_fileinfo fi = { 0 }; HWND hProgBar; DWORD dwRead; MSG msg; char buf[(256 * 1024)]; // 256 KB DWORDLONG dwSrcFileSize, dwTotalBytes = 0; ptrA szSourceName(mir_u2a(dbname)); ptrT tszDestPath(DoubleSlash(tszDest)); hSrc = CreateFile(tszSource, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hSrc == INVALID_HANDLE_VALUE) return ret; if (GetFileAttributesEx(tszSource, GetFileExInfoStandard, &fad) == FALSE) goto err_out; dwSrcFileSize = ((DWORDLONG)fad.nFileSizeLow | (((DWORDLONG)fad.nFileSizeHigh) << 32)); if (dwSrcFileSize == 0) /* Prevent division by zero error. */ goto err_out; FileTimeToLocalFileTime(&fad.ftLastWriteTime, &fad.ftLastWriteTime); FileTimeToSystemTime(&fad.ftLastWriteTime, &st); hZip = zipOpen2_64(tszDestPath, APPEND_STATUS_CREATE, NULL, NULL); if (hZip == NULL) goto err_out; fi.tmz_date.tm_sec = st.wSecond; fi.tmz_date.tm_min = st.wMinute; fi.tmz_date.tm_hour = st.wHour; fi.tmz_date.tm_mday = st.wDay; fi.tmz_date.tm_mon = (st.wMonth - 1); fi.tmz_date.tm_year = st.wYear; if (zipOpenNewFileInZip(hZip, szSourceName, &fi, NULL, 0, NULL, 0, "", Z_DEFLATED, Z_BEST_COMPRESSION) == ZIP_OK) { hProgBar = GetDlgItem(progress_dialog, IDC_PROGRESS); while (GetWindowLongPtr(progress_dialog, GWLP_USERDATA) != 1) { if (!ReadFile(hSrc, buf, sizeof(buf), &dwRead, NULL)) break; if (dwRead == 0) { // EOF ret = true; break; } if (zipWriteInFileInZip(hZip, buf, dwRead) != ZIP_OK) break; dwTotalBytes += dwRead; SendMessage(hProgBar, PBM_SETPOS, (WPARAM)((100 * dwTotalBytes) / dwSrcFileSize), 0); while (PeekMessage(&msg, progress_dialog, 0, 0, PM_REMOVE) != 0) { if (progress_dialog == NULL || !IsDialogMessage(progress_dialog, &msg)) { /* Wine fix. */ TranslateMessage(&msg); DispatchMessage(&msg); } } } zipCloseFileInZip(hZip); } if (ret) { mir_snprintf(buf, "%s\r\n%s %s %d.%d.%d.%d\r\n", Translate("Miranda NG database"), Translate("Created by:"), __PLUGIN_NAME, __MAJOR_VERSION, __MINOR_VERSION, __RELEASE_NUM, __BUILD_NUM); } else { buf[0] = 0; } zipClose(hZip, buf); err_out: CloseHandle(hSrc); return ret; }
/////////////////////////////////////////////////////////////// // // 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; }
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; }
static cell_t Zip_AddFile(IPluginContext *pCtx, const cell_t *params) { Handle_t handle = static_cast<Handle_t>(params[1]); HandleError err; HandleSecurity sec; cell_t ret = true; sec.pOwner = NULL; sec.pIdentity = myself->GetIdentity(); zipFile zf; err = handlesys->ReadHandle(handle, g_ZipFileType, &sec, (void **)&zf); if (HandleError_None != err) { return pCtx->ThrowNativeError("Invalid Zip file handle %x (error %d)", handle, err); } char path[PLATFORM_MAX_PATH]; char *filename; pCtx->LocalToString(params[2], &filename); g_pSM->BuildPath(Path_Game, path, sizeof(path), "%s", filename); zip_fileinfo zi; memset(&zi, 0, sizeof(zi)); int zipErr = zipOpenNewFileInZip64(zf, filename, &zi, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION, isLargeFile(path)); if (ZIP_OK != zipErr) { g_pSM->LogError(myself, "Could not open new file %s in zip (%d)", filename, err); return false; } FILE *fp = fopen64(path, "rb"); if (NULL == fp) { g_pSM->LogError(myself, "fopen64(%s) failed", path); ret = false; } if (ret) { char buf[4096]; size_t bytesRead = 0; do { zipErr = ZIP_OK; bytesRead = fread(buf, 1, sizeof(buf), fp); if (bytesRead < sizeof(buf) && feof(fp) != 0) { zipErr = ZIP_ERRNO; } if (bytesRead > 0) { zipErr = zipWriteInFileInZip(zf, buf, bytesRead); } if (ZIP_ERRNO == zipErr && EAGAIN == errno) zipErr = ZIP_OK; } while (ZIP_OK == zipErr && bytesRead > 0); if (ZIP_OK != zipErr) { if (ZIP_ERRNO == zipErr) g_pSM->LogError(myself, "Failed to write to zip archive (%s)", strerror(errno)); else g_pSM->LogError(myself, "Failed to write to zip archive (%d)", zipErr); ret = false; } } if (fp) fclose(fp); zipCloseFileInZip(zf); return ret; }
int createZIP(gameSave_t *save, device_t src) { FILE *mcFile; zipFile zf; zip_fileinfo zfi; sceMcTblGetDir mcDir[64] __attribute__((aligned(64))); fio_stat_t stat; char mcPath[100]; char zipPath[100]; char filePath[150]; char validName[32]; char *data; int i; int ret; float progress = 0.0; if(!save || !(src & (MC_SLOT_1|MC_SLOT_2))) return 0; replaceIllegalChars(save->name, validName, '-'); rtrim(validName); snprintf(zipPath, 100, "%s%s.zip", flashDriveDevice, validName); if(fioGetstat(zipPath, &stat) == 0) { const char *items[] = {"Yes", "No"}; int choice = displayPromptMenu(items, 2, "Save already exists. Do you want to overwrite it?"); if(choice == 1) return 0; } zf = zipOpen(zipPath, APPEND_STATUS_CREATE); if(!zf) return 0; snprintf(mcPath, 100, "%s/*", strstr(save->path, ":") + 1); mcGetDir((src == MC_SLOT_1) ? 0 : 1, 0, mcPath, 0, 54, mcDir); mcSync(0, NULL, &ret); for(i = 0; i < ret; i++) { if(mcDir[i].AttrFile & MC_ATTR_SUBDIR) continue; else if(mcDir[i].AttrFile & MC_ATTR_FILE) { progress += (float)1/(ret-2); drawCopyProgress(progress); snprintf(filePath, 100, "%s/%s", save->path, mcDir[i].EntryName); mcFile = fopen(filePath, "rb"); data = malloc(mcDir[i].FileSizeByte); fread(data, 1, mcDir[i].FileSizeByte, mcFile); fclose(mcFile); if(zipOpenNewFileInZip(zf, strstr(filePath, ":") + 1, &zfi, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_BEST_COMPRESSION) == ZIP_OK) { zipWriteInFileInZip(zf, data, mcDir[i].FileSizeByte); zipCloseFileInZip(zf); } else { zipClose(zf, NULL); free(data); return 0; } free(data); } } zipClose(zf, NULL); return 1; }
int main(int argc, char *argv[]) { zipFile zf = NULL; #ifdef USEWIN32IOAPI zlib_filefunc64_def ffunc = {0}; #endif char *zipfilename = NULL; const char* password = NULL; void* buf = NULL; int size_buf = WRITEBUFFERSIZE; int zipfilenamearg = 0; int errclose = 0; int err = 0; int i = 0; int opt_overwrite = APPEND_STATUS_CREATE; int opt_compress_level = Z_DEFAULT_COMPRESSION; int opt_exclude_path = 0; do_banner(); if (argc == 1) { do_help(); return 0; } /* Parse command line options */ 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 = APPEND_STATUS_CREATEAFTER; if ((c == 'a') || (c == 'A')) opt_overwrite = APPEND_STATUS_ADDINZIP; if ((c >= '0') && (c <= '9')) opt_compress_level = (c - '0'); if ((c == 'j') || (c == 'J')) opt_exclude_path = 1; if (((c == 'p') || (c == 'P')) && (i+1 < argc)) { password=argv[i+1]; i++; } } } else { if (zipfilenamearg == 0) zipfilenamearg = i; } } if (zipfilenamearg == 0) { do_help(); return 0; } zipfilename = argv[zipfilenamearg]; buf = (void*)malloc(size_buf); if (buf == NULL) { printf("Error allocating memory\n"); return ZIP_INTERNALERROR; } if (opt_overwrite == 2) { /* If the file don't exist, we not append file */ if (check_file_exists(zipfilename) == 0) opt_overwrite = 1; } else if (opt_overwrite == 0) { /* If ask the user what to do because append and overwrite args not set */ //if (check_file_exists(zipfilename) != 0) //{ // char rep = 0; // do // { // char answer[128]; // printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ", zipfilename); // if (scanf("%1s", answer) != 1) // exit(EXIT_FAILURE); // rep = answer[0]; // if ((rep >= 'a') && (rep <= 'z')) // rep -= 0x20; // } // while ((rep != 'Y') && (rep != 'N') && (rep != 'A')); // if (rep == 'A') // opt_overwrite = 2; // else if (rep == 'N') // { // do_help(); // free(buf); // return 0; // } //} } #ifdef USEWIN32IOAPI fill_win32_filefunc64A(&ffunc); zf = zipOpen2_64(zipfilename, opt_overwrite, NULL, &ffunc); #else zf = zipOpen64(zipfilename, opt_overwrite); #endif if (zf == NULL) { printf("error opening %s\n", zipfilename); err = ZIP_ERRNO; } else printf("creating %s\n", zipfilename); /* Go through command line args looking for files to add to zip */ for (i = zipfilenamearg + 1; (i < argc) && (err == ZIP_OK); i++) { FILE *fin = NULL; int size_read = 0; const char* filenameinzip = argv[i]; const char *savefilenameinzip; zip_fileinfo zi = {0}; unsigned long crcFile = 0; int zip64 = 0; /* Skip command line options */ if ((((*(argv[i])) == '-') || ((*(argv[i])) == '/')) && (strlen(argv[i]) == 2) && ((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')))) continue; /* Get information about the file on disk so we can store it in zip */ filetime(filenameinzip, &zi.tmz_date, &zi.dosDate); if ((password != NULL) && (err == ZIP_OK)) err = get_file_crc(filenameinzip, buf, size_buf, &crcFile); zip64 = is_large_file(filenameinzip); /* Construct the filename that our file will be stored in the zip as. The path name saved, should not include a leading slash. If it did, windows/xp and dynazip couldn't read the zip file. */ savefilenameinzip = filenameinzip; while (savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/') savefilenameinzip++; /* Should the file be stored with any path info at all? */ if (opt_exclude_path) { const char *tmpptr = NULL; const char *lastslash = 0; for (tmpptr = savefilenameinzip; *tmpptr; tmpptr++) { if (*tmpptr == '\\' || *tmpptr == '/') lastslash = tmpptr; } if (lastslash != NULL) savefilenameinzip = lastslash + 1; /* base filename follows last slash. */ } /* Add to zip file */ err = zipOpenNewFileInZip3_64(zf, savefilenameinzip, &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, password, crcFile, zip64); if (err != ZIP_OK) printf("error in opening %s in zipfile (%d)\n", filenameinzip, err); else { fin = FOPEN_FUNC(filenameinzip, "rb"); if (fin == NULL) { err = ZIP_ERRNO; printf("error in opening %s for reading\n", filenameinzip); } } if (err == ZIP_OK) { /* Read contents of file and write it to zip */ do { size_read = (int)fread(buf, 1, size_buf, fin); if ((size_read < size_buf) && (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 (%d)\n", filenameinzip, err); } } 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 (%d)\n", filenameinzip, err); } } errclose = zipClose(zf, NULL); if (errclose != ZIP_OK) printf("error in closing %s (%d)\n", zipfilename, errclose); free(buf); return err; }
extern "C" bool ArchAddFileW(HZIP hZip,WCHAR *pstrSourceFile,WCHAR *pstrDestFile) { bool r=false; if ((hZip) && (((ZIPCOMPRESSION *)hZip)->bHandleType == HT_COMPRESSOR) && (pstrSourceFile) && (pstrDestFile)) { int lDest,lSrc; if (((lDest=lstrlenW(pstrDestFile)) < MAX_PATH-1) && ((lSrc=lstrlenW(pstrSourceFile)) < MAX_PATH-1)) { ZIPCOMPRESSION *p=(ZIPCOMPRESSION *)hZip; char *file=UnicodeToOemEx(pstrDestFile,lDest); if (file) { void *buf=_alloc(INT_BUF_SIZE); if (buf) { p->bInMem=false; zip_fileinfo zi={0}; filetime(pstrSourceFile,&zi.tmz_date,&zi.dosDate); char *lpPassword=NULL; unsigned long crcFile=0; if (p->bEncrypted) { getFileCrc(pstrSourceFile,buf,INT_BUF_SIZE,&crcFile); lpPassword=p->szPassword; } int err=zipOpenNewFileInZip3_64(p->hZip,file,&zi,NULL,0,NULL,0,NULL,(p->dwCompLevel>0) ? Z_DEFLATED:0,p->dwCompLevel,0,-MAX_WBITS,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY,lpPassword,crcFile,0); if (err == ZIP_OK) { HANDLE fin=CreateFileW(pstrSourceFile,GENERIC_READ,0,NULL,OPEN_EXISTING,0,NULL); if (fin != INVALID_HANDLE_VALUE) { unsigned long size_read = 0; do { err=ZIP_OK; ReadFile(fin,buf,INT_BUF_SIZE,&size_read,0); if (size_read < INT_BUF_SIZE) { if (!_feof(fin)) err=ZIP_ERRNO; } if (size_read>0) err=zipWriteInFileInZip(p->hZip,buf,size_read); } while ((err == ZIP_OK) && (size_read>0)); SysCloseHandle(fin); if (err<0) err=ZIP_ERRNO; else { err=zipCloseFileInZip(p->hZip); r=true; } } } MemFree(buf); } } MemFree(file); } } else ArchSetLastError(ARCH_INVALID_PARAMETER); return r; }
int TRI_ZipFile (const char* filename, const char* dir, TRI_vector_string_t const* files, const char* password) { void* buffer; size_t bufferSize; zipFile zf; #ifdef USEWIN32IOAPI zlib_filefunc64_def ffunc; #endif size_t i, n; int res; if (TRI_ExistsFile(filename)) { return TRI_ERROR_CANNOT_OVERWRITE_FILE; } bufferSize = 16384; buffer = TRI_Allocate(TRI_UNKNOWN_MEM_ZONE, bufferSize, false); if (buffer == NULL) { return TRI_ERROR_OUT_OF_MEMORY; } #ifdef USEWIN32IOAPI fill_win32_filefunc64A(&ffunc); zf = zipOpen2_64(filename, 0, NULL, &ffunc); #else zf = zipOpen64(filename, 0); #endif if (zf == NULL) { TRI_Free(TRI_UNKNOWN_MEM_ZONE, buffer); return ZIP_ERRNO; } res = TRI_ERROR_NO_ERROR; n = files->_length; for (i = 0; i < n; ++i) { FILE* fin; char* file; char* fullfile; char* saveName; zip_fileinfo zi; uint32_t crc; int isLarge; file = TRI_AtVectorString(files, i); if (*dir == '\0') { fullfile = TRI_DuplicateString(file); } else { fullfile = TRI_Concatenate2File(dir, file); } memset(&zi, 0, sizeof(zi)); res = TRI_Crc32File(fullfile, &crc); if (res != TRI_ERROR_NO_ERROR) { break; } isLarge = (TRI_SizeFile(file) > 0xFFFFFFFFLL); saveName = file; while (*saveName == '\\' || *saveName == '/') { ++saveName; } if (zipOpenNewFileInZip3_64(zf, saveName, &zi, NULL, 0, NULL, 0, NULL, /* comment*/ Z_DEFLATED, Z_DEFAULT_COMPRESSION, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, password, (unsigned long) crc, isLarge) != ZIP_OK) { } fin = fopen(fullfile, "rb"); TRI_FreeString(TRI_CORE_MEM_ZONE, fullfile); if (fin == NULL) { break; } while (true) { int sizeRead; sizeRead = (int) fread(buffer, 1, bufferSize, fin); if (sizeRead < bufferSize) { if (feof(fin) == 0) { res = TRI_set_errno(TRI_ERROR_SYS_ERROR); break; } } if (sizeRead > 0) { res = zipWriteInFileInZip(zf, buffer, sizeRead); if (res != 0) { break; } } else if (sizeRead <= 0) { break; } } fclose(fin); zipCloseFileInZip(zf); if (res != TRI_ERROR_NO_ERROR) { break; } } zipClose(zf, NULL); TRI_Free(TRI_UNKNOWN_MEM_ZONE, buffer); return res; }
// This method compresses the files contained in the report and produces a ZIP archive. BOOL CErrorReportExporter::CompressReportFiles(CErrorReportInfo* eri) { BOOL bStatus = FALSE; strconv_t strconv; zipFile hZip = NULL; CString sMsg; LONG64 lTotalSize = 0; LONG64 lTotalCompressed = 0; BYTE buff[1024]; DWORD dwBytesRead=0; HANDLE hFile = INVALID_HANDLE_VALUE; std::map<CString, ERIFileItem>::iterator it; FILE* f = NULL; CString sMD5Hash; // Add a different log message depending on the current mode. if(m_bExport) m_Assync.SetProgress(_T("[exporting_report]"), 0, false); else m_Assync.SetProgress(_T("[compressing_files]"), 0, false); // Calculate the total size of error report files lTotalSize = eri->GetTotalSize(); // Add a message to log sMsg.Format(_T("Total file size for compression is %I64d bytes"), lTotalSize); m_Assync.SetProgress(sMsg, 0, false); // Determine what name to use for the output ZIP archive file. if(m_bExport) m_sZipName = m_sExportFileName; else m_sZipName = eri->GetErrorReportDirName() + _T(".zip"); // Update progress sMsg.Format(_T("Creating ZIP archive file %s"), m_sZipName); m_Assync.SetProgress(sMsg, 1, false); // Create ZIP archive hZip = zipOpen((const char*)m_sZipName.GetBuffer(0), APPEND_STATUS_CREATE); if(hZip==NULL) { m_Assync.SetProgress(_T("Failed to create ZIP file."), 100, true); goto cleanup; } // Enumerate files contained in the report int i; for(i=0; i<eri->GetFileItemCount(); i++) { ERIFileItem* pfi = eri->GetFileItemByIndex(i); // Check if the operation was cancelled by user if(m_Assync.IsCancelled()) goto cleanup; // Define destination file name in ZIP archive CString sDstFileName = pfi->m_sDestFile.GetBuffer(0); // Define source file name CString sFileName = pfi->m_sSrcFile.GetBuffer(0); // Define file description CString sDesc = pfi->m_sDesc; // Update progress sMsg.Format(_T("Compressing file %s"), sDstFileName); m_Assync.SetProgress(sMsg, 0, false); // Open file for reading hFile = CreateFile(sFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL); if(hFile==INVALID_HANDLE_VALUE) { sMsg.Format(_T("Couldn't open file %s"), sFileName); m_Assync.SetProgress(sMsg, 0, false); continue; } // Get file information. BY_HANDLE_FILE_INFORMATION fi; GetFileInformationByHandle(hFile, &fi); // Convert file creation time to system file time. SYSTEMTIME st; FileTimeToSystemTime(&fi.ftLastWriteTime, &st); // Fill in the ZIP file info zip_fileinfo info; info.dosDate = 0; info.tmz_date.tm_year = st.wYear; info.tmz_date.tm_mon = st.wMonth-1; info.tmz_date.tm_mday = st.wDay; info.tmz_date.tm_hour = st.wHour; info.tmz_date.tm_min = st.wMinute; info.tmz_date.tm_sec = st.wSecond; info.external_fa = FILE_ATTRIBUTE_NORMAL; info.internal_fa = FILE_ATTRIBUTE_NORMAL; // Create new file inside of our ZIP archive int n = zipOpenNewFileInZip( hZip, (const char*)strconv.t2a(sDstFileName.GetBuffer(0)), &info, NULL, 0, NULL, 0, strconv.t2a(sDesc), Z_DEFLATED, Z_DEFAULT_COMPRESSION); if(n!=0) { sMsg.Format(_T("Couldn't compress file %s"), sDstFileName); m_Assync.SetProgress(sMsg, 0, false); continue; } // Read source file contents and write it to ZIP archive for(;;) { // Check if operation was cancelled by user if(m_Assync.IsCancelled()) goto cleanup; // Read a portion of source file BOOL bRead = ReadFile(hFile, buff, 1024, &dwBytesRead, NULL); if(!bRead || dwBytesRead==0) break; // Write a portion into destination file int res = zipWriteInFileInZip(hZip, buff, dwBytesRead); if(res!=0) { zipCloseFileInZip(hZip); sMsg.Format(_T("Couldn't write to compressed file %s"), sDstFileName); m_Assync.SetProgress(sMsg, 0, false); break; } // Update totals lTotalCompressed += dwBytesRead; // Update progress float fProgress = 100.0f*lTotalCompressed/lTotalSize; m_Assync.SetProgress((int)fProgress, false); } // Close file zipCloseFileInZip(hZip); CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; } // Close ZIP archive if(hZip!=NULL) { zipClose(hZip, NULL); hZip = NULL; } // Check if totals match if(lTotalSize==lTotalCompressed) bStatus = TRUE; cleanup: // Clean up if(hZip!=NULL) zipClose(hZip, NULL); if(hFile!=INVALID_HANDLE_VALUE) CloseHandle(hFile); if(f!=NULL) fclose(f); if(bStatus) m_Assync.SetProgress(_T("Finished compressing files...OK"), 100, true); else m_Assync.SetProgress(_T("File compression failed."), 100, true); if(m_bExport) { if(bStatus) m_Assync.SetProgress(_T("[end_exporting_report_ok]"), 100, false); else m_Assync.SetProgress(_T("[end_exporting_report_failed]"), 100, false); } else { m_Assync.SetProgress(_T("[end_compressing_files]"), 100, false); } return bStatus; }
int ZipFile::AddFile(const char *filepath, const char *destfilepath, int compresslevel, bool RefreshList) { if(!destfilepath) return -1; if(OpenMode == ZipFile::OPEN) { if(!SwitchMode(ZipFile::APPEND)) return -2; } else if(!SwitchMode(OpenMode)) return -3; zip_fileinfo file_info; memset(&file_info, 0, sizeof(zip_fileinfo)); if(destfilepath[strlen(destfilepath)-1] == '/') { int ret = zipOpenNewFileInZip(zFile, destfilepath, &file_info, NULL, 0, NULL, 0, NULL, Z_DEFLATED, compresslevel); if(ret != ZIP_OK) return -4; zipCloseFileInZip(zFile); return 1; } if(!filepath) return -5; struct stat filestat; memset(&filestat, 0, sizeof(struct stat)); stat(filepath, &filestat); u64 filesize = filestat.st_size; //! Set up the modified time struct tm * ModTime = localtime(&filestat.st_mtime); file_info.tmz_date.tm_sec = ModTime->tm_sec; file_info.tmz_date.tm_min = ModTime->tm_min; file_info.tmz_date.tm_hour = ModTime->tm_hour; file_info.tmz_date.tm_mday = ModTime->tm_mday; file_info.tmz_date.tm_mon = ModTime->tm_mon; file_info.tmz_date.tm_year = ModTime->tm_year; FILE * sourceFile = fopen(filepath, "rb"); if(!sourceFile) return -6; u32 blocksize = 1024*70; u8 * buffer = (u8 *) malloc(blocksize); if(!buffer) { fclose(sourceFile); return -7; } int ret = zipOpenNewFileInZip(zFile, destfilepath, &file_info, NULL, 0, NULL, 0, NULL, Z_DEFLATED, compresslevel); if(ret != ZIP_OK) { free(buffer); fclose(sourceFile); return -8; } const char * RealFilename = strrchr(destfilepath, '/'); if(RealFilename) RealFilename += 1; else RealFilename = destfilepath; int res = 0; u64 done = 0; while(done < filesize) { if(filesize - done < blocksize) blocksize = filesize - done; ret = fread(buffer, 1, blocksize, sourceFile); if(ret <= 0) break; //done res = zipWriteInFileInZip(zFile, buffer, ret); if(res != ZIP_OK) break; done += ret; } free(buffer); fclose(sourceFile); zipCloseFileInZip(zFile); if(RefreshList) LoadList(); //! File is now created the next files need to be appended OpenMode = ZipFile::APPEND; return (done == filesize) ? 1 : -12; }
int _compress(const char** srcs, int src_num, const char** srcspath, int srcpath_num, const char* dst, int level, const char* password, int exclude_path, PyObject* progress) { zipFile zf = NULL; int size_buf = WRITEBUFFERSIZE; int opt_overwrite = APPEND_STATUS_CREATE; int err = ZIP_OK; int errclose = 0; int i; #ifdef USEWIN32IOAPI zlib_filefunc64_def ffunc = {0}; #endif void* buf = NULL; buf = (void*)malloc(size_buf); if (buf == NULL) { pyerr_msg = PyErr_Format(PyExc_MemoryError, "could not allocate memory"); return ZIP_ERRNO; } if (srcpath_num > 0) assert(src_num == srcpath_num); #ifdef USEWIN32IOAPI fill_win32_filefunc64A(&ffunc); zf = zipOpen2_64(dst, opt_overwrite, NULL, &ffunc); #else zf = zipOpen64(dst, opt_overwrite); #endif if (zf == NULL) { pyerr_msg = PyErr_Format(PyExc_IOError, "error opening %s", dst); err = ZIP_ERRNO; } for (i = 0; i < src_num && (err == ZIP_OK); i++) { FILE *fin = NULL; int size_read = 0; const char* filenameinzip = srcs[i]; const char* filepathnameinzip; const char *savefilenameinzip; const char *savefilepathnameinzip = NULL; char *fullpathfileinzip = NULL; unsigned long crcFile = 0; int zip64 = 0; zip_fileinfo zi; memset(&zi, 0, sizeof(zip_fileinfo)); if (srcpath_num > 0) filepathnameinzip = srcspath[i]; /* Get information about the file on disk so we can store it in zip */ filetime(filenameinzip, &zi.tmz_date, &zi.dosDate); if ((password != NULL) && (err == ZIP_OK)) err = get_file_crc(filenameinzip, buf, size_buf, &crcFile); zip64 = is_large_file(filenameinzip); /* Construct the filename that our file will be stored in the zip as. The path name saved, should not include a leading slash. If it did, windows/xp and dynazip couldn't read the zip file. */ savefilenameinzip = filenameinzip; while (savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/') savefilenameinzip++; if (srcpath_num > 0) { savefilepathnameinzip = filepathnameinzip; while (savefilepathnameinzip[0] == '\\' || savefilepathnameinzip[0] == '/') savefilepathnameinzip++; } /* Should the file be stored with any path info at all? */ if (exclude_path) { const char *tmpptr = NULL; const char *lastslash = NULL; for (tmpptr = savefilenameinzip; *tmpptr; tmpptr++) { if (*tmpptr == '\\' || *tmpptr == '/') lastslash = tmpptr; } if (lastslash != NULL) savefilenameinzip = lastslash + 1; // base filename follows last slash. if (srcpath_num > 0) { /* prepend savefilepathnameinzip for each savefilenameinzip */ const char * slash; #if (defined(_WIN32)) const char default_slash = '\\'; #else const char default_slash = '/'; #endif size_t extra_len = 0; size_t filename_len = strlen(savefilenameinzip); size_t filepathname_len = strlen(savefilepathnameinzip); /* look for slash used in filepath */ slash = strchr(savefilepathnameinzip, '/'); if (slash == NULL) { slash = strchr(savefilepathnameinzip, '\\'); if (slash == NULL) { // no slash found.. use default slash = &default_slash; } } if (savefilepathnameinzip[filepathname_len-1] != *slash) extra_len = 1; /* allocate buffer */ fullpathfileinzip = (char *)malloc(filename_len + filepathname_len + extra_len + 1); if (fullpathfileinzip == NULL) { free(buf); pyerr_msg = PyErr_Format(PyExc_MemoryError, "error allocating memory on minizip compress"); return ZIP_INTERNALERROR; } strncpy(fullpathfileinzip, savefilepathnameinzip, filepathname_len); if (extra_len) fullpathfileinzip[filepathname_len] = *slash; strncpy(fullpathfileinzip + filepathname_len + extra_len, savefilenameinzip, filename_len); /* terminate string */ fullpathfileinzip[filename_len + filepathname_len + extra_len] = '\0'; /* set pointer */ savefilenameinzip = fullpathfileinzip; } } /* Add to zip file */ err = zipOpenNewFileInZip3_64(zf, savefilenameinzip, &zi, NULL, 0, NULL, 0, NULL /* comment*/, (level != 0) ? Z_DEFLATED : 0, level, 0, /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */ -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, password, crcFile, zip64); if (err != ZIP_OK) { pyerr_msg = PyErr_Format(PyExc_IOError, "error in opening %s in zipfile (%d)", filenameinzip, err); err = ZIP_ERRNO; } else { fin = FOPEN_FUNC(filenameinzip, "rb"); if (fin == NULL) { pyerr_msg = PyErr_Format(PyExc_IOError, "error in opening %s for reading", filenameinzip); err = ZIP_ERRNO; } } if (err == ZIP_OK) { /* Read contents of file and write it to zip */ do { size_read = (int)fread(buf, 1, size_buf, fin); if ((size_read < size_buf) && (feof(fin) == 0)) { pyerr_msg = PyErr_Format(PyExc_IOError, "error in reading %s", filenameinzip); err = ZIP_ERRNO; } if (0 < size_read) { err = zipWriteInFileInZip(zf, buf, size_read); if (err < 0) { pyerr_msg = PyErr_Format(PyExc_IOError, "error in writing %s in the zipfile (%d)", filenameinzip, err); err = ZIP_ERRNO; } } } while ((err == ZIP_OK) && (size_read > 0)); } if (fin) fclose(fin); if (err == ZIP_OK) { err = zipCloseFileInZip(zf); if (err != ZIP_OK) { pyerr_msg = PyErr_Format(PyExc_IOError, "error in closing %s in the zipfile (%d)", filenameinzip, err); err = ZIP_ERRNO; } } if (progress != NULL) { PyObject* args = Py_BuildValue("(I)", i + 1); PyObject* result = PyObject_CallObject(progress, args); if (PyErr_Occurred()) // Ignore errors in the callback, don't want them to crash this c module { PyErr_Clear(); } Py_XDECREF(result); Py_XDECREF(args); } if(srcpath_num > 0 && fullpathfileinzip) free(fullpathfileinzip); } errclose = zipClose(zf, NULL); if (errclose != ZIP_OK) { pyerr_msg = PyErr_Format(PyExc_IOError, "error in closing %s (%d)", dst, errclose); err = ZIP_ERRNO; } free(buf); return err; }
/****************************************************************************** *** Description *** Load a file in a zip file into memory. *** *** Arguments *** zipName - Name of zip file *** fileName - Name of file insize zipfile to load *** size - Output of size of file *** *** Return *** Pointer to allocate memory buffer with file content or NULL on *** failure. *** ******************************************************************************* */ void* _zipLoadFile(const char* zipName, const char* fileName, int* size, zlib_filefunc_def* filefunc) { void* buf; char name[256]; unzFile zip; unz_file_info info; *size = 0; if (fileName[0] == '*') { strcpy(name, zipName); name[strlen(zipName) - 3] = fileName[strlen(fileName) - 3]; name[strlen(zipName) - 2] = fileName[strlen(fileName) - 2]; name[strlen(zipName) - 1] = fileName[strlen(fileName) - 1]; } else { strcpy(name, fileName); } zip = unzOpen2(zipName, filefunc); if (!zip) { return NULL; } #ifdef __APPLE__ // Most OS X installs are on a case-insensitive FS if (unzLocateFile(zip, name, 2) == UNZ_END_OF_LIST_OF_FILE) { #else if (unzLocateFile(zip, name, 1) == UNZ_END_OF_LIST_OF_FILE) { #endif unzClose(zip); return NULL; } if (unzOpenCurrentFile(zip) != UNZ_OK) { return NULL; } unzGetCurrentFileInfo(zip,&info,NULL,0,NULL,0,NULL,0); buf = malloc(info.uncompressed_size); *size = info.uncompressed_size; if (!buf) { unzCloseCurrentFile(zip); unzClose(zip); return NULL; } unzReadCurrentFile(zip, buf, info.uncompressed_size); unzCloseCurrentFile(zip); unzClose(zip); return buf; } /****************************************************************************** *** Description *** Read cache to speed-up reading multiple files from one zip. *** ******************************************************************************/ static char *cacheData = NULL, cacheFile[512]; static zlib_filefunc_def cacheFilefunc; void* zipLoadFile(const char* zipName, const char* fileName, int* size) { if (strncmp(zipName, "mem", 3) == 0) { return memFileLoad(zipName, fileName, size); } if( cacheData != NULL && *cacheFile != '\0' && 0==strcmp(cacheFile, zipName) ) { return _zipLoadFile(cacheData, fileName, size, &cacheFilefunc); }else{ return _zipLoadFile(zipName, fileName, size, NULL); } } void zipCacheReadOnlyZip(const char* zipName) { if (zipName != NULL && strncmp(zipName, "mem", 3) == 0) { return; } *cacheFile = '\0'; if( cacheData != NULL ) { free(cacheData); cacheData = NULL; free_fopen_memfunc(&cacheFilefunc); } if( zipName != NULL ) { FILE *file; file = fopen(zipName, "rb"); if( file != NULL ) { unsigned int filesize; fseek(file, 0, SEEK_END); filesize = ftell(file); fill_fopen_memfunc(&cacheFilefunc, filesize); fseek(file, 0, SEEK_SET); cacheData = malloc(filesize); if( cacheData != NULL ) { size_t size = fread(cacheData, 1, filesize, file); if( size == filesize ) { strcpy(cacheFile, zipName); } } fclose(file); } } } /****************************************************************************** *** Description *** Load a file in a zip file into memory. *** *** Arguments *** zipName - Name of zip file *** fileName - Name of file insize zipfile to save *** buffer - Buffer to save *** size - Size of buffer to save *** ******************************************************************************* */ int zipSaveFile(const char* zipName, const char* fileName, int append, void* buffer, int size) { zipFile zip; zip_fileinfo zi; int err; if (strncmp(zipName, "mem", 3) == 0) { return memFileSave(zipName, fileName, append, buffer, size); } zip = zipOpen(zipName, append ? 2 : 0); if (zip == NULL) { return 0; } memset(&zi, 0, sizeof(zi)); err = zipOpenNewFileInZip(zip, fileName, &zi, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION); if (err == ZIP_OK) { err = zipWriteInFileInZip(zip, buffer, size); } zipClose(zip, NULL); return err >= 0; }
// ShowProgress( 0, TRUE, buf2 ); // archive the report into ONE big ZIP file void PostProc_ZipReport( char *reportLocation, char *zipfilename, int deletereport ) { if ( gFopenHistoryPtr ){ char newfilename[256]; char sourcepath[256], msg[128]; long count=0,filenum,perc = 0; LLStructRecPtr next = gFopenHistoryPtr; filenum = LListGetTotal( gFopenHistoryPtr ); PathFromFullPath( reportLocation, sourcepath ); DateFixFilename( sourcepath, 0 ); if ( !strstr( reportLocation, ".zip" ) ) { char *p; mystrcpy( newfilename, reportLocation ); DateFixFilename( newfilename, 0 ); p = strrchr( newfilename, '.' ); if ( p ) mystrcpy( p, ".zip" ); else return; mystrcpy( zipfilename, newfilename ); sprintf( msg, "Making ZIP %s", newfilename ); ShowProgress( perc, FALSE, msg ); } #ifdef _zip_H { zipFile zipData; char *source; zipData = zipOpen( (const char *)newfilename, 0 ); while( next && !IsStopped() ) { perc = ((count*100)/filenum); source = (char*)next->data; sprintf( msg, "Adding to zip file %s", FileFromPath( source,0 ) ); ShowProgress( perc, FALSE, msg ); long infilelen = GetFileLength( source ); char *ram = (char*)malloc( infilelen+1 ); if ( ram ) { zip_fileinfo zinfo; memset( &zinfo, 0, sizeof(zip_fileinfo) ); FileToMem( source, ram, infilelen ); zipOpenNewFileInZip( zipData, source, &zinfo, 0, 0, 0, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION ); zipWriteInFileInZip( zipData, ram , infilelen ); zipCloseFileInZip( zipData ); free( ram ); } if( deletereport ) remove( source ); next = next->next; count++; } zipClose( zipData, NULL ); } #endif #if DEF_WINZIP { ZCL zipData; char *source; memset( &zipData, 0, sizeof(ZCL) ); zipData.Stdout = stdout; zipData.fQuiet = TRUE; zipData.fUpdate = TRUE; zipData.lpszZipFN = newfilename; //"C:\install\test.zip"; zipData.fLevel = 1; zipData.FNV = &source; zipData.argc = 1; while( next && !IsStopped() ){ perc = ((count*100)/filenum); source = (char*)next->data; sprintf( msg, "Adding to zip file %s", FileFromPath( source,0 ) ); ShowProgress( perc, FALSE, msg ); ZipUpFiles( &zipData ); if( deletereport ) remove( source ); next = next->next; count++; } } #endif } }
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; }
int PackerJob::createZipFile() { int result = ZIP_ERRNO; zipFile zf = zipOpen2_64(m_tszFilePath, 0, nullptr, nullptr); if (zf != nullptr) { result = ZIP_OK; int size_buf = 65536; void *buff = (void *)mir_alloc(size_buf); for (UINT i = 0; i < m_files.size(); i++) { int size_read; zip_fileinfo zi; zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour = 0; 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; getFileTime(m_files[i], &zi.tmz_date, &zi.dosDate); char *file = mir_u2a(Utils::getFileNameFromPath(m_files[i])); int err = zipOpenNewFileInZip(zf, file, &zi, nullptr, 0, nullptr, 0, nullptr, Z_DEFLATED, opt.iCompressionLevel); FREE(file); if (err == ZIP_OK) { FILE *fin = _wfopen(m_files[i], L"rb"); if (fin) { do { if (isCanceled()) { fclose(fin); result = STATUS_CANCELED; goto Cleanup; } err = ZIP_OK; size_read = (int)fread(buff, 1, size_buf, fin); if (size_read < size_buf && feof(fin) == 0) { fclose(fin); result = ZIP_ERRNO; goto Cleanup; } if (size_read > 0) { err = zipWriteInFileInZip(zf, buff, size_read); m_uiReaded += size_read; } updateStats(); } while ((err == ZIP_OK) && (size_read > 0)); fclose(fin); } else err = ZIP_ERRNO; err = zipCloseFileInZip(zf); if (err < 0) { result = ZIP_ERRNO; goto Cleanup; } } else { result = ZIP_ERRNO; break; } } Cleanup: zipClose(zf, nullptr); FREE(buff); } return result; }