List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry getName
public String getName()
From source file:mj.ocraptor.extraction.tika.parser.iwork.IWorkPackageParser.java
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { ZipArchiveInputStream zip = new ZipArchiveInputStream(stream); ZipArchiveEntry entry = zip.getNextZipEntry(); TikaImageHelper helper = new TikaImageHelper(metadata); XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); IWORKDocumentType type = null;//from w ww. j av a 2 s .c o m try { while (entry != null) { // ------------------------------------------------ // // -- handle image files // ------------------------------------------------ // String entryExtension = null; try { entryExtension = FilenameUtils.getExtension(new File(entry.getName()).getName()); } catch (Exception e) { e.printStackTrace(); } if (entryExtension != null && FileType.isValidImageFileExtension(entryExtension)) { File imageFile = null; try { imageFile = TikaImageHelper.saveZipEntryToTemp(zip, entry); helper.addImage(imageFile); } catch (Exception e) { e.printStackTrace(); } finally { if (imageFile != null) { imageFile.delete(); } } } // ------------------------------------------------ // // -- // ------------------------------------------------ // if (!IWORK_CONTENT_ENTRIES.contains(entry.getName())) { entry = zip.getNextZipEntry(); continue; } InputStream entryStream = new BufferedInputStream(zip, 4096); entryStream.mark(4096); type = IWORKDocumentType.detectType(entryStream); entryStream.reset(); if (type != null) { ContentHandler contentHandler; switch (type) { case KEYNOTE: contentHandler = new KeynoteContentHandler(xhtml, metadata); break; case NUMBERS: contentHandler = new NumbersContentHandler(xhtml, metadata); break; case PAGES: contentHandler = new PagesContentHandler(xhtml, metadata); break; case ENCRYPTED: // We can't do anything for the file right now contentHandler = null; break; default: throw new TikaException("Unhandled iWorks file " + type); } metadata.add(Metadata.CONTENT_TYPE, type.getType().toString()); xhtml.startDocument(); if (contentHandler != null) { context.getSAXParser().parse(new CloseShieldInputStream(entryStream), new OfflineContentHandler(contentHandler)); } } entry = zip.getNextZipEntry(); } helper.addTextToHandler(xhtml); xhtml.endDocument(); } catch (Exception e) { // TODO: logging e.printStackTrace(); } finally { if (zip != null) { zip.close(); } if (helper != null) { helper.close(); } } }
From source file:com.warfrog.bitmapallthethings.BattEngine.java
private void unzipArchive() throws Exception { System.out.println("Unzipping " + getInputTarget()); final InputStream is = new FileInputStream(getInputTarget()); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is); ZipArchiveEntry entry = null; while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) { System.out.println("Extracting " + entry.getName()); final OutputStream out = new FileOutputStream(new File(getOutputDirectory(), entry.getName())); IOUtils.copy(in, out);/* w ww. ja va2 s .c o m*/ out.close(); } in.close(); }
From source file:com.fujitsu.dc.core.bar.BarFileInstaller.java
/** * bar?????./*from w w w . j a va 2 s . co m*/ * <ul> * <li>bar????</li> * <li>bar???????</li> * <li>TODO bar??????</li> * </ul>. * @param barFile ????bar?File * @returns bar? */ private long checkBarFileContents(File barFile) { // bar? checkBarFileSize(barFile); ZipFile zipFile = null; try { zipFile = new ZipFile(barFile, "UTF-8"); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); ZipArchiveEntry zae = null; long entryCount = 0; String entryName = null; try { long maxBarEntryFileSize = getMaxBarEntryFileSize(); // ?? Map<String, String> requiredBarFiles = setupBarFileOrder(); while (entries.hasMoreElements()) { zae = entries.nextElement(); entryName = zae.getName(); log.info("read: " + entryName); if (!zae.isDirectory()) { // ??????bar? entryCount++; // bar?? checkBarFileEntrySize(zae, entryName, maxBarEntryFileSize); // Box????? if (zae.getName().endsWith("/" + BarFileReadRunner.MANIFEST_JSON)) { checkAndReadManifest(entryName, zae, zipFile); } } // bar??????? if (!checkBarFileStructures(zae, requiredBarFiles)) { throw DcCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES.params(entryName); } } if (!requiredBarFiles.isEmpty()) { StringBuilder entryNames = new StringBuilder(); Object[] requiredFileNames = requiredBarFiles.keySet().toArray(); for (int i = 0; i < requiredFileNames.length; i++) { if (i > 0) { entryNames.append(" " + requiredFileNames[i]); } else { entryNames.append(requiredFileNames[i]); } } throw DcCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES.params(entryNames.toString()); } return entryCount; } catch (DcCoreException e) { throw e; } catch (Exception e) { log.info(e.getMessage(), e.fillInStackTrace()); throw DcCoreException.BarInstall.BAR_FILE_CANNOT_READ.params(entryName); } } catch (FileNotFoundException e) { throw DcCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params("barFile"); } catch (ZipException e) { throw DcCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage()); } catch (IOException e) { throw DcCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage()); } catch (DcCoreException e) { throw e; } catch (RuntimeException e) { throw DcCoreException.Server.UNKNOWN_ERROR; } finally { ZipFile.closeQuietly(zipFile); } }
From source file:io.personium.core.bar.BarFileInstaller.java
/** * bar?????.//from w ww . ja v a2 s . com * <ul> * <li>bar????</li> * <li>bar???????</li> * <li>TODO bar??????</li> * </ul>. * @param barFile ????bar?File * @returns bar? */ private long checkBarFileContents(File barFile) { // bar? checkBarFileSize(barFile); ZipFile zipFile = null; try { zipFile = new ZipFile(barFile, "UTF-8"); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); ZipArchiveEntry zae = null; long entryCount = 0; String entryName = null; try { long maxBarEntryFileSize = getMaxBarEntryFileSize(); // ?? Map<String, String> requiredBarFiles = setupBarFileOrder(); while (entries.hasMoreElements()) { zae = entries.nextElement(); entryName = zae.getName(); log.info("read: " + entryName); if (!zae.isDirectory()) { // ??????bar? entryCount++; // bar?? checkBarFileEntrySize(zae, entryName, maxBarEntryFileSize); // Box????? if (zae.getName().endsWith("/" + BarFileReadRunner.MANIFEST_JSON)) { checkAndReadManifest(entryName, zae, zipFile); } } // bar??????? if (!checkBarFileStructures(zae, requiredBarFiles)) { throw PersoniumCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES.params(entryName); } } if (!requiredBarFiles.isEmpty()) { StringBuilder entryNames = new StringBuilder(); Object[] requiredFileNames = requiredBarFiles.keySet().toArray(); for (int i = 0; i < requiredFileNames.length; i++) { if (i > 0) { entryNames.append(" " + requiredFileNames[i]); } else { entryNames.append(requiredFileNames[i]); } } throw PersoniumCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES .params(entryNames.toString()); } return entryCount; } catch (PersoniumCoreException e) { throw e; } catch (Exception e) { log.info(e.getMessage(), e.fillInStackTrace()); throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_READ.params(entryName); } } catch (FileNotFoundException e) { throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params("barFile"); } catch (ZipException e) { throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage()); } catch (IOException e) { throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage()); } catch (PersoniumCoreException e) { throw e; } catch (RuntimeException e) { throw PersoniumCoreException.Server.UNKNOWN_ERROR; } finally { ZipFile.closeQuietly(zipFile); } }
From source file:com.android.sdklib.internal.repository.ArchiveInstaller.java
/** * Unzips a zip file into the given destination directory. * * The archive file MUST have a unique "root" folder. * This root folder is skipped when unarchiving. *///from ww w . jav a2s. co m @SuppressWarnings("unchecked") private boolean unzipFolder(File archiveFile, long compressedSize, File unzipDestFolder, String description, ITaskMonitor monitor) { description += " (%1$d%%)"; ZipFile zipFile = null; try { zipFile = new ZipFile(archiveFile); // figure if we'll need to set the unix permissions boolean usingUnixPerm = SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_DARWIN || SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_LINUX; // To advance the percent and the progress bar, we don't know the number of // items left to unzip. However we know the size of the archive and the size of // each uncompressed item. The zip file format overhead is negligible so that's // a good approximation. long incStep = compressedSize / NUM_MONITOR_INC; long incTotal = 0; long incCurr = 0; int lastPercent = 0; byte[] buf = new byte[65536]; Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); String name = entry.getName(); // ZipFile entries should have forward slashes, but not all Zip // implementations can be expected to do that. name = name.replace('\\', '/'); // Zip entries are always packages in a top-level directory // (e.g. docs/index.html). However we want to use our top-level // directory so we drop the first segment of the path name. int pos = name.indexOf('/'); if (pos < 0 || pos == name.length() - 1) { continue; } else { name = name.substring(pos + 1); } File destFile = new File(unzipDestFolder, name); if (name.endsWith("/")) { //$NON-NLS-1$ // Create directory if it doesn't exist yet. This allows us to create // empty directories. if (!destFile.isDirectory() && !destFile.mkdirs()) { monitor.setResult("Failed to create temp directory %1$s", destFile.getPath()); return false; } continue; } else if (name.indexOf('/') != -1) { // Otherwise it's a file in a sub-directory. // Make sure the parent directory has been created. File parentDir = destFile.getParentFile(); if (!parentDir.isDirectory()) { if (!parentDir.mkdirs()) { monitor.setResult("Failed to create temp directory %1$s", parentDir.getPath()); return false; } } } FileOutputStream fos = null; try { fos = new FileOutputStream(destFile); int n; InputStream entryContent = zipFile.getInputStream(entry); while ((n = entryContent.read(buf)) != -1) { if (n > 0) { fos.write(buf, 0, n); } } } finally { if (fos != null) { fos.close(); } } // if needed set the permissions. if (usingUnixPerm && destFile.isFile()) { // get the mode and test if it contains the executable bit int mode = entry.getUnixMode(); if ((mode & 0111) != 0) { OsHelper.setExecutablePermission(destFile); } } // Increment progress bar to match. We update only between files. for (incTotal += entry.getCompressedSize(); incCurr < incTotal; incCurr += incStep) { monitor.incProgress(1); } int percent = (int) (100 * incTotal / compressedSize); if (percent != lastPercent) { monitor.setDescription(description, percent); lastPercent = percent; } if (monitor.isCancelRequested()) { return false; } } return true; } catch (IOException e) { monitor.setResult("Unzip failed: %1$s", e.getMessage()); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // pass } } } return false; }
From source file:cz.muni.fi.xklinec.zipstream.Mallory.java
/** * Returns true if given file name should be postponed (is modified in tampering process). * @param ze // ww w. j a v a 2 s . c o m * @return */ public boolean isPostponed(ZipArchiveEntry ze) { final String curName = ze.getName(); if (curName.startsWith(META_INF) || CLASSES.equalsIgnoreCase(curName) || ANDROID_MANIFEST.equalsIgnoreCase(curName) || RESOURCES.equalsIgnoreCase(curName) || curName.endsWith(".xml") || (ze.getMethod() == ZipArchiveOutputStream.DEFLATED && curName.endsWith(".png"))) { return true; } if (exclude != null && !exclude.isEmpty()) { for (String regex : exclude) { if (curName.matches(regex)) { return true; } } } return false; }
From source file:com.android.sdklib.internal.repository.Archive.java
/** * Unzips a zip file into the given destination directory. * * The archive file MUST have a unique "root" folder. This root folder is skipped when * unarchiving. However we return that root folder name to the caller, as it can be used * as a template to know what destination directory to use in the Add-on case. *//*from w ww.ja va 2 s . com*/ @SuppressWarnings("unchecked") private boolean unzipFolder(File archiveFile, long compressedSize, File unzipDestFolder, String description, String[] outZipRootFolder, ITaskMonitor monitor) { description += " (%1$d%%)"; ZipFile zipFile = null; try { zipFile = new ZipFile(archiveFile); // figure if we'll need to set the unix permission boolean usingUnixPerm = SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_DARWIN || SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_LINUX; // To advance the percent and the progress bar, we don't know the number of // items left to unzip. However we know the size of the archive and the size of // each uncompressed item. The zip file format overhead is negligible so that's // a good approximation. long incStep = compressedSize / NUM_MONITOR_INC; long incTotal = 0; long incCurr = 0; int lastPercent = 0; byte[] buf = new byte[65536]; Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); String name = entry.getName(); // ZipFile entries should have forward slashes, but not all Zip // implementations can be expected to do that. name = name.replace('\\', '/'); // Zip entries are always packages in a top-level directory // (e.g. docs/index.html). However we want to use our top-level // directory so we drop the first segment of the path name. int pos = name.indexOf('/'); if (pos < 0 || pos == name.length() - 1) { continue; } else { if (outZipRootFolder[0] == null && pos > 0) { outZipRootFolder[0] = name.substring(0, pos); } name = name.substring(pos + 1); } File destFile = new File(unzipDestFolder, name); if (name.endsWith("/")) { //$NON-NLS-1$ // Create directory if it doesn't exist yet. This allows us to create // empty directories. if (!destFile.isDirectory() && !destFile.mkdirs()) { monitor.setResult("Failed to create temp directory %1$s", destFile.getPath()); return false; } continue; } else if (name.indexOf('/') != -1) { // Otherwise it's a file in a sub-directory. // Make sure the parent directory has been created. File parentDir = destFile.getParentFile(); if (!parentDir.isDirectory()) { if (!parentDir.mkdirs()) { monitor.setResult("Failed to create temp directory %1$s", parentDir.getPath()); return false; } } } FileOutputStream fos = null; try { fos = new FileOutputStream(destFile); int n; InputStream entryContent = zipFile.getInputStream(entry); while ((n = entryContent.read(buf)) != -1) { if (n > 0) { fos.write(buf, 0, n); } } } finally { if (fos != null) { fos.close(); } } // if needed set the permissions. if (usingUnixPerm && destFile.isFile()) { // get the mode and test if it contains the executable bit int mode = entry.getUnixMode(); if ((mode & 0111) != 0) { setExecutablePermission(destFile); } } // Increment progress bar to match. We update only between files. for (incTotal += entry.getCompressedSize(); incCurr < incTotal; incCurr += incStep) { monitor.incProgress(1); } int percent = (int) (100 * incTotal / compressedSize); if (percent != lastPercent) { monitor.setDescription(description, percent); lastPercent = percent; } if (monitor.isCancelRequested()) { return false; } } return true; } catch (IOException e) { monitor.setResult("Unzip failed: %1$s", e.getMessage()); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // pass } } } return false; }
From source file:com.android.tools.idea.sdk.remote.internal.archives.ArchiveInstaller.java
/** * Unzips a zip file into the given destination directory. * <p/>// www . java2 s . c o m * The archive file MUST have a unique "root" folder. * This root folder is skipped when unarchiving. */ @SuppressWarnings("unchecked") @VisibleForTesting(visibility = Visibility.PRIVATE) protected boolean unzipFolder(ArchiveReplacement archiveInfo, File archiveFile, File unzipDestFolder, ITaskMonitor monitor) { Archive newArchive = archiveInfo.getNewArchive(); RemotePkgInfo pkg = newArchive.getParentPackage(); String pkgName = pkg.getShortDescription(); long compressedSize = newArchive.getSize(); ZipFile zipFile = null; try { zipFile = new ZipFile(archiveFile); // To advance the percent and the progress bar, we don't know the number of // items left to unzip. However we know the size of the archive and the size of // each uncompressed item. The zip file format overhead is negligible so that's // a good approximation. long incStep = compressedSize / NUM_MONITOR_INC; long incTotal = 0; long incCurr = 0; int lastPercent = 0; byte[] buf = new byte[65536]; Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); String name = entry.getName(); // ZipFile entries should have forward slashes, but not all Zip // implementations can be expected to do that. name = name.replace('\\', '/'); // Zip entries are always packages in a top-level directory (e.g. docs/index.html). int pos = name.indexOf('/'); if (pos == -1) { // All zip entries should have a root folder. // This zip entry seems located at the root of the zip. // Rather than ignore the file, just place it at the root. } else if (pos == name.length() - 1) { // This is a zip *directory* entry in the form dir/, so essentially // it's the root directory of the SDK. It's safe to ignore that one // since we want to use our own root directory and we'll recreate // root directories as needed. // A direct consequence is that if a malformed archive has multiple // root directories, their content will all be merged together. continue; } else { // This is the expected behavior: the zip entry is in the form root/file // or root/dir/. We want to use our top-level directory so we drop the // first segment of the path name. name = name.substring(pos + 1); } File destFile = new File(unzipDestFolder, name); if (name.endsWith("/")) { //$NON-NLS-1$ // Create directory if it doesn't exist yet. This allows us to create // empty directories. if (!mFileOp.isDirectory(destFile) && !mFileOp.mkdirs(destFile)) { monitor.logError("Failed to create directory %1$s", destFile.getPath()); return false; } continue; } else if (name.indexOf('/') != -1) { // Otherwise it's a file in a sub-directory. // Sanity check: since we're always unzipping in a fresh temp folder // the destination file shouldn't already exist. if (mFileOp.exists(destFile)) { monitor.logVerbose("Duplicate file found: %1$s", name); } // Make sure the parent directory has been created. File parentDir = destFile.getParentFile(); if (!mFileOp.isDirectory(parentDir)) { if (!mFileOp.mkdirs(parentDir)) { monitor.logError("Failed to create directory %1$s", parentDir.getPath()); return false; } } } FileOutputStream fos = null; long remains = entry.getSize(); try { fos = new FileOutputStream(destFile); // Java bug 4040920: do not rely on the input stream EOF and don't // try to read more than the entry's size. InputStream entryContent = zipFile.getInputStream(entry); int n; while (remains > 0 && (n = entryContent.read(buf, 0, (int) Math.min(remains, buf.length))) != -1) { remains -= n; if (n > 0) { fos.write(buf, 0, n); } } } catch (EOFException e) { monitor.logError("Error uncompressing file %s. Size: %d bytes, Unwritten: %d bytes.", entry.getName(), entry.getSize(), remains); throw e; } finally { if (fos != null) { fos.close(); } } pkg.postUnzipFileHook(newArchive, monitor, mFileOp, destFile, entry); // Increment progress bar to match. We update only between files. for (incTotal += entry.getCompressedSize(); incCurr < incTotal; incCurr += incStep) { monitor.incProgress(1); } int percent = (int) (100 * incTotal / compressedSize); if (percent != lastPercent) { monitor.setDescription("Unzipping %1$s (%2$d%%)", pkgName, percent); lastPercent = percent; } if (monitor.isCancelRequested()) { return false; } } return true; } catch (IOException e) { monitor.logError("Unzip failed: %1$s", e.getMessage()); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // pass } } } return false; }
From source file:com.android.sdklib.internal.repository.archives.ArchiveInstaller.java
/** * Unzips a zip file into the given destination directory. * * The archive file MUST have a unique "root" folder. * This root folder is skipped when unarchiving. */// w w w.ja va2 s . co m @SuppressWarnings("unchecked") @VisibleForTesting(visibility = Visibility.PRIVATE) protected boolean unzipFolder(ArchiveReplacement archiveInfo, File archiveFile, File unzipDestFolder, ITaskMonitor monitor) { Archive newArchive = archiveInfo.getNewArchive(); Package pkg = newArchive.getParentPackage(); String pkgName = pkg.getShortDescription(); long compressedSize = newArchive.getSize(); ZipFile zipFile = null; try { zipFile = new ZipFile(archiveFile); // To advance the percent and the progress bar, we don't know the number of // items left to unzip. However we know the size of the archive and the size of // each uncompressed item. The zip file format overhead is negligible so that's // a good approximation. long incStep = compressedSize / NUM_MONITOR_INC; long incTotal = 0; long incCurr = 0; int lastPercent = 0; byte[] buf = new byte[65536]; Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); String name = entry.getName(); // ZipFile entries should have forward slashes, but not all Zip // implementations can be expected to do that. name = name.replace('\\', '/'); // Zip entries are always packages in a top-level directory (e.g. docs/index.html). int pos = name.indexOf('/'); if (pos == -1) { // All zip entries should have a root folder. // This zip entry seems located at the root of the zip. // Rather than ignore the file, just place it at the root. } else if (pos == name.length() - 1) { // This is a zip *directory* entry in the form dir/, so essentially // it's the root directory of the SDK. It's safe to ignore that one // since we want to use our own root directory and we'll recreate // root directories as needed. // A direct consequence is that if a malformed archive has multiple // root directories, their content will all be merged together. continue; } else { // This is the expected behavior: the zip entry is in the form root/file // or root/dir/. We want to use our top-level directory so we drop the // first segment of the path name. name = name.substring(pos + 1); } File destFile = new File(unzipDestFolder, name); if (name.endsWith("/")) { //$NON-NLS-1$ // Create directory if it doesn't exist yet. This allows us to create // empty directories. if (!mFileOp.isDirectory(destFile) && !mFileOp.mkdirs(destFile)) { monitor.logError("Failed to create directory %1$s", destFile.getPath()); return false; } continue; } else if (name.indexOf('/') != -1) { // Otherwise it's a file in a sub-directory. // Sanity check: since we're always unzipping in a fresh temp folder // the destination file shouldn't already exist. if (mFileOp.exists(destFile)) { monitor.logVerbose("Duplicate file found: %1$s", name); } // Make sure the parent directory has been created. File parentDir = destFile.getParentFile(); if (!mFileOp.isDirectory(parentDir)) { if (!mFileOp.mkdirs(parentDir)) { monitor.logError("Failed to create directory %1$s", parentDir.getPath()); return false; } } } FileOutputStream fos = null; long remains = entry.getSize(); try { fos = new FileOutputStream(destFile); // Java bug 4040920: do not rely on the input stream EOF and don't // try to read more than the entry's size. InputStream entryContent = zipFile.getInputStream(entry); int n; while (remains > 0 && (n = entryContent.read(buf, 0, (int) Math.min(remains, buf.length))) != -1) { remains -= n; if (n > 0) { fos.write(buf, 0, n); } } } catch (EOFException e) { monitor.logError("Error uncompressing file %s. Size: %d bytes, Unwritten: %d bytes.", entry.getName(), entry.getSize(), remains); throw e; } finally { if (fos != null) { fos.close(); } } pkg.postUnzipFileHook(newArchive, monitor, mFileOp, destFile, entry); // Increment progress bar to match. We update only between files. for (incTotal += entry.getCompressedSize(); incCurr < incTotal; incCurr += incStep) { monitor.incProgress(1); } int percent = (int) (100 * incTotal / compressedSize); if (percent != lastPercent) { monitor.setDescription("Unzipping %1$s (%2$d%%)", pkgName, percent); lastPercent = percent; } if (monitor.isCancelRequested()) { return false; } } return true; } catch (IOException e) { monitor.logError("Unzip failed: %1$s", e.getMessage()); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // pass } } } return false; }
From source file:cz.muni.fi.xklinec.zipstream.Mallory.java
/** * Reads tampered APK file (zip object is prepared for this file prior * this function call).// ww w .j a v a2 s .co m * * If a) file differs or b) file is new, it is added to the output zip stream. * * Method also handles padding to a given size. Attribute padlen is used, * if addPadding is true, padlen bytes are distributed to {new, modiffied} * files in extra field in central directory. * * @param addPadding * @throws IOException */ public void mergeTamperedApk(boolean addPadding, boolean forReal) throws IOException { // Read the tampered archive ZipArchiveEntry ze = zip.getNextZipEntry(); Set<String> files = new HashSet<String>(); long padlenLeft = padlen; while (ze != null) { // Data for entry byte[] byteData = Utils.readAll(zip); byte[] deflData = new byte[0]; int defl = 0; long padd2add = -1; if (addPadding) { padd2add = compPadding(padlenLeft); } // If method is deflated, get the raw data (compress again). if (ze.getMethod() == ZipArchiveOutputStream.DEFLATED) { def.reset(); def.setInput(byteData); def.finish(); byte[] deflDataTmp = new byte[byteData.length * 2]; defl = def.deflate(deflDataTmp); deflData = new byte[defl]; System.arraycopy(deflDataTmp, 0, deflData, 0, defl); } final String curName = ze.getName(); PostponedEntry al = new PostponedEntry(ze, byteData, deflData); files.add(curName); // Compare posponed entry with entry in previous if (alMap.containsKey(curName) == false || alMap.get(curName) == null) { // This element is not in the archive at all! // Add it to the zop if (!quiet) System.err.println( "Detected newly added file [" + curName + "] written prior dump: " + zop.getWritten()); // Apply padding if (padd2add > 0) { addExtraPadding(al.ze, (int) padd2add); padlenLeft -= padd2add; if (!quiet) System.err.println(" Added padding: " + padd2add + "; left: " + padlenLeft); } al.dump(zop, recomputeCrc); } else { // Check the entry against the old entry hash // All files are read linary from the new APK file // thus it will be put to the archive in the right order. PostponedEntry oldEntry = alMap.get(curName); boolean wasPostponed = isPostponed(oldEntry.ze); if ((oldEntry.hashByte == null && al.hashByte != null) || (oldEntry.hashByte != null && oldEntry.hashByte.equals(al.hashByte) == false) || (defl > 0 && (oldEntry.hashDefl == null && al.hashDefl != null)) || (defl > 0 && (oldEntry.hashDefl != null && oldEntry.hashDefl.equals(al.hashDefl) == false))) { // Element was changed, add it to the zop // if (!quiet) { System.err.println( "Detected modified file [" + curName + "] written prior dump: " + zop.getWritten()); System.err.println(" t1=" + oldEntry.hashByte.equals(al.hashByte) + "; t2=" + oldEntry.hashDefl.equals(al.hashDefl)); } if (!wasPostponed && !quiet) { System.err.println( " Warning: This file was already sent to the victim (file was not postponed) !!!"); } // Apply padding if (padd2add > 0) { addExtraPadding(al.ze, (int) padd2add); padlenLeft -= padd2add; if (!quiet) System.err.println(" Added padding: " + padd2add + "; left: " + padlenLeft); } al.dump(zop, recomputeCrc); } else if (wasPostponed) { // File was not modified but is one of the postponed files, thus has to // be flushed also. if (!quiet) System.err.println("Postponed file not modified [" + curName + "] written prior dump: " + zop.getWritten()); // Apply padding if (padd2add > 0) { addExtraPadding(al.ze, (int) padd2add); padlenLeft -= padd2add; if (!quiet) System.err.println(" Added padding: " + padd2add + "; left: " + padlenLeft); } al.dump(zop, recomputeCrc); } } ze = zip.getNextZipEntry(); } // Check if some file from the original file is not in the modified file. if (forReal && !quiet) { // Iterate over map files and lookup the same among modified files. for (String oldFile : alMap.keySet()) { if (files.contains(oldFile) == false) { if (sentFiles.contains(oldFile)) { System.err.println("Warning: File from original file [" + oldFile + "] was not found in tampered file and file was already sent!!!"); } else { System.err.println("Warning: File from original file [" + oldFile + "] was not found in tampered file!"); } } } } // If omitMissing is specified, remove ZIP entries from ZOP that are not present // in tampered file (no signature for them). if (omitMissing) { List<ZipArchiveEntry> entries = zop.getEntries(); // Iterate over map files and lookup the same among modified files. for (String oldFile : alMap.keySet()) { if (files.contains(oldFile) == false) { if (!sentFiles.contains(oldFile)) { continue; } // Remove from ZOP entries list - will be not added to central directory if (alMap.containsKey(oldFile) == false) { if (!quiet) { System.err.println("Warning: File from original file [" + oldFile + "] was not found in tampered file and file was already sent, no ZIP entry!!!"); } continue; } boolean deleted = false; // Delete file based on filename (do not rely on .equals()). Iterator<ZipArchiveEntry> it = entries.iterator(); while (it.hasNext()) { ZipArchiveEntry tmpZe = it.next(); if (tmpZe.getName().equals(oldFile)) { it.remove(); deleted = true; break; } } if (!quiet) { System.err.println( "Removed [" + deleted + "] File [" + oldFile + "] remove from zip entries."); } } } } if (!quiet && addPadding && padlenLeft > 0) { System.err.println("Warning! Not enough modified files to add required padding. Left: " + padlenLeft + "/" + padlen); } }