bool MpkManip::extractDir(const char* source,const char* target,bool replaceExist,IMpkManipCallback *pCallback,void *p) { bool bOk = true; std::string strSource = source; if(!strSource.empty()) strSource = strSource + "\\*"; else strSource = "*"; SFILE_FIND_DATA fileFindData; HANDLE hFind = SFileFindFirstFile(m_hMpk,strSource.c_str(),&fileFindData,0); if(hFind) { do { std::string targetFilename = std::string(target) + "\\" + fileFindData.cFileName; if(pCallback) { pCallback->onProcessFile(fileFindData.cFileName,p); } if(!extractFile(fileFindData.cFileName,targetFilename.c_str(),replaceExist)) { bOk = false; } } while(SFileFindNextFile(hFind,&fileFindData)); SFileFindClose(hFind); } return bOk; }
void extractFileEntry(GCMFileEntryStruct *e) { /* ** this gets called from recurseFileEntry() ** because of this, we only need to create a directory if e is a directory */ if (!e) return; GCMFetchFilenameForFileEntry(gcmFile, e); //for building the path for where we're making dirs and extracting... char s[1024]; char fp[256] = ""; //now do the actual work... if (e->isDir) { GCMGetFullPathForFileEntry(gcmFile, e, fp); strcpy(s, extractRootPath); strcat(s, fp); lastDir = e; //printf("mkdir %s\n", s); if (e->index == 0) { //if it's the root directory, we're gonna create a directory to extract into named filename.FILES strcat(extractRootPath, "/"); strcat(extractRootPath, filename); strcat(extractRootPath, ".FILES"); // printf("MAKING NEW DIR! %s\n", extractRootPath); mkdir(extractRootPath, S_IRWXU); } else { mkdir(s, S_IRWXU); } } else { GCMGetFullPathForFileEntry(gcmFile, lastDir, fp); strcpy(s, extractRootPath); strcat(s, fp); strcat(s, "/"); strcat(s, e->filename); printf("extracting %s\n", s); extractFile(e, s); } //GCMFetchDataForFileEntry(gcmFile, e); //DOESN'T WORK!!!!!!! return; }
bool BSA::extractAll(const std::string& outputDirName, uint32_t& extractedFileCount) { extractedFileCount = 0; if (!hasAllStructureData()) { std::cout << "BSA::extractAll: Error: not all structure data is present " << "to properly fulfill the requested operation!\n"; return false; } //check for output directory if (!directoryExists(outputDirName)) { if (!createDirectoryRecursive(outputDirName)) { std::cout << "BSA::extractAll: Error: Could not create destination directory \"" << outputDirName << "\".\n"; return false; } } uint32_t i, j; for (i=0; i<m_FolderBlocks.size(); ++i) { //create output directory, if necessary if (!directoryExists(outputDirName+MWTP::pathDelimiter+m_FolderBlocks[i].folderName)) { if (!createDirectoryRecursive(outputDirName+MWTP::pathDelimiter+m_FolderBlocks[i].folderName)) { std::cout << "BSA::extractAll: Error: Could not create destination subdirectory \"" << outputDirName+MWTP::pathDelimiter+m_FolderBlocks[i].folderName << "\".\n"; return false; } } //now extract each file in that directory for (j=0; j<m_FolderBlocks[i].files.size(); ++j) { if (!extractFile(i, j, outputDirName+MWTP::pathDelimiter+m_FolderBlocks[i].folderName +MWTP::pathDelimiter+m_FolderBlocks[i].files[j].fileName)) { std::cout << "BSA::extractAll: Error: Could not extract file \"" <<m_FolderBlocks[i].folderName+MWTP::pathDelimiter +m_FolderBlocks[i].files[j].fileName<< "\".\n"; return false; }//if ++extractedFileCount; }//for j }//for i return true; }
void extractTree(struct Volume *vol, struct List* tree, char *path, unsigned char *extbuf, BOOL pflag, BOOL qflag) { struct Entry* entry; char *buf; char sysbuf[200]; while(tree) { entry = (struct Entry*)tree->content; if (entry->type==ST_DIR) { buf = NULL; if (strlen(path)>0) { buf=(char*)malloc(strlen(path)+1+strlen(entry->name)+1); if (!buf) return; sprintf(buf,"%s%c%s",path,DIRSEP,entry->name); sprintf(sysbuf,"%s %s",MKDIR,buf); if (!qflag) printf("x - %s%c\n",buf,DIRSEP); } else { sprintf(sysbuf,"%s %s",MKDIR,entry->name); if (!qflag) printf("x - %s%c\n",entry->name,DIRSEP); } if (!pflag) system(sysbuf); if (tree->subdir!=NULL) { if (adfChangeDir(vol,entry->name)==RC_OK) { if (buf!=NULL) extractTree(vol,tree->subdir,buf,extbuf, pflag, qflag); else extractTree(vol,tree->subdir,entry->name,extbuf, pflag, qflag); adfParentDir(vol); } else { if (strlen(path)>0) fprintf(stderr,"ExtractTree : dir \"%s/%s\" not found.\n",path,entry->name); else fprintf(stderr,"ExtractTree : dir \"%s\" not found.\n",entry->name); } } if (buf!=NULL) free(buf); } else if (entry->type==ST_FILE) { extractFile(vol,entry->name,path,extbuf, pflag, qflag); } tree = tree->next; } }
bool BSA::extractFile(const std::string& inArchiveFileName, const std::string& outputFileName) { if (!hasAllStructureData()) { std::cout << "BSA::extractFile: Error: not all structure data is present " << "to properly fulfill the requested operation!\n"; return false; } uint32_t folderIndex, fileIndex; getIndexPairForFile(inArchiveFileName, folderIndex, fileIndex); //use the above function for the rest return extractFile(folderIndex, fileIndex, outputFileName); }
string BSAFile::extract(const string& path) { string dir, file; auto pos = path.find_last_of("/\\"); if (pos != string::npos) { dir = path.substr(0, pos); file = path.substr(pos + 1); } else file = path; auto dirHash = pathHash(dir); auto fileHash = pathHash(file); return extractFile(dirHash, fileHash); }
bool BSA::extractFolder(const uint32_t folderIndex, const std::string& outputDirName, uint32_t& extractedFileCount) { extractedFileCount = 0; if (!hasAllStructureData()) { std::cout << "BSA::extractFolder: Error: not all structure data is present " << "to properly fulfill the requested operation!\n"; return false; } if ((folderIndex==cIndexNotFound) or (folderIndex>=m_FolderBlocks.size())) { std::cout << "BSA::extractFolder: Error: invalid folder index!\n"; return false; } //check for output directory if (!directoryExists(outputDirName)) { if (!createDirectoryRecursive(outputDirName)) { std::cout << "BSA::extractFolder: Error: Could not create destination directory \"" << outputDirName << "\".\n"; return false; } } uint32_t file_index; //now extract each file in that directory for (file_index=0; file_index<m_FolderBlocks[folderIndex].files.size(); ++file_index) { if (!extractFile(folderIndex, file_index, outputDirName+MWTP::pathDelimiter +m_FolderBlocks[folderIndex].files[file_index].fileName)) { std::cout << "BSA::extractFolder: Error: Could not extract file \"" << m_FolderBlocks[folderIndex].folderName+MWTP::pathDelimiter +m_FolderBlocks[folderIndex].files[file_index].fileName<< "\".\n"; return false; }//if ++extractedFileCount; }//for file_index return true; }
int pkg2rpkg(const std::string& inputFile, const std::string& outputFile, Rangers::RPKGCompression compression) { ifstream pkgfile(inputFile.c_str(), ios::binary | ios::in); std::map<RPKGEntry*, PKGItem*> itemMap; PKGItem *root = loadPKG(pkgfile); if (root->childCount != 1) { std::cout << "Incorrect input file" << endl; return -1; } countFiles(L"", root, itemMap); //FIXME: OH SHI~ std::vector<RPKGEntry> files; std::vector<PKGItem> pkgfiles; for (std::map<RPKGEntry*, PKGItem*>::iterator i = itemMap.begin(); i != itemMap.end(); i++) { files.push_back(*(i->first)); pkgfiles.push_back(*(i->second)); } int c = itemMap.size(); uint32_t headerSize = calculateRPKGHeaderSize(files); ofstream outfile(outputFile.c_str(), ios::binary | ios::out); //FIXME: Better way to fill file for (int i = 0; i < headerSize + 8; i++) outfile.put(0); for (int i = 0; i < files.size(); i++) { wcout << files[i].name << endl; unsigned char *data = extractFile(pkgfiles[i], pkgfile); appendRPKGFile(outfile, files[i], (const char*)data, pkgfiles[i].size, compression); delete data; } outfile.seekp(0, ios_base::beg); writeRPKGHeader(outfile, files); cleanup(root); delete root; outfile.close(); pkgfile.close(); }
void KTNEFMain::contextMenuEvent( QContextMenuEvent *event ) { QList<KTNEFAttach *> list = mView->getSelection(); if ( !list.count() ) { return; } QAction *view = 0; QAction *viewWith = 0; QAction *prop = 0; KMenu *menu = new KMenu(); if ( list.count() == 1 ) { view = menu->addAction( KIcon( "document-open" ), i18nc( "@action:inmenu", "View" ) ); viewWith = menu->addAction( i18nc( "@action:inmenu", "View With..." ) ); menu->addSeparator(); } QAction *extract = menu->addAction( i18nc( "@action:inmenu", "Extract" ) ); QAction *extractTo = menu->addAction( KIcon( "archive-extract" ), i18nc( "@action:inmenu", "Extract To..." ) ); if ( list.count() == 1 ) { menu->addSeparator(); prop = menu->addAction( KIcon( "document-properties" ), i18nc( "@action:inmenu", "Properties" ) ); } QAction *a = menu->exec( event->globalPos(), 0 ); if ( a ) { if ( a == view ) { viewFile(); } else if ( a == viewWith ) { viewFileAs(); } else if ( a == extract ) { extractFile(); } else if ( a == extractTo ) { extractFileTo(); } else if ( a == prop ) { propertiesFile(); } } delete menu; }
std::vector<openstudio::path> UnzipFile::extractAllFiles(const openstudio::path &outputPath) const { std::vector<openstudio::path> files = listFiles(); std::vector<openstudio::path> retfiles; for (std::vector<openstudio::path>::const_iterator itr = files.begin(); itr != files.end(); ++itr) { if (toString(itr->filename())=="." || toString(itr->filename())=="/") { // This is a directory - skip it } else { retfiles.push_back(extractFile(*itr, outputPath)); } } return retfiles; }
bool MROMInstaller::extractTarball(const std::string& base, const std::string& name, const std::string& tarball) { gui_print("Extrating tarball %s...\n", tarball.c_str()); system("rm /tmp/tarballs/rom.tar.gz"); if(!extractFile(tarball, "/tmp/tarballs/rom.tar.gz")) return false; bool res = true; char cmd[256]; sprintf(cmd, "gnutar --numeric-owner --overwrite -C \"%s\" -xf /tmp/tarballs/rom.tar.gz", (base + "/" + name).c_str()); if(system(cmd) != 0) { gui_print("Failed to extract tarball %s for folder %s!\n", tarball.c_str(), name.c_str()); res = false; } system("rm /tmp/tarballs/rom.tar.gz"); return res; }
int main(int argc, char **argv) { const char *filename = "test3.xml"; const char *pattern = "preserved"; xmlDocPtr doc; if (argc == 3) { filename = argv[1]; pattern = argv[2]; } /* * this initialize the library and check potential ABI mismatches * between the version it was compiled for and the actual shared * library used. */ LIBXML_TEST_VERSION doc = extractFile(filename, (const xmlChar *) pattern); if (doc != NULL) { /* * ouptut the result. */ xmlDocDump(stdout, doc); /* * don't forget to free up the doc */ xmlFreeDoc(doc); } /* * Cleanup function for the XML library. */ xmlCleanupParser(); /* * this is to debug memory for regression tests */ xmlMemoryDump(); return(0); }
size_t ZipArchive::extractFilesToDirectory(const std::string& dirName, const bool replaceExistingFiles) { std::string currentDir = FileSystem::currentDirectory(); if (FileSystem::changeDirectory(dirName) == false) { LERROR("extractFilesToDirectory(): failed to locate target directory '" << dirName << "'!"); return 0; } LINFO("extracting following files to directory '" << dirName << "'..."); size_t counter = 0; for (ArchiveMap::const_iterator it = files_.begin(); it != files_.end(); ++it) { File* xFile = extractFile(it->second.fileName_, TARGET_DISK, "", true, replaceExistingFiles); if (xFile != 0) { xFile->close(); delete xFile; ++counter; } } FileSystem::changeDirectory(currentDir); return counter; }
bool FindSubtitlesWindow::uncompressZip(const QString & filename, const QString & output_path, const QString & preferred_output_name) { qDebug("FindSubtitlesWindow::uncompressZip: zip file '%s', output_path '%s', save subtitle as '%s'", filename.toUtf8().constData(), output_path.toUtf8().constData(), preferred_output_name.toUtf8().constData()); QuaZip zip(filename); if (!zip.open(QuaZip::mdUnzip)) { qWarning("FindSubtitlesWindow::uncompressZip: open zip failed: %d", zip.getZipError()); return false; } zip.setFileNameCodec("IBM866"); qDebug("FindSubtitlesWindow::uncompressZip: %d entries", zip.getEntriesCount()); qDebug("FindSubtitlesWindow::uncompressZip: global comment: '%s'", zip.getComment().toUtf8().constData()); QStringList sub_files; QuaZipFileInfo info; for (bool more=zip.goToFirstFile(); more; more=zip.goToNextFile()) { if (!zip.getCurrentFileInfo(&info)) { qWarning("FindSubtitlesWindow::uncompressZip: getCurrentFileInfo(): %d\n", zip.getZipError()); return false; } qDebug("FindSubtitlesWindow::uncompressZip: file '%s'", info.name.toUtf8().constData()); if (QFileInfo(info.name).suffix() != "nfo") sub_files.append(info.name); } qDebug("FindSubtitlesWindow::uncompressZip: list of subtitle files:"); for (int n=0; n < sub_files.count(); n++) { qDebug("FindSubtitlesWindow::uncompressZip: subtitle file %d '%s'", n, sub_files[n].toUtf8().constData()); } if (sub_files.count() == 1) { // If only one file, just extract it QString output_name = output_path +"/"+ preferred_output_name; if (extractFile(zip, sub_files[0], output_name )) { status->setText(tr("Subtitle saved as %1").arg(preferred_output_name)); emit subtitleDownloaded(output_name); } else { return false; } } else { // More than one file SubChooserDialog d(this); for (int n=0; n < sub_files.count(); n++) { d.addFile(sub_files[n]); } if (d.exec() == QDialog::Rejected) return false; QStringList files_to_extract = d.selectedFiles(); int extracted_count = 0; for (int n=0; n < files_to_extract.count(); n++) { QString file = files_to_extract[n]; bool ok = extractFile(zip, file, output_path +"/"+ file); qDebug("FindSubtitlesWindow::uncompressZip: extracted %s ok: %d", file.toUtf8().constData(), ok); if (ok) extracted_count++; } status->setText(tr("%1 subtitle(s) extracted","", extracted_count).arg(extracted_count)); if (extracted_count > 0) { emit subtitleDownloaded( output_path +"/"+ files_to_extract[0] ); } } zip.close(); return true; }
static void * mozload(const char * path, void *zip, struct cdir_entry *cdir_start, uint16_t cdir_entries) { #ifdef DEBUG struct timeval t0, t1; gettimeofday(&t0, 0); #endif struct cdir_entry *entry = find_cdir_entry(cdir_start, cdir_entries, path); struct local_file_header *file = (struct local_file_header *)((char *)zip + letoh32(entry->offset)); void * data = ((char *)&file->data) + letoh16(file->filename_size) + letoh16(file->extra_field_size); void * handle; if (extractLibs) { char fullpath[PATH_MAX]; snprintf(fullpath, PATH_MAX, "%s/%s", getenv("CACHE_PATH"), path); __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "resolved %s to %s", path, fullpath); extractFile(fullpath, entry, data); handle = __wrap_dlopen(fullpath, RTLD_LAZY); if (!handle) __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Couldn't load %s because %s", fullpath, __wrap_dlerror()); #ifdef DEBUG gettimeofday(&t1, 0); __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "%s: spent %d", path, (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) - (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)); #endif return handle; } size_t offset = letoh32(entry->offset) + sizeof(*file) + letoh16(file->filename_size) + letoh16(file->extra_field_size); bool skipLibCache = false; int fd = zip_fd; void * buf = NULL; uint32_t lib_size = letoh32(entry->uncompressed_size); int cache_fd = 0; if (letoh16(file->compression) == DEFLATE) { cache_fd = lookupLibCacheFd(path); fd = cache_fd; if (fd < 0) fd = createAshmem(lib_size, path); #ifdef DEBUG else __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Loading %s from cache", path); #endif if (fd < 0) { __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Couldn't open " ASHMEM_NAME_DEF ", Error %d, %s, bailing out", errno, strerror(errno)); return NULL; } buf = mmap(NULL, lib_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (buf == (void *)-1) { __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Couldn't mmap decompression buffer"); close(fd); return NULL; } offset = 0; if (cache_fd < 0) { extractLib(entry, data, buf); #ifdef ANDROID_ARM_LINKER /* We just extracted data that is going to be executed in the future. * We thus need to ensure Instruction and Data cache coherency. */ cacheflush((unsigned) buf, (unsigned) buf + entry->uncompressed_size, 0); #endif addLibCacheFd(path, fd, lib_size, buf); } // preload libxul, to avoid slowly demand-paging it if (!strcmp(path, "libxul.so")) madvise(buf, entry->uncompressed_size, MADV_WILLNEED); data = buf; } #ifdef DEBUG __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Loading %s with len %d (0x%08x) and offset %d (0x%08x)", path, lib_size, lib_size, offset, offset); #endif handle = moz_mapped_dlopen(path, RTLD_LAZY, fd, data, lib_size, offset); if (!handle) __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Couldn't load %s because %s", path, __wrap_dlerror()); if (buf) munmap(buf, lib_size); #ifdef DEBUG gettimeofday(&t1, 0); __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "%s: spent %d", path, (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) - (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)); #endif return handle; }
int main(int argc ,char **argv) { char *filename ="p"; int i = 0; if (argc < 2) { fprintf (stderr,"Usage: %s [-v] [-l] [-e file] _filename_\nWhere: -l: list files in update payload\n -e _file: extract file from update payload (use \"*\" for all files)\n", argv[0]); exit(10); } for (i = 1; i < argc -1; i++) { // This is super quick/dirty. You might want to rewrite with getopt, etc.. if (strcmp (argv[i], "-l") == 0) { g_list++;} if (strcmp (argv[i] , "-v") == 0) { g_verbose++;} if (strcmp (argv[i], "-e") == 0) { g_extract = argv[i+1]; i++;} } filename =argv[argc-1]; //unsigned char buf[4096]; int fd = open (filename, O_RDONLY); if (fd < 0) { perror (filename); exit(1);} #if 0 // Don't need this anymore :-) // Cheat - actually use 0x00 0x50 0x81 0xb4 as an anchor read (fd, buf, 4096); for (i = 0 ; i < 4096; i++) { if ((buf[i] == 0x00) && (buf[i+1] == 0x50) && (buf[i + 2] == 0x81) && (buf[i+3] == 0xb4)) { printf("Got anchor\n"); lseek(fd, i-26, SEEK_SET); break; } } if (i == 4096) { fprintf (stderr, "Unable to find anchor\n"); exit(5);} // Otherwise, we can start reading entries from here: #endif i = 0; int bytes_read = 1; struct entry *ent = alloca (sizeof(struct entry)); while(bytes_read ){ bytes_read = read(fd, (void *) ent, sizeof(struct entry)); if (bytes_read <= 0) { // fprintf (stderr, "Error reading next entry or EOF (this could be OK if it's the last entry, @TODO implement == 0 or fstat on filesize..)\n"); exit(1);} i+= bytes_read; uint32_t size = swap32(ent->fileSize); // Get Name (immediately after the entry) char *name = alloca(ntohs(ent->nameLen) + 1); bytes_read = read (fd , (void *) name, ntohs(ent->nameLen)); if (bytes_read <= 0) { fprintf (stderr, "Error reading Name. This is not ok\n"); exit(2);} i+= bytes_read; name[ntohs(ent->nameLen)] = '\0'; if (g_list){ if (g_verbose) { printf ("Entry @0x%d: UID: %d GID: %d Size: %d (0x%x) Namelen: %d Name: ", i, ntohs(ent->uid), ntohs(ent->gid), size, size, ntohs(ent->nameLen)); } printf ("%s\n", name);} // Get size (immediately after the name) uint32_t fileSize = swap32(ent->fileSize); if (fileSize) { char *file = malloc (fileSize); bytes_read = read (fd, (void *) file, fileSize); // Zero length file sizes are apparently ok.. if (bytes_read <= 0) { fprintf (stderr, "Error reading file. This is not ok \n"); exit(3);} i+= bytes_read; if (g_extract) { extractFile(file, name, fileSize, g_extract);} free(file); } } // Back to loop close(fd); }
static void * mozload(const char * path, void *zip, struct cdir_entry *cdir_start, uint16_t cdir_entries) { #ifdef DEBUG struct timeval t0, t1; gettimeofday(&t0, 0); #endif struct cdir_entry *entry = find_cdir_entry(cdir_start, cdir_entries, path); struct local_file_header *file = (struct local_file_header *)((char *)zip + letoh32(entry->offset)); void * data = ((char *)&file->data) + letoh16(file->filename_size) + letoh16(file->extra_field_size); void * handle; if (extractLibs) { char fullpath[PATH_MAX]; snprintf(fullpath, PATH_MAX, "%s/%s", getenv("CACHE_PATH"), path); __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "resolved %s to %s", path, fullpath); extractFile(fullpath, entry, data); handle = __wrap_dlopen(fullpath, RTLD_LAZY); if (!handle) __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Couldn't load %s because %s", fullpath, __wrap_dlerror()); #ifdef DEBUG gettimeofday(&t1, 0); __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "%s: spent %d", path, (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) - (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)); #endif return handle; } size_t offset = letoh32(entry->offset) + sizeof(*file) + letoh16(file->filename_size) + letoh16(file->extra_field_size); bool skipLibCache = false; int fd = zip_fd; void * buf = NULL; uint32_t lib_size = letoh32(entry->uncompressed_size); int cache_fd = 0; if (letoh16(file->compression) == DEFLATE) { cache_fd = lookupLibCacheFd(path); fd = cache_fd; if (fd < 0) { char fullpath[PATH_MAX]; snprintf(fullpath, PATH_MAX, "%s/%s", getenv("CACHE_PATH"), path); fd = open(fullpath, O_RDWR); struct stat status; if (stat(fullpath, &status) || status.st_size != lib_size || apk_mtime > status.st_mtime) { unlink(fullpath); fd = -1; } else { cache_fd = fd; addLibCacheFd(path, fd); } } if (fd < 0) fd = createAshmem(lib_size, path); #ifdef DEBUG else __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Loading %s from cache", path); #endif if (fd < 0) { __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Couldn't open " ASHMEM_NAME_DEF ", Error %d, %s, using a file", errno, strerror(errno)); char fullpath[PATH_MAX]; snprintf(fullpath, PATH_MAX, "%s/%s", getenv("CACHE_PATH"), path); fd = open(fullpath, O_RDWR | O_CREAT); if (fd < 0) { __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Couldn't create a file either, giving up"); return NULL; } // we'd like to use fallocate here, but it doesn't exist currently? if (lseek(fd, lib_size - 1, SEEK_SET) == (off_t) - 1) { __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "seeking file failed"); close(fd); return NULL; } if (write(fd, "", 1) != 1) { __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "writting one byte to the file failed"); close(fd); return NULL; } skipLibCache = true; addLibCacheFd(path, fd); } buf = mmap(NULL, lib_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (buf == (void *)-1) { __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Couldn't mmap decompression buffer"); close(fd); return NULL; } offset = 0; if (cache_fd < 0) { extractLib(entry, data, buf); #ifdef ANDROID_ARM_LINKER /* We just extracted data that is going to be executed in the future. * We thus need to ensure Instruction and Data cache coherency. */ cacheflush((unsigned) buf, (unsigned) buf + entry->uncompressed_size, 0); #endif if (!skipLibCache) addLibCacheFd(path, fd, lib_size, buf); } // preload libxul, to avoid slowly demand-paging it if (!strcmp(path, "libxul.so")) madvise(buf, entry->uncompressed_size, MADV_WILLNEED); data = buf; } #ifdef DEBUG __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Loading %s with len %d (0x%08x) and offset %d (0x%08x)", path, lib_size, lib_size, offset, offset); #endif handle = moz_mapped_dlopen(path, RTLD_LAZY, fd, data, lib_size, offset); if (!handle) __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Couldn't load %s because %s", path, __wrap_dlerror()); // if we're extracting the libs to disk and cache_fd is not valid then // keep this buffer around so it can be used to write to disk if (buf && (!extractLibs || cache_fd >= 0)) munmap(buf, lib_size); #ifdef DEBUG gettimeofday(&t1, 0); __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "%s: spent %d", path, (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) - (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)); #endif return handle; }
FAR_RTRN farExtract(char* archiveName, char** fileArgs, unsigned char numFileArgs) { FILE* archive; // the archive from which we are extracting unsigned int numFiles; // the number of files in archive charBuffer* filename; // the name of a file read from archive unsigned int fileSize; // the size of a file read from archive char** slashedFileArgs = NULL; /* holds the strings of fileArgs with a '/' * added to the end if it's not already * there. Used to compare directory paths */ unsigned int* usedArgs = NULL; /* holds the indicies of entries in fileArgs * and slashedFileArgs that caused * extractions */ unsigned int numUsedArgs = 0; // the number of elements in usedArgs archive = fopen(archiveName, "rb"); if(!archive) { return invalidArchiveNameError(); } else if(fread(&numFiles, sizeof(unsigned int), 1, archive) < 1) { fclose(archive); return corruptedArchiveError(); } if(numFileArgs > 0) { // initialize slashedFileArgs slashedFileArgs = malloc(sizeof(char*) * numFileArgs); for(unsigned int i = 0; i < numFileArgs; i++) { slashedFileArgs[i] = ensureSingleSlash(fileArgs[i]); } } filename = charBufferNew(); // move through archive, extracting all files that should be extracted for(unsigned int i = 0; i < numFiles; i++) { // get filename and fileSize if(getFileName(archive, filename) || fread(&fileSize, sizeof(unsigned int), 1, archive) < 1) { // failure fclose(archive); charBufferDelete(filename); if(slashedFileArgs) charArrayDelete(slashedFileArgs, numFileArgs); return corruptedArchiveError(); } // extract all files if we weren't passed any fileArgs if(numFileArgs == 0) { if(extractFile(archive, filename->str, fileSize) < 0) { // corrupted archive fclose(archive); charBufferDelete(filename); if(slashedFileArgs) charArrayDelete(slashedFileArgs, numFileArgs); return corruptedArchiveError(); } continue; } // compare filename to the arguments passed to 'x' int exactMatchIndex = isDuplicateFile(filename->str, fileArgs, numFileArgs); int directoryMatchIndex = isDirectoryMatch(filename->str, slashedFileArgs, numFileArgs); // remember which file argument caused this extraction, if one is // to occur if(exactMatchIndex >= 0) { usedArgs = uintArrayAdd(usedArgs, numUsedArgs, exactMatchIndex); numUsedArgs++; } else if(directoryMatchIndex >= 0) { usedArgs = uintArrayAdd(usedArgs, numUsedArgs, directoryMatchIndex); numUsedArgs++; } if(exactMatchIndex >= 0 || directoryMatchIndex >= 0) { if(extractFile(archive, filename->str, fileSize) < 0) { // corrupted archive fclose(archive); charBufferDelete(filename); if(slashedFileArgs) charArrayDelete(slashedFileArgs, numFileArgs); return corruptedArchiveError(); } } else { // move past file body without extracting for(unsigned int j = 0; j < fileSize; j++) { int c = fgetc(archive); if(c == EOF) { // unexpected EOF; corrupted archive fclose(archive); charBufferDelete(filename); if(slashedFileArgs) charArrayDelete(slashedFileArgs, numFileArgs); return corruptedArchiveError(); } } } } // print messages to stderr about unused filename arguments printUnusedArgs(fileArgs, numFileArgs, usedArgs, numUsedArgs); // clean-up fclose(archive); charBufferDelete(filename); if(slashedFileArgs) charArrayDelete(slashedFileArgs, numFileArgs); return SUCCESS; }
int main(int argc ,char **argv) { printf("sizeof(struct entry) = %li\n", sizeof(struct entry)); signal (2, showPos); char *filename ="p"; int i = 0; if (argc < 2) { fprintf (stderr,"Usage: %s [-v] [-l] [-e file] _filename_\nWhere: -l: list files in update payload\n -e _file: extract file from update payload (use \"*\" for all files)\n", argv[0]); exit(10); } for (i = 1; i < argc -1; i++) { // This is super quick/dirty. You might want to rewrite with getopt, etc.. if (strcmp (argv[i], "-l") == 0) { g_list++;} if (strcmp (argv[i] , "-v") == 0) { g_verbose++;} if (strcmp (argv[i], "-e") == 0) { g_extract = argv[i+1]; i++;} } filename =argv[argc-1]; //unsigned char buf[4096]; int fd = open (filename, O_RDONLY); if (fd < 0) { perror (filename); exit(1);} // 02/17/2016 - mmap struct stat stbuf; int rc = fstat(fd, &stbuf); char *mmapped = mmap(NULL, // void *addr, stbuf.st_size , // size_t len, PROT_READ, // int prot, MAP_PRIVATE, // int flags, fd, // int fd, 0); // off_t offset); if (mmapped == MAP_FAILED) { perror ("mmap"); exit(1);} i = 0; struct entry *ent = alloca (sizeof(struct entry)); while(pos + 3*sizeof(struct entry) < stbuf.st_size) { ent = (struct entry *) (mmapped + pos ); pos += sizeof(struct entry); if ((ent->usually_0x210_or_0x110 != 0x210 && ent->usually_0x210_or_0x110 != 0x110 && ent->usually_0x210_or_0x110 != 0x310) || ent->usually_0x00_00) { fprintf (stderr,"Corrupt entry (0x%x at pos %llu).. skipping\n", ent->usually_0x210_or_0x110,pos); int skipping = 1; while (skipping) { ent = (struct entry *) (mmapped + pos ) ; while (ent->usually_0x210_or_0x110 != 0x210 && ent->usually_0x210_or_0x110 != 0x110) { // #@$#$%$# POS ISN'T ALIGNED! pos ++; ent = (struct entry *) (mmapped + pos ) ; } // read rest of entry int nl = ntohs(ent->nameLen); if (ent->usually_0x00_00 || !nl) { // fprintf(stderr,"False positive.. skipping %d\n",pos); pos+=1; } else { skipping =0; pos += sizeof(struct entry); } } } uint32_t size = swap32(ent->fileSize); // fprintf(stdout," Here - ENT at pos %d: %x and 0 marker is %x namelen: %d, fileSize: %d\n", pos, ent->usually_0x210_or_0x110, ent->usually_0x00_00, ntohs(ent->nameLen), size); uint32_t nameLen = ntohs(ent->nameLen); // Get Name (immediately after the entry) // // 02/08/2016: Fixed this from alloca() - the Apple jumbo OTAs have so many files in them (THANKS GUYS!!) // that this would exceed the stack limits (could solve with ulimit -s, or also by using // a max buf size and reusing same buf, which would be a lot nicer) // Note to AAPL: Life would have been a lot nicer if the name would have been NULL terminated.. // What's another byte per every file in a huge file such as this? // char *name = (char *) (mmapped+pos); char *name = malloc (nameLen+1); strncpy(name, mmapped+pos , nameLen); name[nameLen] = '\0'; //printf("NAME IS %s\n", name); pos += ntohs(ent->nameLen); if (g_list){ if (g_verbose) { printf ("Entry @0x%d: UID: %d GID: %d Size: %d (0x%x) Namelen: %d Name: ", i, ntohs(ent->uid), ntohs(ent->gid), size, size, ntohs(ent->nameLen)); } printf ("%s\n", name);} // Get size (immediately after the name) uint32_t fileSize = swap32(ent->fileSize); if (fileSize) { if (g_extract) { extractFile(mmapped +pos, name, fileSize, g_extract);} pos +=fileSize; } free (name); } // Back to loop close(fd); }
int C3dsTool::Action() { if (m_eAction == kActionExtract) { if (!extractFile()) { printf("ERROR: extract file failed\n\n"); return 1; } } if (m_eAction == kActionCreate) { if (!createFile()) { printf("ERROR: create file failed\n\n"); return 1; } } if (m_eAction == kActionEncrypt) { if (!encryptFile()) { printf("ERROR: encrypt file failed\n\n"); return 1; } } if (m_eAction == kActionUncompress) { if (!uncompressFile()) { printf("ERROR: uncompress file failed\n\n"); return 1; } } if (m_eAction == kActionCompress) { if (!compressFile()) { printf("ERROR: compress file failed\n\n"); return 1; } } if (m_eAction == kActionTrim) { if (!trimFile()) { printf("ERROR: trim file failed\n\n"); return 1; } } if (m_eAction == kActionPad) { if (!padFile()) { printf("ERROR: pad file failed\n\n"); return 1; } } if (m_eAction == kActionDiff) { if (!diffFile()) { printf("ERROR: create patch file failed\n\n"); return 1; } } if (m_eAction == kActionPatch) { if (!patchFile()) { printf("ERROR: apply patch file failed\n\n"); return 1; } } if (m_eAction == kActionSample) { return sample(); } if (m_eAction == kActionHelp) { return Help(); } return 0; }
void PackageDialog::extractPackage() { QString s = QFileDialog::getOpenFileName( lastDir.isEmpty() ? QString(".") : lastDir, tr("Qucs Packages")+" (*.qucs);;"+ tr("Any File")+" (*)", this, 0, tr("Enter a Package File Name")); if(s.isEmpty()) { reject(); return; } QFileInfo Info(s); lastDir = Info.dirPath(true); // remember last directory QFile PkgFile(s); if(!PkgFile.open(QIODevice::ReadOnly)) { if(Info.extension().isEmpty()) s += ".qucs"; PkgFile.setName(s); if(!PkgFile.open(QIODevice::ReadOnly)) { MsgText->append(tr("ERROR: Cannot open package!")); ButtClose->setDisabled(false); return; } } QDataStream Stream(&PkgFile); QDir currDir = QucsSettings.QucsHomeDir; QString Version; Q_UINT16 Checksum; Q_UINT32 Code, Length; // First read and check header. QByteArray Content = PkgFile.readAll(); if(strncmp(Content.data(), "Qucs package ", 13) != 0) { MsgText->append(tr("ERROR: File contains wrong header!")); goto ErrorEnd; } Version = QString(Content.data()+13); if(!checkVersion(Version)) { MsgText->append(tr("ERROR: Wrong version number!")); goto ErrorEnd; } // checksum correct ? PkgFile.at(HEADER_LENGTH-2); Stream >> Checksum; *((Q_UINT16*)(Content.data()+HEADER_LENGTH-2)) = 0; if(Checksum != qChecksum(Content.data(), Content.size())) { MsgText->append(tr("ERROR: Checksum mismatch!")); goto ErrorEnd; } Content.resize(0); // dispose memory // work on all files and directories in the package for(;;) { if(PkgFile.atEnd()) break; Stream >> Code >> Length; switch(Code) { case CODE_DIR: if(extractDirectory(PkgFile, Length, currDir) > 0) break; goto ErrorEnd; case CODE_DIR_END: MsgText->append(tr("Leave directory \"%1\"").arg(currDir.absPath())); currDir.cdUp(); break; case CODE_FILE: if(extractFile(PkgFile, Length, currDir) > 0) break; goto ErrorEnd; case CODE_LIBRARY: if(extractLibrary(PkgFile, Length) > 0) break; goto ErrorEnd; default: MsgText->append(tr("ERROR: Package is corrupt!")); goto ErrorEnd; } } MsgText->append(" "); MsgText->append(tr("Successfully extracted package!")); ErrorEnd: MsgText->append(" "); ButtClose->setDisabled(false); PkgFile.close(); }
void processFile(struct Volume *vol, char* name, char* path, unsigned char *extbuf, BOOL pflag, BOOL qflag) { char *sepptr, *cdstr, *fullname, *filename; char *bigstr; FILE *tfile; adfToRootDir(vol); sepptr = strchr(name, '/'); if (sepptr==NULL) { extractFile(vol, name, path, extbuf, pflag, qflag); } else { /* the all-in-one string : to call system(), to find the filename, the convert dir sep char ... */ bigstr=(char*)malloc(strlen(MKDIR)+1+strlen(path)+1+strlen(name)+1); if (!bigstr) { fprintf(stderr,"processFile : malloc"); return; } /* to build to extract path */ if (strlen(path)>0) { sprintf(bigstr,"%s %s%c%s",MKDIR,path,DIRSEP,name); cdstr = bigstr+strlen(MKDIR)+1+strlen(path)+1; } else { sprintf(bigstr,"%s %s",MKDIR,name); cdstr = bigstr+strlen(MKDIR)+1; } /* the directory in which the file will be extracted */ fullname = bigstr+strlen(MKDIR)+1; /* finds the filename, and separates it from the path */ filename = strrchr(bigstr,'/')+1; filename[-1]='\0'; sepptr = cdstr; /* find the end of the first dir to create */ while(sepptr[0]!='/' && sepptr[0]!='\0') sepptr++; while(strlen(cdstr)>0) { if (sepptr[0]=='/') { /* not the last one */ sepptr[0]='\0'; if (adfChangeDir(vol,cdstr)!=RC_OK) return; tfile = fopen(fullname,"r"); /* the only portable way to test if the dir exists */ if (tfile==NULL) { /* does't exist : create it */ if (!pflag) system(bigstr); if (!qflag) printf("x - %s%c\n",fullname,DIRSEP); } else fclose(tfile); sepptr[0] = DIRSEP; /* converts the '/' to '/' or '\' */ cdstr = sepptr+1; /* next beginning of the next dir to create */ /* to find the end of the next dir */ sepptr++; while(sepptr[0]!='/' && sepptr[0]!='\0') sepptr++; } else { /* the last one */ if (adfChangeDir(vol,cdstr)!=RC_OK) return; tfile = fopen(fullname,"r"); if (tfile==NULL) { if (!pflag) system(bigstr); if (!qflag) printf("x - %s%c\n",fullname,DIRSEP); } else fclose(tfile); cdstr = cdstr+strlen(cdstr); /* at the end, ends the while loop */ } } extractFile(vol, filename, fullname, extbuf, pflag, qflag); free(bigstr); } }
void KTNEFMain::setupActions() { KStandardAction::quit( this, SLOT(close()), actionCollection() ); KAction *action = KStandardAction::keyBindings( this, SLOT(slotConfigureKeys()), actionCollection() ); action->setWhatsThis( i18nc( "@info:whatsthis", "You will be presented with a dialog where you can configure " "the application-wide shortcuts." ) ); KStandardAction::configureToolbars( this, SLOT(slotEditToolbars()), actionCollection() ); // File menu KStandardAction::open( this, SLOT(openFile()), actionCollection() ); // Action menu KAction *openAction = actionCollection()->addAction( "view_file" ); openAction->setText( i18nc( "@action:inmenu", "View" ) ); openAction->setIcon( KIcon( "document-open" ) ); connect( openAction, SIGNAL(triggered()), this, SLOT(viewFile()) ); KAction *openAsAction = actionCollection()->addAction( "view_file_as" ); openAsAction->setText( i18nc( "@action:inmenu", "View With..." ) ); connect( openAsAction, SIGNAL(triggered()), this, SLOT(viewFileAs()) ); KAction *extractAction = actionCollection()->addAction( "extract_file" ); extractAction->setText( i18nc( "@action:inmenu", "Extract" ) ); connect( extractAction, SIGNAL(triggered()), this, SLOT(extractFile()) ); KAction *extractToAction = actionCollection()->addAction( "extract_file_to" ); extractToAction->setText( i18nc( "@action:inmenu", "Extract To..." ) ); extractToAction->setIcon( KIcon( "archive-extract" ) ); connect( extractToAction, SIGNAL(triggered()), this, SLOT(extractFileTo()) ); KAction *extractAllToAction = actionCollection()->addAction( "extract_all_files" ); extractAllToAction->setText( i18nc( "@action:inmenu", "Extract All To..." ) ); extractAllToAction->setIcon( KIcon( "archive-extract" ) ); connect( extractAllToAction, SIGNAL(triggered()), this, SLOT(extractAllFiles()) ); KAction *filePropsAction = actionCollection()->addAction( "properties_file" ); filePropsAction->setText( i18nc( "@action:inmenu", "Properties" ) ); filePropsAction->setIcon( KIcon( "document-properties" ) ); connect( filePropsAction, SIGNAL(triggered()), this, SLOT(propertiesFile())); KAction *messPropsAction = actionCollection()->addAction( "msg_properties" ); messPropsAction->setText( i18nc( "@action:inmenu", "Message Properties" ) ); connect( messPropsAction, SIGNAL(triggered()), this, SLOT(slotShowMessageProperties()) ); KAction *messShowAction = actionCollection()->addAction( "msg_text" ); messShowAction->setText( i18nc( "@action:inmenu", "Show Message Text" ) ); messShowAction->setIcon( KIcon( "document-preview-archive" ) ); connect( messShowAction, SIGNAL(triggered()), this, SLOT(slotShowMessageText()) ); KAction *messSaveAction = actionCollection()->addAction( "msg_save" ); messSaveAction->setText( i18nc( "@action:inmenu", "Save Message Text As..." ) ); messSaveAction->setIcon( KIcon( "document-save" ) ); connect( messSaveAction, SIGNAL(triggered()), this, SLOT(slotSaveMessageText()) ); actionCollection()->action( "view_file" )->setEnabled( false ); actionCollection()->action( "view_file_as" )->setEnabled( false ); actionCollection()->action( "extract_file" )->setEnabled( false ); actionCollection()->action( "extract_file_to" )->setEnabled( false ); actionCollection()->action( "extract_all_files" )->setEnabled( false ); actionCollection()->action( "properties_file" )->setEnabled( false ); // Options menu KAction *defFolderAction = actionCollection()->addAction( "options_default_dir" ); defFolderAction->setText( i18nc( "@action:inmenu", "Default Folder..." ) ); defFolderAction->setIcon( KIcon( "folder-open" ) ); connect( defFolderAction, SIGNAL(triggered()), this, SLOT(optionDefaultDir()) ); }
int commandExtract(programOptions po) { // Open archive file char* archiveFilename = programOptionsGetArchiveName(po); FILE* archiveFile = fopen(archiveFilename, "r+"); // Check file existence if (archiveFile == NULL) { fprintf(stderr, "No such file or directory : %s\n", archiveFilename); return 1; } // Get file counts char** extractFiles = programOptionsGetFilesName(po); unsigned int extractFilesCount = programOptionsGetFilesCount(po); if (extractFilesCount == 0) { // Read file count unsigned int fileCount = 0; if (fread(&fileCount, sizeof(unsigned int), 1, archiveFile) <= 0) { perror("Error reading.\n"); return 1; } // Read headers fileHeader header; for (int i = 0; i < fileCount; ++i) { size_t readSize = fread(&header, sizeof(fileHeader), 1, archiveFile); if (readSize > 0) { // Verbose Log if (programOptionsGetVerbose(po)) printf("Extracting file %s from archive %s\n", header.name, archiveFilename); if (extractFile(archiveFile, header.name, header.name) != 0) { fprintf(stderr, "Error extracting %s.\n", header.name); return 1; } } else { // Close archive file fclose(archiveFile); return 1; } } } for (int i = 0; i < extractFilesCount; i++) { // Verbose Log if (programOptionsGetVerbose(po)) printf("Extracting file %s from archive %s\n", extractFiles[i], archiveFilename); if (extractFile(archiveFile, extractFiles[i], extractFiles[i]) != 0) { fprintf(stderr, "Error extracting %s.\n", extractFiles[i]); return 1; } } // Close archive file fflush(archiveFile); fclose(archiveFile); return 0; }