unsigned int getSize() const { unz_file_info file_info; unzGetCurrentFileInfo(_entry->zp, &file_info, 0, 0, 0, 0, 0, 0); return (unsigned int) file_info.uncompressed_size; }
// Load one file directly, added by regret INT32 __cdecl ZipLoadOneFile(const char* arcName, const char* fileName, void** Dest, INT32* pnWrote) { if (ZipOpen(arcName)) { return 1; } unz_global_info ZipGlobalInfo; memset(&ZipGlobalInfo, 0, sizeof(ZipGlobalInfo)); unzGetGlobalInfo(Zip, &ZipGlobalInfo); INT32 nListLen = ZipGlobalInfo.number_entry; if (nListLen <= 0) { ZipClose(); return 1; } INT32 nRet = unzGoToFirstFile(Zip); if (nRet != UNZ_OK) { unzClose(Zip); return 1; } unz_file_info FileInfo; memset(&FileInfo, 0, sizeof(FileInfo)); if (fileName != NULL) { // Step through all of the files, until we get to the end INT32 nNextRet = 0; char szName[MAX_PATH] = ""; for (nCurrFile = 0, nNextRet = UNZ_OK; nCurrFile < nListLen && nNextRet == UNZ_OK; nCurrFile++, nNextRet = unzGoToNextFile(Zip)) { nRet = unzGetCurrentFileInfo(Zip, &FileInfo, szName, MAX_PATH, NULL, 0, NULL, 0); if (nRet != UNZ_OK) continue; if (!strcmp(szName, fileName)) { break; } } if (nCurrFile == nListLen) { ZipClose(); return 1; // didn't find } } else { nRet = unzGetCurrentFileInfo(Zip, &FileInfo, NULL, 0, NULL, 0, NULL, 0); if (nRet != UNZ_OK) { ZipClose(); return 1; } } // Extract file nRet = unzOpenCurrentFile(Zip); if (nRet != UNZ_OK) { unzCloseCurrentFile(Zip); ZipClose(); return 1; } if (*Dest == NULL) { *Dest = (UINT8*)malloc(FileInfo.uncompressed_size); if (!*Dest) { unzCloseCurrentFile(Zip); ZipClose(); return 1; } } nRet = unzReadCurrentFile(Zip, *Dest, FileInfo.uncompressed_size); // Return how many bytes were copied if (nRet >= 0 && pnWrote != NULL) *pnWrote = nRet; nRet = unzCloseCurrentFile(Zip); ZipClose(); if (nRet == UNZ_CRCERROR) { if (*Dest) { free(*Dest); } return 2; } if (nRet != UNZ_OK) { if (*Dest) { free(*Dest); } return 1; } return 0; }
static char *load_archive(char *filename, int *file_size) { int size = 0; char *buf = NULL; unzFile fd = NULL; unz_file_info info; int ret = 0; /* Attempt to open the archive */ fd = unzOpen(filename); if(!fd) { printf("Failed to open archive\r\n"); return NULL; } /* Go to first file in archive */ ret = unzGoToFirstFile(fd); if(ret != UNZ_OK) { printf("Failed to find first file in zip\r\n"); unzClose(fd); return NULL; } ret = unzGetCurrentFileInfo(fd, &info, NULL, 0, NULL, 0, NULL, 0); if(ret != UNZ_OK) { printf("Failed to zip info\r\n"); unzClose(fd); return NULL; } /* Open the file for reading */ ret = unzOpenCurrentFile(fd); if(ret != UNZ_OK) { printf("Failed to read file\r\n"); unzClose(fd); return NULL; } /* Allocate file data buffer */ size = info.uncompressed_size; buf=(char*)malloc(size); if(!buf) { printf("Failed to malloc zip buffer\r\n"); unzClose(fd); return NULL; } /* Read (decompress) the file */ ret = unzReadCurrentFile(fd, buf, info.uncompressed_size); if(ret != info.uncompressed_size) { free(buf); printf("File failed to uncompress fully\r\n"); unzCloseCurrentFile(fd); unzClose(fd); return NULL; } /* Close the current file */ ret = unzCloseCurrentFile(fd); if(ret != UNZ_OK) { free(buf); printf("Failed to close file in zip\r\n"); unzClose(fd); return NULL; } /* Close the archive */ ret = unzClose(fd); if(ret != UNZ_OK) { free(buf); printf("Failed to close zip\r\n"); return NULL; } /* Update file size and return pointer to file data */ *file_size = size; return buf; }
bool HttpDownload::uncompress(std::string path ) { // Open the zip file string outFileName = path == ""? _filePath + _url.substr(_url.rfind('/') + 1):path; unzFile zipfile = unzOpen(outFileName.c_str()); if (! zipfile) { CCLOG("can not open downloaded zip file %s", outFileName.c_str()); return false; } // Get info about the zip file unz_global_info global_info; if (unzGetGlobalInfo(zipfile, &global_info) != UNZ_OK) { CCLOG("can not read file global info of %s", outFileName.c_str()); unzClose(zipfile); return false; } // Buffer to hold data read from the zip file char readBuffer[BUFFER_SIZE]; CCLOG("start uncompressing"); // Loop to extract all files. uLong i; for (i = 0; i < global_info.number_entry; ++i) { // Get info about current file. unz_file_info fileInfo; char fileName[MAX_FILENAME]; if (unzGetCurrentFileInfo(zipfile, &fileInfo, fileName, MAX_FILENAME, nullptr, 0, nullptr, 0) != UNZ_OK) { CCLOG("can not read file info"); unzClose(zipfile); return false; } const string fullPath = _filePath + fileName; // Check if this entry is a directory or a file. const size_t filenameLength = strlen(fileName); if (fileName[filenameLength-1] == '/') { // Entry is a direcotry, so create it. // If the directory exists, it will failed scilently. if (!createDirectory(fullPath.c_str())) { CCLOG("can not create directory %s", fullPath.c_str()); unzClose(zipfile); return false; } } else { //There are not directory entry in some case. //So we need to test whether the file directory exists when uncompressing file entry //, if does not exist then create directory const string fileNameStr(fileName); size_t startIndex=0; size_t index=fileNameStr.find("/",startIndex); while(index != std::string::npos) { const string dir=_filePath+fileNameStr.substr(0,index); FILE *out = fopen(FileUtils::getInstance()->getSuitableFOpen(dir).c_str(), "r"); if(!out) { if (!createDirectory(dir.c_str())) { CCLOG("can not create directory %s", dir.c_str()); unzClose(zipfile); return false; } else { CCLOG("create directory %s",dir.c_str()); } } else { fclose(out); } startIndex=index+1; index=fileNameStr.find("/",startIndex); } // Entry is a file, so extract it. // Open current file. if (unzOpenCurrentFile(zipfile) != UNZ_OK) { CCLOG("can not open file %s", fileName); unzClose(zipfile); return false; } // Create a file to store current file. FILE *out = fopen(FileUtils::getInstance()->getSuitableFOpen(fullPath).c_str(), "wb"); if (! out) { CCLOG("can not open destination file %s", fullPath.c_str()); unzCloseCurrentFile(zipfile); unzClose(zipfile); return false; } // Write current file content to destinate file. int error = UNZ_OK; do { error = unzReadCurrentFile(zipfile, readBuffer, BUFFER_SIZE); if (error < 0) { CCLOG("can not read zip file %s, error code is %d", fileName, error); unzCloseCurrentFile(zipfile); unzClose(zipfile); return false; } if (error > 0) { fwrite(readBuffer, error, 1, out); } } while(error > 0); fclose(out); } unzCloseCurrentFile(zipfile); // Goto next entry listed in the zip file. if ((i+1) < global_info.number_entry) { if (unzGoToNextFile(zipfile) != UNZ_OK) { CCLOG("can not read next file"); unzClose(zipfile); return false; } } } CCLOG("end uncompressing"); unzClose(zipfile); return true; }
si64 CZipStream::getSize() { unz_file_info info; unzGetCurrentFileInfo (file, &info, nullptr, 0, nullptr, 0, nullptr, 0); return info.uncompressed_size; }
void ExportTemplateManager::_install_from_file(const String &p_file, bool p_use_progress) { FileAccess *fa = NULL; zlib_filefunc_def io = zipio_create_io_from_file(&fa); unzFile pkg = unzOpen2(p_file.utf8().get_data(), &io); if (!pkg) { EditorNode::get_singleton()->show_warning(TTR("Can't open export templates zip.")); return; } int ret = unzGoToFirstFile(pkg); int fc = 0; //count them and find version String version; while (ret == UNZ_OK) { unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0); String file = fname; if (file.ends_with("version.txt")) { Vector<uint8_t> data; data.resize(info.uncompressed_size); //read unzOpenCurrentFile(pkg); ret = unzReadCurrentFile(pkg, data.ptrw(), data.size()); unzCloseCurrentFile(pkg); String data_str; data_str.parse_utf8((const char *)data.ptr(), data.size()); data_str = data_str.strip_edges(); // Version number should be of the form major.minor[.patch].status[.module_config] // so it can in theory have 3 or more slices. if (data_str.get_slice_count(".") < 3) { EditorNode::get_singleton()->show_warning(vformat(TTR("Invalid version.txt format inside templates: %s."), data_str)); unzClose(pkg); return; } version = data_str; } fc++; ret = unzGoToNextFile(pkg); } if (version == String()) { EditorNode::get_singleton()->show_warning(TTR("No version.txt found inside templates.")); unzClose(pkg); return; } String template_path = EditorSettings::get_singleton()->get_templates_dir().plus_file(version); DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); Error err = d->make_dir_recursive(template_path); if (err != OK) { EditorNode::get_singleton()->show_warning(TTR("Error creating path for templates:") + "\n" + template_path); unzClose(pkg); return; } memdelete(d); ret = unzGoToFirstFile(pkg); EditorProgress *p = NULL; if (p_use_progress) { p = memnew(EditorProgress("ltask", TTR("Extracting Export Templates"), fc)); } fc = 0; while (ret == UNZ_OK) { //get filename unz_file_info info; char fname[16384]; unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0); String file = String(fname).get_file(); Vector<uint8_t> data; data.resize(info.uncompressed_size); //read unzOpenCurrentFile(pkg); unzReadCurrentFile(pkg, data.ptrw(), data.size()); unzCloseCurrentFile(pkg); if (p) { p->step(TTR("Importing:") + " " + file, fc); } FileAccess *f = FileAccess::open(template_path.plus_file(file), FileAccess::WRITE); if (!f) { ret = unzGoToNextFile(pkg); fc++; ERR_CONTINUE(!f); } f->store_buffer(data.ptr(), data.size()); memdelete(f); ret = unzGoToNextFile(pkg); fc++; } if (p) { memdelete(p); } unzClose(pkg); _update_template_list(); }
/** * If loadFileBuf is NULL the loadFileBufSize is ignored and the necessary buffer size * is returned in loadFileBufSize and the functions returns. * \param fileName [in] The name of the CAP file. * \param loadFileBuf [out] The destination buffer with the Executable Load File contents. * \param loadFileBufSize [in, out] The size of the loadFileBuf. * \return OPGP_ERROR_SUCCESS if no error, error code else. */ OPGP_ERROR_STATUS extract_cap_file(OPGP_CSTRING fileName, PBYTE loadFileBuf, PDWORD loadFileBufSize) { int rv; OPGP_ERROR_STATUS status; zipFile szip; unsigned char *appletbuf = NULL; unsigned char *classbuf = NULL; unsigned char *constantpoolbuf = NULL; unsigned char *descriptorbuf = NULL; unsigned char *directorybuf = NULL; unsigned char *headerbuf = NULL; unsigned char *importbuf = NULL; unsigned char *methodbuf = NULL; unsigned char *reflocationbuf = NULL; unsigned char *staticfieldbuf = NULL; unsigned char *exportbuf = NULL; int appletbufsz = 0; int classbufsz = 0; int constantpoolbufsz = 0; int descriptorbufsz = 0; int directorybufsz = 0; int headerbufsz = 0; int importbufsz = 0; int methodbufsz = 0; int reflocationbufsz = 0; int staticfieldbufsz = 0; int exportbufsz = 0; unsigned char *buf; char capFileName[MAX_PATH_LENGTH]; DWORD totalSize = 0; OPGP_LOG_START(_T("extract_cap_file")); convertT_to_C(capFileName, fileName); #ifdef DEBUG OPGP_log_Msg(_T("extract_cap_file: Try to open cap file %s"), fileName); #endif szip = unzOpen((const char *)capFileName); if (szip==NULL) { OPGP_ERROR_CREATE_ERROR(status, OPGP_ERROR_CAP_UNZIP, OPGP_stringify_error(OPGP_ERROR_CAP_UNZIP)); goto end; } rv = unzGoToFirstFile(szip); while (rv == UNZ_OK) { // get zipped file info unz_file_info unzfi; char fn[MAX_PATH_LENGTH]; int sz; if (unzGetCurrentFileInfo(szip, &unzfi, fn, MAX_PATH_LENGTH, NULL, 0, NULL, 0) != UNZ_OK) { OPGP_ERROR_CREATE_ERROR(status, OPGP_ERROR_CAP_UNZIP, OPGP_stringify_error(OPGP_ERROR_CAP_UNZIP)); goto end; } if (unzOpenCurrentFile(szip)!=UNZ_OK) { OPGP_ERROR_CREATE_ERROR(status, OPGP_ERROR_CAP_UNZIP, OPGP_stringify_error(OPGP_ERROR_CAP_UNZIP)); goto end; } #ifdef DEBUG OPGP_log_Msg(_T("extract_cap_file: Allocating buffer size for cap file content %s"), fn); #endif // write file if (strcmp(fn + strlen(fn)-10, "Header.cap") == 0) { totalSize+=unzfi.uncompressed_size; headerbufsz = unzfi.uncompressed_size; buf = headerbuf = (unsigned char *)malloc(unzfi.uncompressed_size); } else if (strcmp(fn + strlen(fn)-10, "Applet.cap") == 0) { totalSize+=unzfi.uncompressed_size; appletbufsz = unzfi.uncompressed_size; buf = appletbuf = (unsigned char *)malloc(unzfi.uncompressed_size); } else if (strcmp(fn + strlen(fn)-9, "Class.cap") == 0) { totalSize+=unzfi.uncompressed_size; classbufsz = unzfi.uncompressed_size; buf = classbuf = (unsigned char *)malloc(unzfi.uncompressed_size); } else if (strcmp(fn + strlen(fn)-10, "Import.cap") == 0) { totalSize+=unzfi.uncompressed_size; importbufsz = unzfi.uncompressed_size; buf = importbuf = (unsigned char *)malloc(unzfi.uncompressed_size); } else if (strcmp(fn + strlen(fn)-13, "Directory.cap") == 0) { totalSize+=unzfi.uncompressed_size; directorybufsz = unzfi.uncompressed_size; buf = directorybuf = (unsigned char *)malloc(unzfi.uncompressed_size); } else if (strcmp(fn + strlen(fn)-10, "Method.cap") == 0) { totalSize+=unzfi.uncompressed_size; methodbufsz = unzfi.uncompressed_size; buf = methodbuf = (unsigned char *)malloc(unzfi.uncompressed_size); } else if (strcmp(fn + strlen(fn)-16, "ConstantPool.cap") == 0) { totalSize+=unzfi.uncompressed_size; constantpoolbufsz = unzfi.uncompressed_size; buf = constantpoolbuf = (unsigned char *)malloc(unzfi.uncompressed_size); } else if (strcmp(fn + strlen(fn)-14, "Descriptor.cap") == 0) { totalSize+=unzfi.uncompressed_size; descriptorbufsz = unzfi.uncompressed_size; buf = descriptorbuf = (unsigned char *)malloc(unzfi.uncompressed_size); } else if (strcmp(fn + strlen(fn)-15, "RefLocation.cap") == 0) { totalSize+=unzfi.uncompressed_size; reflocationbufsz = unzfi.uncompressed_size; buf = reflocationbuf = (unsigned char *)malloc(unzfi.uncompressed_size); } else if (strcmp(fn + strlen(fn)-15, "StaticField.cap") == 0) { totalSize+=unzfi.uncompressed_size; staticfieldbufsz = unzfi.uncompressed_size; buf = staticfieldbuf = (unsigned char *)malloc(unzfi.uncompressed_size); } else if (strcmp(fn + strlen(fn)-10, "Export.cap") == 0) { totalSize+=unzfi.uncompressed_size; exportbufsz = unzfi.uncompressed_size; buf = exportbuf = (unsigned char *)malloc(unzfi.uncompressed_size); } else { goto next; } if ((buf==NULL)&&(unzfi.uncompressed_size!=0)) { OPGP_ERROR_CREATE_ERROR(status, ENOMEM, OPGP_stringify_error(ENOMEM)); goto end; } // read file sz = unzReadCurrentFile(szip, buf, unzfi.uncompressed_size); if ((unsigned int)sz != unzfi.uncompressed_size) { OPGP_ERROR_CREATE_ERROR(status, OPGP_ERROR_CAP_UNZIP, OPGP_stringify_error(OPGP_ERROR_CAP_UNZIP)); goto end; } next: if (unzCloseCurrentFile(szip)==UNZ_CRCERROR) { OPGP_ERROR_CREATE_ERROR(status, OPGP_ERROR_CAP_UNZIP, OPGP_stringify_error(OPGP_ERROR_CAP_UNZIP)); goto end; } rv = unzGoToNextFile(szip); } if ( rv!=UNZ_END_OF_LIST_OF_FILE ) { OPGP_ERROR_CREATE_ERROR(status, OPGP_ERROR_CAP_UNZIP, OPGP_stringify_error(OPGP_ERROR_CAP_UNZIP)); goto end; } #ifdef DEBUG OPGP_log_Msg(_T("extract_cap_file: Successfully extracted cap file %s"), fileName); #endif if (loadFileBuf == NULL) { *loadFileBufSize = totalSize; { OPGP_ERROR_CREATE_NO_ERROR(status); goto end; } goto end; } if (*loadFileBufSize < totalSize) { OPGP_ERROR_CREATE_ERROR(status, OPGP_ERROR_INSUFFICIENT_BUFFER, OPGP_stringify_error(OPGP_ERROR_INSUFFICIENT_BUFFER)); goto end; } #ifdef DEBUG OPGP_log_Msg(_T("extract_cap_file: Copying extracted cap file contents into buffer")); #endif totalSize = 0; if (headerbuf != NULL) { memcpy(loadFileBuf+totalSize, headerbuf, headerbufsz); totalSize+=headerbufsz; } if (directorybuf != NULL) { memcpy(loadFileBuf+totalSize, directorybuf, directorybufsz); totalSize+=directorybufsz; } if (importbuf != NULL) { memcpy(loadFileBuf+totalSize, importbuf, importbufsz); totalSize+=importbufsz; } if (appletbuf != NULL) { memcpy(loadFileBuf+totalSize, appletbuf, appletbufsz); totalSize+=appletbufsz; } if (classbuf != NULL) { memcpy(loadFileBuf+totalSize, classbuf, classbufsz); totalSize+=classbufsz; } if (methodbuf != NULL) { memcpy(loadFileBuf+totalSize, methodbuf, methodbufsz); totalSize+=methodbufsz; } if (staticfieldbuf != NULL) { memcpy(loadFileBuf+totalSize, staticfieldbuf, staticfieldbufsz); totalSize+=staticfieldbufsz; } if (exportbuf != NULL) { memcpy(loadFileBuf+totalSize, exportbuf, exportbufsz); totalSize+=exportbufsz; } if (constantpoolbuf != NULL) { memcpy(loadFileBuf+totalSize, constantpoolbuf, constantpoolbufsz); totalSize+=constantpoolbufsz; } if (reflocationbuf != NULL) { memcpy(loadFileBuf+totalSize, reflocationbuf, reflocationbufsz); totalSize+=reflocationbufsz; } if (descriptorbuf != NULL) { memcpy(loadFileBuf+totalSize, descriptorbuf, descriptorbufsz); totalSize+=descriptorbufsz; } #ifdef DEBUG OPGP_log_Msg(_T("extract_cap_file: Buffer copied.")); #endif { OPGP_ERROR_CREATE_NO_ERROR(status); goto end; } end: if (szip != NULL) { unzClose(szip); } if (appletbuf != NULL) { free(appletbuf); } if (classbuf != NULL) { free(classbuf); } if (constantpoolbuf != NULL) { free(constantpoolbuf); } if (descriptorbuf != NULL) { free(descriptorbuf); } if (directorybuf != NULL) { free(directorybuf); } if (headerbuf != NULL) { free(headerbuf); } if (importbuf != NULL) { free(importbuf); } if (methodbuf != NULL) { free(methodbuf); } if (reflocationbuf != NULL) { free(reflocationbuf); } if (staticfieldbuf != NULL) { free(staticfieldbuf); } OPGP_LOG_END(_T("extract_cap_file"), status); return status; }
int do_list(unzFile uf) { uLong i; unz_global_info gi; int err; err = unzGetGlobalInfo (uf,&gi); if (err!=UNZ_OK) printf("error %d with zipfile in unzGetGlobalInfo \n",err); printf(" Length Method Size Ratio Date Time CRC-32 Name\n"); printf(" ------ ------ ---- ----- ---- ---- ------ ----\n"); for (i=0; i<gi.number_entry; i++) { char filename_inzip[256]; unz_file_info file_info; uLong ratio=0; const char *string_method = NULL; char charCrypt=' '; err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); if (err!=UNZ_OK) { printf("error %d with zipfile in unzGetCurrentFileInfo\n",err); break; } if (file_info.uncompressed_size>0) ratio = (file_info.compressed_size*100)/file_info.uncompressed_size; /* display a '*' if the file is crypted */ if ((file_info.flag & 1) != 0) charCrypt='*'; if (file_info.compression_method==0) string_method="Stored"; else if (file_info.compression_method==Z_DEFLATED) { uInt iLevel=(uInt)((file_info.flag & 0x6)/2); if (iLevel==0) string_method="Defl:N"; else if (iLevel==1) string_method="Defl:X"; else if ((iLevel==2) || (iLevel==3)) string_method="Defl:F"; /* 2:fast , 3 : extra fast*/ } else string_method="Unkn. "; printf("%7lu %6s%c%7lu %3lu%% %2.2lu-%2.2lu-%2.2lu %2.2lu:%2.2lu %8.8lx %s\n", file_info.uncompressed_size,string_method, charCrypt, file_info.compressed_size, ratio, (uLong)file_info.tmu_date.tm_mon + 1, (uLong)file_info.tmu_date.tm_mday, (uLong)file_info.tmu_date.tm_year % 100, (uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min, (uLong)file_info.crc,filename_inzip); if ((i+1)<gi.number_entry) { err = unzGoToNextFile(uf); if (err!=UNZ_OK) { printf("error %d with zipfile in unzGoToNextFile\n",err); break; } } } return 0; }
int do_extract_currentfile(unzFile uf, const int *popt_extract_without_path, int *popt_overwrite, const char *password) { char filename_inzip[256]; char* filename_withoutpath; char* p; int err=UNZ_OK; FILE *fout=NULL; void* buf; uInt size_buf; unz_file_info file_info; uLong ratio=0; err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); if (err!=UNZ_OK) { printf("error %d with zipfile in unzGetCurrentFileInfo\n",err); return err; } size_buf = WRITEBUFFERSIZE; buf = (void*)malloc(size_buf); if (buf==NULL) { printf("Error allocating memory\n"); return UNZ_INTERNALERROR; } p = filename_withoutpath = filename_inzip; while ((*p) != '\0') { if (((*p)=='/') || ((*p)=='\\')) filename_withoutpath = p+1; p++; } if ((*filename_withoutpath)=='\0') { if ((*popt_extract_without_path)==0) { printf("creating directory: %s\n",filename_inzip); mymkdir(filename_inzip); } } else { const char* write_filename; int skip=0; if ((*popt_extract_without_path)==0) write_filename = filename_inzip; else write_filename = filename_withoutpath; err = unzOpenCurrentFilePassword(uf,password); if (err!=UNZ_OK) { printf("error %d with zipfile in unzOpenCurrentFilePassword\n",err); } if (((*popt_overwrite)==0) && (err==UNZ_OK)) { char rep=0; FILE* ftestexist; ftestexist = fopen(write_filename,"rb"); if (ftestexist!=NULL) { fclose(ftestexist); do { char answer[128]; int ret; printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename); ret = scanf("%1s",answer); if (ret != 1) { exit(EXIT_FAILURE); } rep = answer[0] ; if ((rep>='a') && (rep<='z')) rep -= 0x20; } while ((rep!='Y') && (rep!='N') && (rep!='A')); } if (rep == 'N') skip = 1; if (rep == 'A') *popt_overwrite=1; } if ((skip==0) && (err==UNZ_OK)) { fout=fopen(write_filename,"wb"); /* some zipfile don't contain directory alone before file */ if ((fout==NULL) && ((*popt_extract_without_path)==0) && (filename_withoutpath!=(char*)filename_inzip)) { char c=*(filename_withoutpath-1); *(filename_withoutpath-1)='\0'; makedir(write_filename); *(filename_withoutpath-1)=c; fout=fopen(write_filename,"wb"); } if (fout==NULL) { printf("error opening %s\n",write_filename); } } if (fout!=NULL) { printf(" extracting: %s\n",write_filename); do { err = unzReadCurrentFile(uf,buf,size_buf); if (err<0) { printf("error %d with zipfile in unzReadCurrentFile\n",err); break; } if (err>0) if (fwrite(buf,err,1,fout)!=1) { printf("error in writing extracted file\n"); err=UNZ_ERRNO; break; } } while (err>0); if (fout) fclose(fout); if (err==0) change_file_date(write_filename,file_info.dosDate, file_info.tmu_date); } if (err==UNZ_OK) { err = unzCloseCurrentFile (uf); if (err!=UNZ_OK) { printf("error %d with zipfile in unzCloseCurrentFile\n",err); } } else unzCloseCurrentFile(uf); /* don't lose the error */ } free(buf); return err; }
void EditorAssetInstaller::ok_pressed() { FileAccess *src_f=NULL; zlib_filefunc_def io = zipio_create_io_from_file(&src_f); unzFile pkg = unzOpen2(package_path.utf8().get_data(), &io); if (!pkg) { error->set_text("Error opening package file, not in zip format."); return; } int ret = unzGoToFirstFile(pkg); Vector<String> failed_files; ProgressDialog::get_singleton()->add_task("uncompress","Uncompressing Assets",status_map.size()); int idx=0; while(ret==UNZ_OK) { //get filename unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0); String name=fname; if (status_map.has(name) && status_map[name]->is_checked(0)) { String path = status_map[name]->get_metadata(0); if (path==String()) { // a dir String dirpath; TreeItem *t = status_map[name]; while(t) { dirpath=t->get_text(0)+dirpath; t=t->get_parent(); } if (dirpath.ends_with("/")) { dirpath=dirpath.substr(0,dirpath.length()-1); } DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); da->make_dir(dirpath); memdelete(da); } else { Vector<uint8_t> data; data.resize(info.uncompressed_size); //read unzOpenCurrentFile(pkg); unzReadCurrentFile(pkg,data.ptr(),data.size()); unzCloseCurrentFile(pkg); FileAccess *f=FileAccess::open(path,FileAccess::WRITE); if (f) { f->store_buffer(data.ptr(),data.size()); memdelete(f); } else { failed_files.push_back(path); } ProgressDialog::get_singleton()->task_step("uncompress",path,idx); } } idx++; ret = unzGoToNextFile(pkg); } ProgressDialog::get_singleton()->end_task("uncompress"); unzClose(pkg); if (failed_files.size()) { String msg="The following files failed extraction from package:\n\n"; for(int i=0;i<failed_files.size();i++) { if (i>15) { msg+="\nAnd "+itos(failed_files.size()-i)+" more files."; break; } msg+=failed_files[i]; } EditorNode::get_singleton()->show_warning(msg); } else { EditorNode::get_singleton()->show_warning("Package Installed Successfully!","Success!"); } }
void EditorAssetInstaller::open(const String& p_path,int p_depth) { package_path=p_path; Set<String> files_sorted; FileAccess *src_f=NULL; zlib_filefunc_def io = zipio_create_io_from_file(&src_f); unzFile pkg = unzOpen2(p_path.utf8().get_data(), &io); if (!pkg) { error->set_text("Error opening package file, not in zip format."); return; } int ret = unzGoToFirstFile(pkg); while(ret==UNZ_OK) { //get filename unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0); String name=fname; files_sorted.insert(name); ret = unzGoToNextFile(pkg); } Map<String,Ref<Texture> > extension_guess; { extension_guess["png"]=get_icon("Texture","EditorIcons"); extension_guess["jpg"]=get_icon("Texture","EditorIcons"); extension_guess["tex"]=get_icon("Texture","EditorIcons"); extension_guess["atex"]=get_icon("Texture","EditorIcons"); extension_guess["dds"]=get_icon("Texture","EditorIcons"); extension_guess["scn"]=get_icon("PackedScene","EditorIcons"); extension_guess["tscn"]=get_icon("PackedScene","EditorIcons"); extension_guess["xml"]=get_icon("PackedScene","EditorIcons"); extension_guess["xscn"]=get_icon("PackedScene","EditorIcons"); extension_guess["mtl"]=get_icon("Material","EditorIcons"); extension_guess["shd"]=get_icon("Shader","EditorIcons"); extension_guess["gd"]=get_icon("GDScript","EditorIcons"); } Ref<Texture> generic_extension = get_icon("Object","EditorIcons"); unzClose(pkg); updating=true; tree->clear(); TreeItem *root=tree->create_item(); root->set_cell_mode(0,TreeItem::CELL_MODE_CHECK); root->set_checked(0,true); root->set_icon(0,get_icon("folder","FileDialog")); root->set_text(0,"res://"); root->set_editable(0,true); Map<String,TreeItem*> dir_map; for(Set<String>::Element *E=files_sorted.front();E;E=E->next()) { String path = E->get(); int depth=p_depth; bool skip=false; while(depth>0) { int pp = path.find("/"); if (pp==-1) { skip=true; break; } path=path.substr(pp+1,path.length()); depth--; } if (skip || path==String()) continue; bool isdir=false; if (path.ends_with("/")) { //a directory path=path.substr(0,path.length()-1); isdir=true; } int pp = path.find_last("/"); TreeItem *parent; if (pp==-1) { parent=root; } else { String ppath=path.substr(0,pp); print_line("PPATH IS: "+ppath); ERR_CONTINUE(!dir_map.has(ppath)); parent=dir_map[ppath]; } TreeItem *ti = tree->create_item(parent); ti->set_cell_mode(0,TreeItem::CELL_MODE_CHECK); ti->set_checked(0,true); ti->set_editable(0,true); if (isdir) { dir_map[path]=ti; ti->set_text(0,path.get_file()+"/"); ti->set_icon(0,get_icon("folder","FileDialog")); } else { String file = path.get_file(); String extension = file.extension().to_lower(); if (extension_guess.has(extension)) { ti->set_icon(0,extension_guess[extension]); } else { ti->set_icon(0,generic_extension); } ti->set_text(0,file); String res_path = "res://"+path; if (FileAccess::exists(res_path)) { ti->set_custom_color(0,Color(1,0.3,0.2)); ti->set_tooltip(0,res_path+" (Already Exists)"); ti->set_checked(0,false); } else { ti->set_tooltip(0,res_path); } ti->set_metadata(0,res_path); } status_map[E->get()]=ti; } popup_centered_ratio(); updating=false; }
void ExtractGameZip(const char* zip_path) { unzFile zip_file = NULL; bool file_open = false; zip_file = unzOpen(zip_path); if (zip_file == NULL) { fprintf(stderr, "unzOpen(%s) failed.", zip_path); goto cleanup; } if (unzGoToFirstFile(zip_file) != UNZ_OK) { fprintf(stderr, "unzGoToFirstFile failed."); goto cleanup; } while (true) { unz_file_info file_info; char file_name[MAXPATHLEN]; char* first_slash; if (unzGetCurrentFileInfo(zip_file, &file_info, &file_name[0], MAXPATHLEN, NULL, 0, NULL, 0) != UNZ_OK) { fprintf(stderr, "unzGetCurrentFileInfo failed."); goto cleanup; } // Is this a file we want to extract? printf("Examining %s...\n", file_name); // Find first slash in filename. first_slash = strchr(file_name, '/'); // We only want data/ or Doukutsu.exe. if (strncmp(first_slash, "/Doukutsu.exe", 13) == 0 || strncmp(first_slash, "/data", 5) == 0) { printf("Copy from %s (in zip file) to %s\n", file_name, first_slash); FILE* fdst = NULL; int bytes_left; int bytes_read; int bytes_written; char* last_slash; if (unzOpenCurrentFile(zip_file) != UNZ_OK) { fprintf(stderr, "unzOpenCurrentFile failed. \"%s\"\n", file_name); goto cleanup; } file_open = true; // Create parent directories. last_slash = strrchr(first_slash, '/'); if (last_slash) { *last_slash = 0; mkdir(first_slash, 0666); *last_slash = '/'; } // If uncompressed_size is 0, this is probably a directory, so skip it. if (file_info.uncompressed_size != 0) { fdst = fileopen(first_slash, "w+"); if (!fdst) { fprintf(stderr, "fopen(%s) failed: %d\n", first_slash, errno); goto cleanup; } bytes_left = file_info.uncompressed_size; while (bytes_left > 0) { int bytes_to_read = std::min<size_t>(kCopyBufferSize, bytes_left); bytes_read = unzReadCurrentFile(zip_file, &g_copy_buffer[0], bytes_to_read); if (bytes_read != bytes_to_read) { fprintf(stderr, "unzReadCurrentFile(%d) was short, %d.\n", bytes_to_read, bytes_read); fclose(fdst); goto cleanup; } bytes_written = fwrite(&g_copy_buffer[0], 1, bytes_to_read, fdst); if (bytes_written != bytes_to_read) { fprintf(stderr, "fwrite(%d) was short, %d.\n", bytes_to_read, bytes_written); goto cleanup; } bytes_left -= bytes_read; } fclose(fdst); unzCloseCurrentFile(zip_file); file_open = false; } } if (unzGoToNextFile(zip_file) != UNZ_OK) { break; } } cleanup: if (zip_file && file_open) unzCloseCurrentFile(zip_file); if (zip_file) unzClose(zip_file); }
/* Open a Zip file. path contain the full pathname (by example, on a Windows NT computer "c:\\test\\zlib109.zip" or on an Unix computer "zlib/zlib109.zip". If the zipfile cannot be opened (file don't exist or in not valid), the return value is NULL. Else, the return value is a unzFile Handle, usable with other function of this unzip package. */ unzFile unzOpen(Common::SeekableReadStream *stream) { if (!stream) return NULL; unz_s *us = new unz_s; uLong central_pos,uL; uLong number_disk; /* number of the current dist, used for spaning ZIP, unsupported, always 0*/ uLong number_disk_with_CD; /* number the the disk with central dir, used for spaning ZIP, unsupported, always 0*/ uLong number_entry_CD; /* total number of entries in the central dir (same than number_entry on nospan) */ int err=UNZ_OK; us->_stream = stream; central_pos = unzlocal_SearchCentralDir(*us->_stream); if (central_pos==0) err=UNZ_ERRNO; us->_stream->seek(central_pos, SEEK_SET); if (us->_stream->err()) err=UNZ_ERRNO; /* the signature, already checked */ if (unzlocal_getLong(us->_stream,&uL)!=UNZ_OK) err=UNZ_ERRNO; /* number of this disk */ if (unzlocal_getShort(us->_stream,&number_disk)!=UNZ_OK) err=UNZ_ERRNO; /* number of the disk with the start of the central directory */ if (unzlocal_getShort(us->_stream,&number_disk_with_CD)!=UNZ_OK) err=UNZ_ERRNO; /* total number of entries in the central dir on this disk */ if (unzlocal_getShort(us->_stream,&us->gi.number_entry)!=UNZ_OK) err=UNZ_ERRNO; /* total number of entries in the central dir */ if (unzlocal_getShort(us->_stream,&number_entry_CD)!=UNZ_OK) err=UNZ_ERRNO; if ((number_entry_CD!=us->gi.number_entry) || (number_disk_with_CD!=0) || (number_disk!=0)) err=UNZ_BADZIPFILE; /* size of the central directory */ if (unzlocal_getLong(us->_stream,&us->size_central_dir)!=UNZ_OK) err=UNZ_ERRNO; /* offset of start of central directory with respect to the starting disk number */ if (unzlocal_getLong(us->_stream,&us->offset_central_dir)!=UNZ_OK) err=UNZ_ERRNO; /* zipfile comment length */ if (unzlocal_getShort(us->_stream,&us->gi.size_comment)!=UNZ_OK) err=UNZ_ERRNO; if ((central_pos<us->offset_central_dir+us->size_central_dir) && (err==UNZ_OK)) err=UNZ_BADZIPFILE; if (err != UNZ_OK) { delete us->_stream; delete us; return NULL; } us->byte_before_the_zipfile = central_pos - (us->offset_central_dir+us->size_central_dir); us->central_pos = central_pos; us->pfile_in_zip_read = NULL; err = unzGoToFirstFile((unzFile)us); while (err == UNZ_OK) { // Get the file details char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1]; unzGetCurrentFileInfo(us, NULL, szCurrentFileName, sizeof(szCurrentFileName) - 1, NULL, 0, NULL, 0); // Save details into the hash cached_file_in_zip fe; fe.num_file = us->num_file; fe.pos_in_central_dir = us->pos_in_central_dir; fe.current_file_ok = us->current_file_ok; fe.cur_file_info = us->cur_file_info; fe.cur_file_info_internal = us->cur_file_info_internal; us->_hash[Common::String(szCurrentFileName)] = fe; // Move to the next file err = unzGoToNextFile((unzFile)us); } return (unzFile)us; }
int Load_ROM_Zipped () { int err = UNZ_OK; unzFile zf = NULL; unz_file_info zf_infos; int start_at; char temp[FILENAME_LEN]; zf = unzOpen(g_env.Paths.MediaImageFile); if (zf == NULL) return (MEKA_ERR_ZIP_LOADING); // Error loading ZIP file // Locating.. err = unzGoToFirstFile(zf); do { if (err != UNZ_OK) { unzClose(zf); return (MEKA_ERR_ZIP_INTERNAL); } // Getting informations.. unzGetCurrentFileInfo(zf, &zf_infos, temp, FILENAME_LEN, NULL, 0, NULL, 0); StrPath_GetExtension(temp); StrUpper(temp); // Check if valid if (drv_is_known_filename_extension(temp)) { break; } // Else try next file err = unzGoToNextFile(zf); // If that was the last one, we'll use it } while (err != UNZ_END_OF_LIST_OF_FILE); tsms.Size_ROM = zf_infos.uncompressed_size; // Setting driver ------------------------------------------------------------ // Must be done there because we don't have the filename before.. g_machine.driver_id = drv_get_from_filename_extension(temp); // Remove Header & Footer Load_Header_and_Footer_Remove(&start_at, &tsms.Size_ROM); // Check out if the ROM isn't actually empty if (tsms.Size_ROM <= 0) { unzClose (zf); return (MEKA_ERR_FILE_EMPTY); } /* File empty */ // Allocate necessary memory to load ROM ------------------------------------- if (Load_ROM_Init_Memory () == -1) { unzClose (zf); return (MEKA_ERR_MEMORY); } /* Not enough memory */ // Opening.. err = unzOpenCurrentFile (zf); if (err != UNZ_OK) { unzClose (zf); return (MEKA_ERR_ZIP_INTERNAL); } // Skipping header if necessary.. if (start_at != 0) unzReadCurrentFile (zf, ROM, start_at); // Reading.. err = unzReadCurrentFile (zf, ROM, tsms.Size_ROM); if (err < 0 || err != tsms.Size_ROM) { unzCloseCurrentFile (zf); unzClose (zf); return (MEKA_ERR_ZIP_INTERNAL); } // Closing.. unzCloseCurrentFile (zf); unzClose (zf); return (MEKA_ERR_OK); }
/** * Returns a list of files from a zip file. returns NULL on failure, * returns a pointer to an array of strings if successful. Sets nfiles * to the number of files. */ zip_dir *ZIP_GetFiles(const char *pszFileName) { int nfiles; unsigned int i; unz_global_info gi; int err; unzFile uf; char **filelist; unz_file_info file_info; char filename_inzip[ZIP_PATH_MAX]; zip_dir *zd; uf = unzOpen(pszFileName); if (uf == NULL) { Log_Printf(LOG_ERROR, "ZIP_GetFiles: Cannot open %s\n", pszFileName); return NULL; } err = unzGetGlobalInfo(uf,&gi); if (err != UNZ_OK) { Log_Printf(LOG_ERROR, "Error %d with zipfile in unzGetGlobalInfo \n",err); return NULL; } /* allocate a file list */ filelist = (char **)malloc(gi.number_entry*sizeof(char *)); if (!filelist) { perror("ZIP_GetFiles"); return NULL; } nfiles = gi.number_entry; /* set the number of files */ for (i = 0; i < gi.number_entry; i++) { err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, ZIP_PATH_MAX, NULL, 0, NULL, 0); if (err != UNZ_OK) { free(filelist); return NULL; } filelist[i] = (char *)malloc(strlen(filename_inzip) + 1); if (!filelist[i]) { perror("ZIP_GetFiles"); free(filelist); return NULL; } strcpy(filelist[i], filename_inzip); if ((i+1) < gi.number_entry) { err = unzGoToNextFile(uf); if (err != UNZ_OK) { Log_Printf(LOG_ERROR, "ZIP_GetFiles: Error in ZIP-file\n"); /* deallocate memory */ for (; i > 0; i--) free(filelist[i]); free(filelist); return NULL; } } } unzClose(uf); zd = (zip_dir *)malloc(sizeof(zip_dir)); if (!zd) { perror("ZIP_GetFiles"); free(filelist); return NULL; } zd->names = filelist; zd->nfiles = nfiles; return zd; }
/** ************************************************************************** * \brief List files in zip and append their names to p_array * \param p_this * \param file Opened zip file * \param p_array vlc_array_t which will receive all filenames * * In case of error, returns VLC_EGENERIC. * In case of success, returns number of files found, and goes back to first file. *****************************************************************************/ static int GetFilesInZip( stream_t *p_this, unzFile file, vlc_array_t *p_filenames, vlc_array_t *p_fileinfos ) { if( !p_filenames || !p_this ) return VLC_EGENERIC; int i_ret = 0; /* Get global info */ unz_global_info info; if( unzGetGlobalInfo( file, &info ) != UNZ_OK ) { msg_Warn( p_this, "this is not a valid zip archive" ); return VLC_EGENERIC; } /* Go to first file in archive */ unzGoToFirstFile( file ); /* Get info about each file */ for( unsigned long i = 0; i < info.number_entry; i++ ) { char *psz_fileName = calloc( ZIP_FILENAME_LEN, 1 ); unz_file_info *p_fileInfo = calloc( 1, sizeof( unz_file_info ) ); if( !p_fileInfo || !psz_fileName ) { free( psz_fileName ); free( p_fileInfo ); return VLC_ENOMEM; } if( unzGetCurrentFileInfo( file, p_fileInfo, psz_fileName, ZIP_FILENAME_LEN, NULL, 0, NULL, 0 ) != UNZ_OK ) { msg_Warn( p_this, "can't get info about file in zip" ); free( psz_fileName ); free( p_fileInfo ); return VLC_EGENERIC; } if( p_filenames ) vlc_array_append( p_filenames, strdup( psz_fileName ) ); free( psz_fileName ); if( p_fileinfos ) vlc_array_append( p_fileinfos, p_fileInfo ); else free( p_fileInfo ); if( i < ( info.number_entry - 1 ) ) { /* Go the next file in the archive */ if( unzGoToNextFile( file ) != UNZ_OK ) { msg_Warn( p_this, "can't go to next file in zip" ); return VLC_EGENERIC; } } i_ret++; } /* i_ret should be equal to info.number_entry */ unzGoToFirstFile( file ); return i_ret; }
KDbool AssetsManager::uncompress_ ( KDvoid ) { // Open the zip file std::string sOutFileName = m_sStoragePath + TEMP_PACKAGE_FILE_NAME; unzFile pZipFile = unzOpen ( sOutFileName.c_str ( ) ); if ( !pZipFile ) { CCLOG ( "can not open downloaded zip file %s", sOutFileName.c_str ( ) ); return KD_FALSE; } // Get info about the zip file unz_global_info tGlobalInfo; if ( unzGetGlobalInfo ( pZipFile, &tGlobalInfo ) != UNZ_OK ) { CCLOG ( "can not read file global info of %s", sOutFileName.c_str ( ) ); unzClose ( pZipFile ); } // Buffer to hold data read from the zip file KDchar aReadBuffer [ BUFFER_SIZE ]; CCLOG ( "start uncompressing" ); // Loop to extract all files. uLong i; for ( i = 0; i < tGlobalInfo.number_entry; ++i ) { // Get info about current file. unz_file_info tFileInfo; KDchar szFileName[MAX_FILENAME]; if ( unzGetCurrentFileInfo ( pZipFile, &tFileInfo, szFileName, MAX_FILENAME, NULL, 0, NULL, 0 ) != UNZ_OK ) { CCLOG ( "can not read file info" ); unzClose ( pZipFile ); return KD_FALSE; } std::string sFullPath = m_sStoragePath + szFileName; // Check if this entry is a directory or a file. const KDsize uFilenameLength = kdStrlen ( szFileName ); if ( szFileName [ uFilenameLength - 1 ] == '/' ) { // Entry is a direcotry, so create it. // If the directory exists, it will failed scilently. if ( !createDirectory ( sFullPath.c_str ( ) ) ) { CCLOG ( "can not create directory %s", sFullPath.c_str ( ) ); unzClose ( pZipFile ); return KD_FALSE; } } else { // Entry is a file, so extract it. // Open current file. if ( unzOpenCurrentFile ( pZipFile ) != UNZ_OK ) { CCLOG ( "can not open file %s", szFileName ); unzClose ( pZipFile ); return KD_FALSE; } // Create a file to store current file. KDFile* pOut = kdFopen ( sFullPath.c_str ( ), "wb" ); if ( !pOut ) { CCLOG ( "can not open destination file %s", sFullPath.c_str ( ) ); unzCloseCurrentFile ( pZipFile ); unzClose ( pZipFile ); return KD_FALSE; } // Write current file content to destinate file. KDint nError = UNZ_OK; do { nError = unzReadCurrentFile ( pZipFile, aReadBuffer, BUFFER_SIZE ); if ( nError < 0 ) { CCLOG ( "can not read zip file %s, error code is %d", szFileName, nError ); unzCloseCurrentFile ( pZipFile ); unzClose( pZipFile ); return KD_FALSE; } if ( nError > 0 ) { kdFwrite ( aReadBuffer, nError, 1, pOut ); } } while ( nError > 0 ); kdFclose ( pOut ); } unzCloseCurrentFile ( pZipFile ); // Goto next entry listed in the zip file. if ( ( i + 1 ) < tGlobalInfo.number_entry ) { if ( unzGoToNextFile ( pZipFile ) != UNZ_OK ) { CCLOG ( "can not read next file" ); unzClose ( pZipFile ); return KD_FALSE; } } } CCLOG ( "end uncompressing" ); return KD_TRUE; }
void CFileCollection::readFile(CFile &file){ unz_file_info info; U32 size; string name; switch(col_type){ case NativeCollection: name = fixSlashes(file.getName()); if(name[0] == '/') name.erase(name.begin()); if (unzLocateFile(zh, name.c_str(), 2) == UNZ_OK){ if (unzOpenCurrentFile(zh) == UNZ_OK){ if (unzGetCurrentFileInfo(zh, &info, NULL, 0, NULL, 0, NULL, 0)!= UNZ_OK) return; size = info.uncompressed_size; file.setSize(size); if((U32)unzReadCurrentFile(zh, file.getData(), size) != size){ unzCloseCurrentFile(zh); file.freeData(); return; } unzCloseCurrentFile(zh); return; } } else { string fname = name + "/"; if (unzLocateFile(zh, fname.c_str(), 2) == UNZ_OK){ CVirtualFS::FindResult fr; Unz_GetStringForDir((unzFile*)zh, fname, "", fr); string data; CVirtualFS::FindResult::iterator i; for(i = fr.begin();i != fr.end();i++){ data += (*i).getName(); data += "\n"; } data += "\0"; file.setSize(data.size()); memcpy(file.getData(), data.c_str(), data.size()); file.setIsDirectory(true); return; } } break; case Directory: S32 i = 0; FILE *fp = 0; U32 size; string fullName = file.getName(); i = fullName.find(mMountPoint, 0); if(i == string::npos){ return; } fullName.replace(i, mMountPoint.size(), ""); if(fullName[0] == '/') fullName.replace(0, 1, ""); fullName = colPath + fullName; #ifdef _WIN32 struct _finddata_t fileinfo; string pattern = fullName + "/*.*"; S32 hd = _findfirst(pattern.c_str(), &fileinfo); if(hd != -1){ // It is a directory string data(""); do { data += fullName + "/" + fileinfo.name + "\n"; } while (_findnext(hd, &fileinfo) != -1); data += "\0"; file.setSize(data.size()); memcpy(file.getData(), data.c_str(), data.size()); file.setIsDirectory(true); _findclose(hd); return; } #else //assert(0 && "NOT IMPLEMENTED DIRECTORY CHECK"); DIR *dirp; struct dirent *dp; dirp = opendir(fullName.c_str()); if(dirp){ string data(""); while( (dp = readdir(dirp)) != NULL ){ if(*dp->d_name == '.') continue; data += fullName + "/" + dp->d_name + "\n"; } data += "\0"; file.setSize(data.size()); memcpy(file.getData(), data.c_str(), data.size()); file.setIsDirectory(true); closedir(dirp); return; } #endif #ifdef _WIN32 while((i = fullName.find('/', i)) != string::npos){ fullName.replace(i, 1, "\\"); } #endif if (!fp) fp = fopen(fullName.c_str(), "rb"); if (fp) { fseek(fp, 0, SEEK_END); size = ftell(fp); fseek(fp, 0, SEEK_SET); file.setSize(size); if (file.getData()) fread(file.getData(), 1, size, fp); fclose(fp); return; } } }
int do_extract_currentfile(unzFile uf, const int* popt_extract_without_path, int*, const char* password) { char fn_inzip[256]; QString filename_inzip; QString filename_withoutpath; int err=UNZ_OK; FILE *fout=NULL; void* buf; uInt size_buf; unz_file_info file_info; //uLong ratio=0; err = unzGetCurrentFileInfo(uf,&file_info,fn_inzip,sizeof(fn_inzip),NULL,0,NULL,0); if (err!=UNZ_OK) return err; size_buf = WRITEBUFFERSIZE; buf = (void*)malloc(size_buf); if (buf==NULL) return UNZ_INTERNALERROR; QChar p; // uint cIndex = 0; filename_inzip = QString::fromLocal8Bit(fn_inzip); filename_withoutpath = filename_inzip; for (int i = 0; i < filename_inzip.length(); i++) { p = filename_inzip[i]; if( (p == '/') || (p =='\\')) filename_withoutpath = filename_inzip.mid(i+1); } if (filename_withoutpath.isEmpty()) { if ((*popt_extract_without_path)==0) mymkdir(filename_inzip); } else { QString write_filename; int skip=0; if ((*popt_extract_without_path)==0) write_filename = filename_inzip; else write_filename = filename_withoutpath; err = unzOpenCurrentFilePassword(uf,password); if ((skip==0) && (err==UNZ_OK)) { fout = openfile(write_filename, "wb"); /* some zipfile don't contain directory alone before file */ if ((fout==NULL) && ((*popt_extract_without_path)==0) && (filename_withoutpath != filename_inzip)) { uint len = filename_inzip.length() - filename_withoutpath.length() - 1; QString write_dir = filename_inzip.left(len); makedir(write_dir); fout = openfile(write_filename, "wb"); } } if (fout!=NULL) { do { err = unzReadCurrentFile(uf,buf,size_buf); if (err<0) break; if (err>0) if (fwrite(buf,err,1,fout)!=1) { err=UNZ_ERRNO; break; } } while (err>0); if (fout) fclose(fout); if (err==0) change_file_date(write_filename,file_info.dosDate, file_info.tmu_date); } if (err==UNZ_OK) err = unzCloseCurrentFile (uf); else unzCloseCurrentFile(uf); /* don't lose the error */ } free(buf); return err; }
/* ======================================================================================================================= ======================================================================================================================= */ long __cdecl ReadZippedRomHeader(char *rompath, INI_ENTRY *ini_entry) { long int filesize; unzFile fp; char szFileName[256]; char ext[_MAX_EXT]; uint8 buffer[0x100]; /* DisplayError("Read Zipped Rom Header: %s",rompath); */ fp = unzOpen(rompath); if(fp == NULL) { return FALSE; /* Cannot open this ZIP file */ } if(unzGoToFirstFile(fp) == UNZ_OK) { do { /*~~~~~~~~~~~~~~~~~~~~~~*/ unz_file_info file_info; /*~~~~~~~~~~~~~~~~~~~~~~*/ if(unzGetCurrentFileInfo(fp, &file_info, szFileName, 256, NULL, 0, NULL, 0) == UNZ_OK) { filesize = file_info.uncompressed_size; if(filesize & 0xFFFF) filesize = filesize + (0x10000 - (filesize & 0xFFFF)); strcpy(ext, szFileName + strlen(szFileName) - 4); if ( stricmp(ext, ".bin") == 0 || stricmp(ext, ".v64") == 0 || stricmp(ext, ".rom") == 0 || stricmp(ext, ".usa") == 0 || stricmp(ext, ".j64") == 0 || stricmp(ext, ".pal") == 0 || stricmp(ext, ".z64") == 0 || stricmp(ext, ".n64") == 0 ) { if(unzOpenCurrentFile(fp) == UNZ_OK) { if(unzReadCurrentFile(fp, buffer, 0x40) == 0x40) { if(ByteSwap(0x40, buffer)) { strncpy((char*)ini_entry->Game_Name, (const char*)(buffer + 0x20), 0x14); SwapRomName((unsigned char*)ini_entry->Game_Name); /* SwapRomHeader(buffer); */ ini_entry->crc1 = *((uint32 *) (buffer + 0x10)); ini_entry->crc2 = *((uint32 *) (buffer + 0x14)); ini_entry->countrycode = buffer[0x3D]; /* ini_entry->countrycode = buffer[0x3E]; */ unzCloseCurrentFile(fp); unzClose(fp); return filesize; } } unzCloseCurrentFile(fp); } } } } while(unzGoToNextFile(fp) == UNZ_OK); } unzClose(fp); return 0; /* Read ZIP file fails for some reason */ }
static int do_extract_currentfile( unzFile uf, const int* popt_extract_without_path, int* popt_overwrite, const char* password, ZnkStr ermsg, ZnkZipProgressFuncT progress_func, void* param, size_t num_of_entry, size_t idx_of_entry ) { char filename_inzip[256]; char* filename_withoutpath; /* tail */ char* p; int err=UNZ_OK; FILE* fout=NULL; void* buf; uInt size_buf; char rep_buf[ 512 ] = ""; unz_file_info file_info; err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, /* extraField */ NULL, 0 /* szComment */ ); if( err != UNZ_OK ){ ZnkStr_addf( ermsg, "ZnkZip : Error : %d with zipfile in unzGetCurrentFileInfo\n", err ); return err; } size_buf = WRITEBUFFERSIZE; buf = (void*)malloc(size_buf); if( buf == NULL ){ Znk_printf_e( "Error : allocating memory\n" ); return UNZ_INTERNALERROR; } p = filename_withoutpath = filename_inzip; while( (*p) != '\0' ){ if (((*p)=='/') || ((*p)=='\\')) filename_withoutpath = p+1; p++; } if( (*filename_withoutpath)=='\0' ){ /* tail is empty : thus, this is directory */ if( (*popt_extract_without_path)==0 ){ if( progress_func ){ Znk_snprintf( rep_buf, sizeof(rep_buf), "creating directory: %s", filename_inzip ); (*progress_func)( rep_buf, num_of_entry, idx_of_entry, param ); } mymkdir(filename_inzip); } } else { const char* write_filename; int skip=0; if( (*popt_extract_without_path)==0 ){ write_filename = filename_inzip; } else { write_filename = filename_withoutpath; } err = unzOpenCurrentFilePassword( uf, password ); if( err != UNZ_OK ){ ZnkStr_addf( ermsg, "ZnkZip : Error : %d with zipfile in unzOpenCurrentFilePassword.\n", err ); } #if 0 if( ((*popt_overwrite)==0) && (err==UNZ_OK) ){ char rep=0; FILE* ftestexist; ftestexist = fopen(write_filename,"rb"); if( ftestexist != NULL ){ fclose(ftestexist); do { char answer[128]; int ret; Znk_printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename); ret = scanf("%1s",answer); if (ret != 1) { exit(EXIT_FAILURE); } rep = answer[0] ; if ((rep>='a') && (rep<='z')) rep -= 0x20; } while ((rep!='Y') && (rep!='N') && (rep!='A')); } if (rep == 'N') skip = 1; if (rep == 'A') *popt_overwrite=1; } #else *popt_overwrite = 1; /* all-overwrite */ #endif if( (skip==0) && (err==UNZ_OK) ){ fout = fopen( write_filename, "wb" ); /* some zipfile don't contain directory alone before file */ if( ( fout==NULL ) && ( (*popt_extract_without_path)==0 ) && ( filename_withoutpath != (char*)filename_inzip ) ){ char c = *(filename_withoutpath-1); *(filename_withoutpath-1)='\0'; makedir( write_filename ); *(filename_withoutpath-1)=c; fout = fopen( write_filename, "wb" ); } if( fout == NULL ){ ZnkStr_addf( ermsg, "ZnkZip : Error : opening [%s].\n", write_filename ); } } if( fout != NULL ){ //Znk_printf(" extracting: %s\n",write_filename); if( progress_func ){ Znk_snprintf( rep_buf, sizeof(rep_buf), "extracting: %s", write_filename ); (*progress_func)( rep_buf, num_of_entry, idx_of_entry, param ); } do{ err = unzReadCurrentFile(uf,buf,size_buf); if( err < 0 ){ ZnkStr_addf( ermsg, "ZnkZip : Error : %d with zipfile in unzReadCurrentFile\n", err ); break; } else if( err > 0 ){ if( fwrite(buf,err,1,fout) != 1 ){ ZnkStr_addf( ermsg, "ZnkZip : Error : in writing extracted file\n" ); err=UNZ_ERRNO; break; } } } while( err>0 ); if (fout) fclose(fout); if (err==0){ change_file_date( write_filename, file_info.dosDate, file_info.tmu_date ); } } if( err==UNZ_OK ){ err = unzCloseCurrentFile (uf); if (err!=UNZ_OK){ ZnkStr_addf( ermsg, "ZnkZip : Error : %d with zipfile in unzCloseCurrentFile\n", err ); } } else { unzCloseCurrentFile(uf); /* don't lose the error */ } } free(buf); return err; }
/* ======================================================================================================================= ======================================================================================================================= */ BOOL ReadZippedRomData(char *rompath) { /*~~~~~~~~~~~~~~~~~~~~~~~*/ unzFile fp; unsigned long gROMLength; /* size in bytes of the ROM */ /*~~~~~~~~~~~~~~~~~~~~~~~*/ if(fp = unzOpen(rompath)) { /*~~~~~~~~~~~~~~~~~~~~*/ char szFileName[256]; /*~~~~~~~~~~~~~~~~~~~~*/ if(unzGoToFirstFile(fp) == UNZ_OK) { do { /*~~~~~~~~~~~~~~~~~~~~~~*/ unz_file_info file_info; /*~~~~~~~~~~~~~~~~~~~~~~*/ if(unzGetCurrentFileInfo(fp, &file_info, szFileName, 256, NULL, 0, NULL, 0) == UNZ_OK) { if ( stricmp(&szFileName[strlen(szFileName) - 4], ".bin") == 0 || stricmp(&szFileName[strlen(szFileName) - 4], ".v64") == 0 || stricmp(&szFileName[strlen(szFileName) - 4], ".rom") == 0 || stricmp(&szFileName[strlen(szFileName) - 4], ".usa") == 0 || stricmp(&szFileName[strlen(szFileName) - 4], ".z64") == 0 || stricmp(&szFileName[strlen(szFileName) - 4], ".j64") == 0 || stricmp(&szFileName[strlen(szFileName) - 4], ".pal") == 0 || stricmp(&szFileName[strlen(szFileName) - 4], ".n64") == 0 ) { gROMLength = file_info.uncompressed_size; /* get size of ROM */ /* pad with zeros to fill the displacement */ if(((gROMLength & 0xFFFF)) == 0) gAllocationLength = gROMLength; else gAllocationLength = gROMLength + (0x10000 - (gROMLength & 0xFFFF)); if(unzOpenCurrentFile(fp) == UNZ_OK) { uint64 i; InitVirtualRomMemory(gAllocationLength); InitMemoryLookupTables(); InitTLB(); Is_Reading_Rom_File = TRUE;; To_Stop_Reading_Rom_File = FALSE; sprintf(generalmessage, "%s [%s] ", TranslateStringByString("Loading"), szFileName); SetStatusBarText(0, generalmessage); for(i = 0; i < gROMLength && To_Stop_Reading_Rom_File == FALSE; i += 65536) /* for( i=0; i<gROMLength; i+=65536) */ { WindowMsgLoop(); if(To_Stop_Reading_Rom_File == TRUE) { CloseROM(); To_Stop_Reading_Rom_File = FALSE; Is_Reading_Rom_File = FALSE; unzClose(fp); return FALSE; } /* fread(gMS_ROM_Image+i, sizeof(uint8), 65536, fp); */ if(unzReadCurrentFile(fp, gMS_ROM_Image + i, sizeof(uint8) * 65536) == 65536) { sprintf(generalmessage, "%s [%s] %d%%", TranslateStringByString("Loading"), szFileName, i * 100 / gROMLength); SetStatusBarText(0, generalmessage); } else if(unzReadCurrentFile(fp, gMS_ROM_Image + i, 1) == 0) { sprintf(generalmessage, "%s [%s] %d%%", TranslateStringByString("Loading"), szFileName, i * 100 / gROMLength); SetStatusBarText(0, generalmessage); } else { DisplayError("File could not be read. gROMLength = %08X\n", gROMLength); CloseROM(); unzCloseCurrentFile(fp); unzClose(fp); Set_Ready_Message(); Is_Reading_Rom_File = FALSE; return FALSE; } } ByteSwap(gAllocationLength, gMS_ROM_Image); memcpy((uint8 *) &rominfo.validation, gMS_ROM_Image, 0x40); SwapRomHeader((uint8 *) &rominfo.validation); /* Copy boot code to SP_DMEM */ memcpy((uint8 *) &SP_DMEM, gMS_ROM_Image, 0x1000); memcpy(rominfo.name, gMS_ROM_Image + 0x20, 20); SwapRomName(rominfo.name); Set_Ready_Message(); unzCloseCurrentFile(fp); unzClose(fp); Is_Reading_Rom_File = FALSE; return TRUE; } else { DisplayError("File could not be read: CRC Error in zip."); unzClose(fp); return FALSE; } } } else { DisplayError("File could not unzipped."); unzClose(fp); return FALSE; } } while(unzGoToNextFile(fp) == UNZ_OK); } unzClose(fp); } return FALSE; }
bool AssetsManagerEx::decompress(const std::string &zip) { // Find root path for zip file size_t pos = zip.find_last_of("/\\"); if (pos == std::string::npos) { CCLOG("AssetsManagerEx : no root path specified for zip file %s\n", zip.c_str()); return false; } const std::string rootPath = zip.substr(0, pos+1); // Open the zip file unzFile zipfile = unzOpen(FileUtils::getInstance()->getSuitableFOpen(zip).c_str()); if (! zipfile) { CCLOG("AssetsManagerEx : can not open downloaded zip file %s\n", zip.c_str()); return false; } // Get info about the zip file unz_global_info global_info; if (unzGetGlobalInfo(zipfile, &global_info) != UNZ_OK) { CCLOG("AssetsManagerEx : can not read file global info of %s\n", zip.c_str()); unzClose(zipfile); return false; } // Buffer to hold data read from the zip file char readBuffer[BUFFER_SIZE]; // Loop to extract all files. uLong i; for (i = 0; i < global_info.number_entry; ++i) { // Get info about current file. unz_file_info fileInfo; char fileName[MAX_FILENAME]; if (unzGetCurrentFileInfo(zipfile, &fileInfo, fileName, MAX_FILENAME, NULL, 0, NULL, 0) != UNZ_OK) { CCLOG("AssetsManagerEx : can not read compressed file info\n"); unzClose(zipfile); return false; } const std::string fullPath = rootPath + fileName; // Check if this entry is a directory or a file. const size_t filenameLength = strlen(fileName); if (fileName[filenameLength-1] == '/') { //There are not directory entry in some case. //So we need to create directory when decompressing file entry if ( !_fileUtils->createDirectory(basename(fullPath)) ) { // Failed to create directory CCLOG("AssetsManagerEx : can not create directory %s\n", fullPath.c_str()); unzClose(zipfile); return false; } } else { // Create all directories in advance to avoid issue std::string dir = basename(fullPath); if (!_fileUtils->isDirectoryExist(dir)) { if (!_fileUtils->createDirectory(dir)) { // Failed to create directory CCLOG("AssetsManagerEx : can not create directory %s\n", fullPath.c_str()); unzClose(zipfile); return false; } } // Entry is a file, so extract it. // Open current file. if (unzOpenCurrentFile(zipfile) != UNZ_OK) { CCLOG("AssetsManagerEx : can not extract file %s\n", fileName); unzClose(zipfile); return false; } // Create a file to store current file. FILE *out = fopen(FileUtils::getInstance()->getSuitableFOpen(fullPath).c_str(), "wb"); if (!out) { CCLOG("AssetsManagerEx : can not create decompress destination file %s (errno: %d)\n", fullPath.c_str(), errno); unzCloseCurrentFile(zipfile); unzClose(zipfile); return false; } // Write current file content to destinate file. int error = UNZ_OK; do { error = unzReadCurrentFile(zipfile, readBuffer, BUFFER_SIZE); if (error < 0) { CCLOG("AssetsManagerEx : can not read zip file %s, error code is %d\n", fileName, error); fclose(out); unzCloseCurrentFile(zipfile); unzClose(zipfile); return false; } if (error > 0) { fwrite(readBuffer, error, 1, out); } } while(error > 0); fclose(out); } unzCloseCurrentFile(zipfile); // Goto next entry listed in the zip file. if ((i+1) < global_info.number_entry) { if (unzGoToNextFile(zipfile) != UNZ_OK) { CCLOG("AssetsManagerEx : can not read next file for decompressing\n"); unzClose(zipfile); return false; } } } unzClose(zipfile); return true; }
static int virgo__lua_loader_zip2buf(virgo_t* v, const char *name, char **p_buf, size_t *p_len) { struct unz_file_info_s finfo; unzFile zip = NULL; char *buf; size_t len; int rv; int rc = 0; /* TODO: would be nice to have better error handling / messages from this method */ *p_buf = NULL; *p_len = 0; zip = unzOpen(v->lua_load_path); if (zip == NULL) { rc = -1; goto cleanup; } /* 1 means case sensitive file comparison */ rv = unzLocateFile(zip, name, 1); if (rv != UNZ_OK) { rc = -2; goto cleanup; } memset(&finfo, '0', sizeof(finfo)); rv = unzGetCurrentFileInfo(zip, &finfo, NULL, 0, NULL, 0, NULL, 0); if (rv != UNZ_OK) { rc = -3; goto cleanup; } rv = unzOpenCurrentFile(zip); if (rv != UNZ_OK) { rc = -4; goto cleanup; } buf = malloc(finfo.uncompressed_size); len = finfo.uncompressed_size; rv = unzReadCurrentFile(zip, buf, len); if (rv != (int)len) { free(buf); rc = -5; goto cleanup; } *p_buf = buf; *p_len = len; cleanup: if (zip) { unzCloseCurrentFile(zip); unzClose(zip); } return rc; }
int loadFromZipByName(unsigned char *buffer, char *archive, char *filename, int *filesize) { char name[_MAX_PATH]; //unsigned char *buffer; int i; const char *recognizedExtensions[] = { ".ngp", ".npc", ".ngc" }; int zerror = UNZ_OK; unzFile zhandle; unz_file_info zinfo; zhandle = unzOpen(archive); if(!zhandle) return (0); /* Seek to first file in archive */ zerror = unzGoToFirstFile(zhandle); if(zerror != UNZ_OK) { unzClose(zhandle); return (0); } //On scanne tous les fichiers de l'archive et ne prend que ceux qui ont une extension valable, sinon on prend le dernier fichier trouvé... while (zerror == UNZ_OK) { if (unzGetCurrentFileInfo(zhandle, &zinfo, name, 0xff, NULL, 0, NULL, 0) != UNZ_OK) { unzClose(zhandle); return 0; } //Vérifions que c'est la bonne extension char *extension = getFileNameExtension(name); for (i=0;i<numberof(recognizedExtensions);i++) { if (!strcmp(extension, recognizedExtensions[i])) break; } if (i < numberof(recognizedExtensions)) break; zerror = unzGoToNextFile(zhandle); } /* Get information about the file */ // unzGetCurrentFileInfo(zhandle, &zinfo, &name[0], 0xff, NULL, 0, NULL, 0); *filesize = zinfo.uncompressed_size; /* Error: file size is zero */ if(*filesize <= 0 || *filesize > (4*1024*1024)) { unzClose(zhandle); return (0); } /* Open current file */ zerror = unzOpenCurrentFile(zhandle); if(zerror != UNZ_OK) { unzClose(zhandle); return (0); } /* Allocate buffer and read in file */ //buffer = malloc(*filesize); //if(!buffer) return (NULL); zerror = unzReadCurrentFile(zhandle, buffer, *filesize); /* Internal error: free buffer and close file */ if(zerror < 0 || zerror != *filesize) { //free(buffer); //buffer = NULL; unzCloseCurrentFile(zhandle); unzClose(zhandle); return (0); } /* Close current file and archive file */ unzCloseCurrentFile(zhandle); unzClose(zhandle); memcpy(filename, name, _MAX_PATH); return 1; }
void* HGE_CALL HGE_Impl::Resource_Load(const char *filename, hgeU32 *size) { static char *res_err="Can't load resource: %s"; CResourceList *resItem=res; char szName[_MAX_PATH]; char szZipName[_MAX_PATH]; unzFile zip; unz_file_info file_info; int done, i; void *ptr; HANDLE hF; if(filename[0]=='\\' || filename[0]=='/' || filename[1]==':') { goto _fromfile; // skip absolute paths } // Load from pack strcpy(szName,filename); strupr(szName); for(i=0; szName[i]; i++) { if(szName[i]=='/') { szName[i]='\\'; } } while(resItem) { zip=unzOpen(resItem->filename); done=unzGoToFirstFile(zip); while(done==UNZ_OK) { unzGetCurrentFileInfo(zip, &file_info, szZipName, sizeof(szZipName), NULL, 0, NULL, 0); strupr(szZipName); for(i=0; szZipName[i]; i++) { if(szZipName[i]=='/') { szZipName[i]='\\'; } } if(!strcmp(szName,szZipName)) { if(unzOpenCurrentFilePassword(zip, resItem->password[0] ? resItem->password : 0) != UNZ_OK) { unzClose(zip); sprintf(szName, res_err, filename); _PostError(szName); return 0; } ptr = malloc(file_info.uncompressed_size); if(!ptr) { unzCloseCurrentFile(zip); unzClose(zip); sprintf(szName, res_err, filename); _PostError(szName); return 0; } if(unzReadCurrentFile(zip, ptr, file_info.uncompressed_size) < 0) { unzCloseCurrentFile(zip); unzClose(zip); free(ptr); sprintf(szName, res_err, filename); _PostError(szName); return 0; } unzCloseCurrentFile(zip); unzClose(zip); if(size) { *size=file_info.uncompressed_size; } return ptr; } done=unzGoToNextFile(zip); } unzClose(zip); resItem=resItem->next; } // Load from file _fromfile: hF = CreateFile(Resource_MakePath(filename), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS, NULL); if(hF == INVALID_HANDLE_VALUE) { sprintf(szName, res_err, filename); _PostError(szName); return 0; } file_info.uncompressed_size = GetFileSize(hF, NULL); ptr = malloc(file_info.uncompressed_size); if(!ptr) { CloseHandle(hF); sprintf(szName, res_err, filename); _PostError(szName); return 0; } if(ReadFile(hF, ptr, file_info.uncompressed_size, &file_info.uncompressed_size, NULL ) == 0) { CloseHandle(hF); free(ptr); sprintf(szName, res_err, filename); _PostError(szName); return 0; } CloseHandle(hF); if(size) { *size=file_info.uncompressed_size; } return ptr; }
void CArchive::InitItems() { // Loading archive info ArchiveGuard arch(mPath.string().c_str()); unz_global_info gi; unzGetGlobalInfo(arch.file, &gi); // Reserving space for items mItems.reserve(gi.number_entry); if(unzGoToFirstFile(arch.file) != UNZ_OK) return; unz_file_info fi; std::vector<char> fnbuf(100); // Iterating through children and creating resource wrappers do { // Getting resource info unzGetCurrentFileInfo(arch.file, &fi, &fnbuf[0], (unsigned long)(fnbuf.size() - 1), 0, 0, 0, 0); if(fi.size_filename >= (fnbuf.size() - 1)) { fnbuf.resize(fi.size_filename + 50); unzGetCurrentFileInfo(arch.file, &fi, &fnbuf[0], (unsigned long)(fnbuf.size() - 1), 0, 0, 0, 0); } // Forming name and path bool isFolder = fnbuf[fi.size_filename - 1] == '/'; if(isFolder) fnbuf[fi.size_filename - 1] = 0; std::string itName(&fnbuf[0]); boost::filesystem::path p(mPath); p /= boost::filesystem::path(itName); IResource* loaded; mFileSystem->TryGetResource(p, &loaded); if(!loaded) { // Resolving file or folder if(isFolder) { CArchFolder* fld; create_instance_impl<CArchFolder>(&fld); fld->FinalConstruct(mFileSystem, mPath, p); loaded = fld; } else { CArchFile* file; create_instance_impl<CArchFile>(&file); file->FinalConstruct(mFileSystem, mPath, p, unzGetOffset(arch.file)); loaded = file; } mFileSystem->AddHandle(p.string(), loaded); } // Ref count == 1 now mItems.push_back(loaded); } while(unzGoToNextFile(arch.file) != UNZ_END_OF_LIST_OF_FILE); }
//=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== quakefile_t *FindQuakeFilesInZip(char *zipfile, char *filter) { unzFile uf; int err; unz_global_info gi; char filename_inzip[MAX_PATH]; unz_file_info file_info; int i; quakefile_t *qfiles, *lastqf, *qf; uf = unzOpen(zipfile); err = unzGetGlobalInfo(uf, &gi); if(err != UNZ_OK) { return NULL; } unzGoToFirstFile(uf); qfiles = NULL; lastqf = NULL; for(i = 0; i < gi.number_entry; i++) { err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); if(err != UNZ_OK) { break; } ConvertPath(filename_inzip); if(FileFilter(filter, filename_inzip, false)) { qf = malloc(sizeof(quakefile_t)); if(!qf) { Error("out of memory"); } memset(qf, 0, sizeof(quakefile_t)); strcpy(qf->pakfile, zipfile); strcpy(qf->filename, zipfile); strcpy(qf->origname, filename_inzip); qf->zipfile = true; //memcpy( &buildBuffer[i].zipfileinfo, (unz_s*)uf, sizeof(unz_s)); memcpy(&qf->zipinfo, (unz_s *)uf, sizeof(unz_s)); qf->offset = 0; qf->length = file_info.uncompressed_size; qf->type = QuakeFileType(filename_inzip); //add the file ot the list qf->next = NULL; if(lastqf) { lastqf->next = qf; } else { qfiles = qf; } lastqf = qf; } //end if unzGoToNextFile(uf); } //end for unzClose(uf); return qfiles; } //end of the function FindQuakeFilesInZip
void SE_AssetManager::readAsset(const char* fileName, char*& outData, int& outLen) { if(_DEBUG) LOGD("SE_AssertManager : readAsset file name = '%s'\n", fileName); outData = NULL; outLen = 0; std::list<std::string>::iterator it = mAssetPaths.begin(); for(; it != mAssetPaths.end() ; it++) { std::string stringPath = *it; unzFile uf = NULL; uf = unzOpen(stringPath.c_str()); if (uf != NULL) { if (unzLocateFile(uf,fileName,1) == UNZ_OK) { if(_DEBUG) LOGD("SE_AssertManager : find file at '%s'\n", stringPath.c_str()); unz_file_info file_info; if (unzGetCurrentFileInfo(uf,&file_info,NULL,0,NULL,0,NULL,0) == UNZ_OK) { if (unzOpenCurrentFile(uf) == UNZ_OK) { outLen = file_info.uncompressed_size; outData = new char[outLen]; if(unzReadCurrentFile(uf, outData, outLen) == outLen) { if(_DEBUG) LOGD("SE_AssertManager : readAsset '%s' success\n", fileName); } else { if(_DEBUG) LOGD("SE_AssertManager : readAsset '%s' failes\n", fileName); } } unzCloseCurrentFile(uf); } } unzClose(uf); } if (outData != NULL) { return; } std::string file = stringPath + fileName; SE_IO::readFileAll(file.c_str(), outData, outLen); if (outData != NULL) { if(_DEBUG) { LOGD("SE_AssertManager : find file at '%s'\n", stringPath.c_str()); LOGD("SE_AssertManager : readAsset '%s' success\n", fileName); } return; } } if(_DEBUG) LOGD("SE_AssertManager : can not find file '%s' at any where", fileName); }
Error EditorExportPlatformBB10::export_project(const String& p_path, bool p_debug, int p_flags) { EditorProgress ep("export","Exporting for BlackBerry 10",104); String src_template=custom_package; if (src_template=="") { String err; src_template = find_export_template("bb10.zip", &err); if (src_template=="") { 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 FileSystem for BAR",0); unzFile pkg = unzOpen2(src_template.utf8().get_data(), &io); if (!pkg) { EditorNode::add_io_error("Could not find template zip to export:\n"+src_template); return ERR_FILE_NOT_FOUND; } DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); da->change_dir(EditorSettings::get_singleton()->get_settings_path()); if (da->change_dir("tmp")!=OK) { da->make_dir("tmp"); if (da->change_dir("tmp")!=OK) return ERR_CANT_CREATE; } if (da->change_dir("bb10_export")!=OK) { da->make_dir("bb10_export"); if (da->change_dir("bb10_export")!=OK) { return ERR_CANT_CREATE; } } String bar_dir = da->get_current_dir(); if (bar_dir.ends_with("/")) { bar_dir=bar_dir.substr(0,bar_dir.length()-1); } //THIS IS SUPER, SUPER DANGEROUS!!!! //CAREFUL WITH THIS CODE, MIGHT DELETE USERS HARD DRIVE OR HOME DIR //EXTRA CHECKS ARE IN PLACE EVERYWERE TO MAKE SURE NOTHING BAD HAPPENS BUT STILL.... //BE SUPER CAREFUL WITH THIS PLEASE!!! //BLACKBERRY THIS IS YOUR FAULT FOR NOT MAKING A BETTER WAY!! bool berr = bar_dir.ends_with("bb10_export"); if (berr) { if (da->list_dir_begin()) { EditorNode::add_io_error("Can't ensure that dir is empty:\n"+bar_dir); ERR_FAIL_COND_V(berr,FAILED); }; String f = da->get_next(); while (f != "") { if (f == "." || f == "..") { f = da->get_next(); continue; }; Error err = da->remove(bar_dir + "/" + f); if (err != OK) { EditorNode::add_io_error("Can't ensure that dir is empty:\n"+bar_dir); ERR_FAIL_COND_V(err!=OK,err); }; f = da->get_next(); }; da->list_dir_end(); } else { print_line("ARE YOU CRAZY??? THIS IS A SERIOUS BUG HERE!!!"); ERR_FAIL_V(ERR_OMFG_THIS_IS_VERY_VERY_BAD); } ERR_FAIL_COND_V(!pkg, ERR_CANT_OPEN); int ret = unzGoToFirstFile(pkg); 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; Vector<uint8_t> data; data.resize(info.uncompressed_size); //read unzOpenCurrentFile(pkg); unzReadCurrentFile(pkg,data.ptr(),data.size()); unzCloseCurrentFile(pkg); //write if (file=="bar-descriptor.xml") { _fix_descriptor(data); } if (file=="icon.png") { bool found=false; if (this->icon!="" && this->icon.ends_with(".png")) { FileAccess *f = FileAccess::open(this->icon,FileAccess::READ); if (f) { data.resize(f->get_len()); f->get_buffer(data.ptr(),data.size()); memdelete(f); found=true; } } if (!found) { String appicon = GlobalConfig::get_singleton()->get("application/icon"); if (appicon!="" && appicon.ends_with(".png")) { FileAccess*f = FileAccess::open(appicon,FileAccess::READ); if (f) { data.resize(f->get_len()); f->get_buffer(data.ptr(),data.size()); memdelete(f); } } } } if (file.find("/")) { da->make_dir_recursive(file.get_base_dir()); } FileAccessRef wf = FileAccess::open(bar_dir.plus_file(file),FileAccess::WRITE); wf->store_buffer(data.ptr(),data.size()); ret = unzGoToNextFile(pkg); } ep.step("Adding Files..",2); FileAccess* dst = FileAccess::open(bar_dir+"/data.pck", FileAccess::WRITE); if (!dst) { EditorNode::add_io_error("Can't copy executable file to:\n "+p_path); return ERR_FILE_CANT_WRITE; } save_pack(dst, false, 1024); dst->close(); memdelete(dst); ep.step("Creating BAR Package..",104); String bb_packager=EditorSettings::get_singleton()->get("export/blackberry/host_tools"); bb_packager=bb_packager.plus_file("blackberry-nativepackager"); if (OS::get_singleton()->get_name()=="Windows") bb_packager+=".bat"; if (!FileAccess::exists(bb_packager)) { EditorNode::add_io_error("Can't find packager:\n"+bb_packager); return ERR_CANT_OPEN; } List<String> args; args.push_back("-package"); args.push_back(p_path); if (p_debug) { String debug_token=EditorSettings::get_singleton()->get("export/blackberry/debug_token"); if (!FileAccess::exists(debug_token)) { EditorNode::add_io_error("Debug token not found!"); } else { args.push_back("-debugToken"); args.push_back(debug_token); } args.push_back("-devMode"); args.push_back("-configuration"); args.push_back("Device-Debug"); } else { args.push_back("-configuration"); args.push_back("Device-Release"); } args.push_back(bar_dir.plus_file("bar-descriptor.xml")); int ec; Error err = OS::get_singleton()->execute(bb_packager,args,true,NULL,NULL,&ec); if (err!=OK) return err; if (ec!=0) return ERR_CANT_CREATE; return OK; }