Skip to content

Ghidra is a software reverse engineering (SRE) framework

GT-3001 (#789) fix RestoreTask to safely extract files from zip.

dev7473686c0171c9200b
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/archive/ArchivePlugin.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/archive/ArchivePlugin.java
index a8d486d338..1bbf864a44 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/archive/ArchivePlugin.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/archive/ArchivePlugin.java
@@ -15,7 +15,9 @@
*/
package ghidra.app.plugin.core.archive;
-import java.io.*;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.jar.JarEntry;
@@ -26,14 +28,24 @@ import docking.ActionContext;
import docking.action.DockingAction;
import docking.action.MenuData;
import ghidra.app.CorePluginPackage;
-import ghidra.framework.main.*;
-import ghidra.framework.model.*;
-import ghidra.framework.plugintool.*;
-import ghidra.framework.plugintool.util.*;
+import ghidra.framework.main.AppInfo;
+import ghidra.framework.main.FrontEndOnly;
+import ghidra.framework.main.FrontEndTool;
+import ghidra.framework.model.Project;
+import ghidra.framework.model.ProjectListener;
+import ghidra.framework.model.ProjectLocator;
+import ghidra.framework.model.ProjectManager;
+import ghidra.framework.plugintool.Plugin;
+import ghidra.framework.plugintool.PluginInfo;
+import ghidra.framework.plugintool.PluginTool;
+import ghidra.framework.plugintool.util.PluginStatus;
+import ghidra.framework.plugintool.util.ToolConstants;
import ghidra.framework.preferences.Preferences;
import ghidra.util.HelpLocation;
import ghidra.util.Msg;
-import ghidra.util.task.*;
+import ghidra.util.task.Task;
+import ghidra.util.task.TaskLauncher;
+import ghidra.util.task.TaskListener;
/**
* The archive plugin provides menu action from the front end allowing the
@@ -197,7 +209,7 @@ public class ArchivePlugin extends Plugin implements FrontEndOnly, ProjectListen
Project activeProject = AppInfo.getActiveProject();
if (activeProject.getToolManager().getRunningTools().length > 0) {
Msg.showInfo(getClass(), tool.getToolFrame(), TOOL_RUNNING_TITLE,
- "You must close running tools before starting the archive process.");
+ "You must close running tools before starting the archive process.");
return;
}
@@ -376,8 +388,7 @@ public class ArchivePlugin extends Plugin implements FrontEndOnly, ProjectListen
void cleanupRestoredProject(ProjectLocator projectLocator) {
- Project project = tool.getProject();
- ProjectManager projectManager = project.getProjectManager();
+ ProjectManager projectManager = tool.getProjectManager();
// delete the project at the given project location
if (!projectManager.deleteProject(projectLocator)) {
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/archive/RestoreTask.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/archive/RestoreTask.java
index 63ed60f4f9..634dc7813d 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/archive/RestoreTask.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/archive/RestoreTask.java
@@ -15,160 +15,179 @@
*/
package ghidra.app.plugin.core.archive;
-import java.io.*;
+import java.io.File;
+import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
-import java.util.jar.JarInputStream;
+import java.util.Set;
import javax.swing.SwingUtilities;
-import generic.io.JarReader;
+import org.apache.commons.io.FilenameUtils;
+
+import ghidra.formats.gfilesystem.AbstractFileExtractorTask;
+import ghidra.formats.gfilesystem.FSRL;
+import ghidra.formats.gfilesystem.FSUtilities;
+import ghidra.formats.gfilesystem.FileSystemService;
+import ghidra.formats.gfilesystem.GFile;
+import ghidra.formats.gfilesystem.GFileSystem;
import ghidra.framework.main.FrontEndTool;
-import ghidra.framework.model.*;
+import ghidra.framework.model.Project;
+import ghidra.framework.model.ProjectLocator;
+import ghidra.framework.model.ProjectManager;
+import ghidra.framework.protocol.ghidra.GhidraURL;
import ghidra.util.Msg;
import ghidra.util.NotOwnerException;
-import ghidra.util.exception.DuplicateFileException;
-import ghidra.util.task.Task;
+import ghidra.util.exception.CancelledException;
import ghidra.util.task.TaskMonitor;
-import utilities.util.FileUtilities;
-class RestoreTask extends Task {
+/**
+ * Task that restores a Ghidra Project Archive file (a zip file with a .gar extension)
+ *
+ */
+class RestoreTask extends AbstractFileExtractorTask {
- private File jarFile;
+ // files that should always be skipped when extracting the zip file
+ private static final Set<String> FILES_TO_SKIP = Set.of( //
+ "/" + ArchivePlugin.JAR_VERSION_TAG.toLowerCase(),
+ "/" + ArchivePlugin.PROJECT_PROPERTY_FILE.toLowerCase(),
+ "/" + ArchivePlugin.OLD_PROJECT_SAVE_DIR.toLowerCase(),
+ "/" + ArchivePlugin.OLD_PROJECT_GROUPS_DIR.toLowerCase());
+
+ private File projectArchiveFile;
private ProjectLocator projectLocator;
private ArchivePlugin plugin;
- private String message;
+ private File projectFile;
+ private File projectDir;
- RestoreTask(ProjectLocator projectLocator, File inJarFile, ArchivePlugin plugin) {
- super("Restoring Project: " + projectLocator.getName(), true, false, true);
+ RestoreTask(ProjectLocator projectLocator, File projectArchiveFile, ArchivePlugin plugin) {
+ super("Restoring Project: " + projectLocator.getName(), true, false, true,
+ projectLocator.getProjectDir());
this.projectLocator = projectLocator;
- jarFile = inJarFile;
+ this.projectArchiveFile = projectArchiveFile;
this.plugin = plugin;
+
+ this.projectFile = projectLocator.getMarkerFile();
+ this.projectDir = projectLocator.getProjectDir();
+
}
@Override
- public void run(TaskMonitor monitor) {
- boolean ok = false;
- try {
- unjarArchive(monitor);
- ok = true;
+ public void run(TaskMonitor monitor) throws CancelledException {
+ FileSystemService fsService = FileSystemService.getInstance();
+ String locInfo = "\"" + projectLocator.toString() + "\" from \"" +
+ projectArchiveFile.getAbsolutePath() + "\"";
+
+ if (projectFile.exists() || projectDir.exists()) {
+ Msg.showError(this, null, "Restore Archive Error",
+ "Project already exists at: " + projectDir);
+ return;
}
- catch (Exception e) {
- Msg.showError(this, null, null, null, e);
- message = message + " failed.";
+
+ FSRL archiveFSRL = fsService.getLocalFSRL(projectArchiveFile);
+ try (GFileSystem fs = fsService.openFileSystemContainer(archiveFSRL, monitor)) {
+ verifyArchive(fs, monitor);
+ startExtract(fs, null, monitor);
+ verifyRestoredProject();
+ openRestoredProject();
+ Msg.info(this, "Restore Archive: " + locInfo + " succeeded.");
}
- message =
- "\"" + projectLocator.toString() + "\" from \"" + jarFile.getAbsolutePath() + "\"";
- if (monitor.isCancelled()) {
- message += " was cancelled by user.";
- // put everything back the way it was...
+ catch (CancelledException ce) {
plugin.cleanupRestoredProject(projectLocator);
+ Msg.info(this, "Restore Archive: " + locInfo + " was cancelled by user.");
}
- else {
- message += ((ok) ? " succeeded." : " failed.");
- final boolean success = ok;
- Runnable r = () -> restoreCompleted(success);
- try {
- SwingUtilities.invokeAndWait(r);
- }
- catch (InterruptedException e1) {
- }
- catch (InvocationTargetException e1) {
- }
+ catch (Throwable e) {
+ plugin.cleanupRestoredProject(projectLocator);
+ String eMsg = (e.getMessage() != null) ? ":\n\n" + e.getMessage() : "";
+ Msg.showError(this, null, "Restore Archive Failed",
+ "An error occurred when restoring the project archive\n " + projectArchiveFile +
+ " to \n " + projectDir + eMsg,
+ e);
+ Msg.info(this, "Restore Archive: " + locInfo + " failed.");
}
+ }
- Msg.info(this, "Restore Archive: " + message);
+ private void verifyRestoredProject() throws IOException {
+ if (!projectFile.createNewFile()) {
+ throw new IOException("Couldn't create file " + projectFile.getAbsolutePath());
+ }
}
- /**
- * Unjar the archive file.
- * @param monitor
- * @throws IOException
- */
- private void unjarArchive(TaskMonitor monitor) throws IOException {
- JarInputStream jarIn = new JarInputStream(new FileInputStream(jarFile));
- JarReader reader = new JarReader(jarIn);
-
- // position input stream to the entry after the .gpr entry since
- // we don't want to create that file
- jarIn.getNextJarEntry();
-
- // the next entry should be JAR_FORMAT
- jarIn.getNextJarEntry();
-
- File projectFile = projectLocator.getMarkerFile();
- File projectDir = projectLocator.getProjectDir();
- if (projectFile.exists()) {
- throw new DuplicateFileException("Project already exists: " + projectFile);
+ private void verifyArchive(GFileSystem fs, TaskMonitor monitor) throws IOException {
+ if (!fs.getFSRL().getProtocol().equals("zip")) {
+ throw new IOException("Not a zip file: " + fs.getFSRL());
}
- if (projectDir.exists()) {
- throw new DuplicateFileException("Project already exists: " + projectDir);
+ GFile magicFile = fs.lookup("/" + ArchivePlugin.JAR_VERSION_TAG);
+ if (magicFile == null) {
+ throw new IOException("Missing Ghidra Project Archive (.gar) marker file");
}
+ }
- reader.createRecursively(projectDir.getAbsolutePath() + File.separator, monitor);
-
- jarIn.close();
- if (monitor.isCancelled()) {
- return;
+ @Override
+ protected void processFile(GFile file, File destFSFile, TaskMonitor monitor)
+ throws IOException, CancelledException {
+ if (!shouldSkip(file)) {
+ super.processFile(file, destFSFile, monitor);
}
+ }
- // Remove unwanted project properties file - will get re-created when project is opened
- File file = new File(projectDir, ArchivePlugin.PROJECT_PROPERTY_FILE);
- file.delete();
-
- // Remove unwanted project state file
- file = new File(projectDir, ArchivePlugin.PROJECT_STATE_FILE);
- file.delete();
-
- // Remove unwanted project state save directory
- file = new File(projectDir, ArchivePlugin.OLD_PROJECT_SAVE_DIR);
- FileUtilities.deleteDir(file);
-
- // Remove unwanted project groups directory
- file = new File(projectDir, ArchivePlugin.OLD_PROJECT_GROUPS_DIR);
- FileUtilities.deleteDir(file);
-
- // Remove unwanted folder property files
- removeOldFolderProperties(projectDir);
-
- // create the .gpr file for the new project
-
- if (!projectFile.createNewFile()) {
- throw new IOException("Couldn't create file " + projectFile.getAbsolutePath());
+ @Override
+ protected void processDirectory(GFile srcGFileDirectory, File destDirectory,
+ TaskMonitor monitor) throws IOException, CancelledException {
+ if (!shouldSkip(srcGFileDirectory)) {
+ super.processDirectory(srcGFileDirectory, destDirectory, monitor);
}
}
- private static void removeOldFolderProperties(File dir) {
-
- File f = new File(dir, ArchivePlugin.OLD_FOLDER_PROPERTIES_FILE);
- f.delete();
+ @Override
+ protected String mapSourceFilenameToDest(GFile srcFile) throws IOException {
+ String filename = srcFile.getName();
+ if (!FSUtilities.getSafeFilename(filename).equals(filename)) {
+ throw new IOException("Bad filename in archive: \"" + filename + "\"");
+ }
+ return filename;
+ }
- File[] files = dir.listFiles();
- for (File file : files) {
- if (file.isDirectory()) {
- removeOldFolderProperties(file);
- }
+ private boolean shouldSkip(GFile file) {
+ String path = file.getPath().toLowerCase();
+ if (FILES_TO_SKIP.contains(path)) {
+ return true;
}
+ if (ArchivePlugin.OLD_FOLDER_PROPERTIES_FILE.equalsIgnoreCase(file.getName())) {
+ // ignore this file in any directory in the archive
+ return true;
+ }
+ String ext = "." + FilenameUtils.getExtension(file.getName());
+ if (GhidraURL.MARKER_FILE_EXTENSION.equalsIgnoreCase(ext)) {
+ // ignore .gpr marker files, any file name
+ return true;
+ }
+ return false;
}
- private void restoreCompleted(boolean ok) {
- if (ok) {
- ProjectManager pm = plugin.getTool().getProjectManager();
- try {
- Project project = pm.openProject(projectLocator, true, true);
- pm.rememberProject(projectLocator);
- FrontEndTool tool = (FrontEndTool) plugin.getTool();
- tool.setActiveProject(project);
- }
- catch (NotOwnerException e) {
- // can't happen since resetOwner is true
- }
- catch (Exception e) {
- message = "Error opening project: " + projectLocator.getName();
- Msg.showError(this, null, null, null, e);
- }
+ private void openRestoredProject() {
+ try {
+ SwingUtilities.invokeAndWait(() -> {
+ ProjectManager pm = plugin.getTool().getProjectManager();
+ try {
+ Project project = pm.openProject(projectLocator, true, true);
+ pm.rememberProject(projectLocator);
+ FrontEndTool tool = (FrontEndTool) plugin.getTool();
+ tool.setActiveProject(project);
+ }
+ catch (NotOwnerException e) {
+ // can't happen since resetOwner is true
+ }
+ catch (Exception e) {
+ Msg.info(this,
+ "Restore Archive: Error opening project: " + projectLocator.getName());
+
+ Msg.showError(this, null, "Restore Archive Error",
+ "Failed to open newly restored project", e);
+ }
+ });
}
- else {
- plugin.cleanupRestoredProject(projectLocator);
+ catch (InvocationTargetException | InterruptedException e) {
+ // ignore
}
}
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/AbstractFileExtractorTask.java b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/AbstractFileExtractorTask.java
new file mode 100644
index 0000000000..1915f1438a
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/AbstractFileExtractorTask.java
@@ -0,0 +1,235 @@
+package ghidra.formats.gfilesystem;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import ghidra.util.Msg;
+import ghidra.util.exception.CancelledException;
+import ghidra.util.exception.CryptoException;
+import ghidra.util.exception.IOCancelledException;
+import ghidra.util.task.Task;
+import ghidra.util.task.TaskMonitor;
+import utilities.util.FileUtilities;
+
+/**
+ * Common base class for tasks that need to extract files from a GFileSystem location.
+ * <p>
+ *
+ */
+public abstract class AbstractFileExtractorTask extends Task {
+
+ protected GFileSystem fs;
+ protected File rootOutputDirectory;
+ private int totalFilesExportedCount;
+ private int totalDirsExportedCount;
+ private long totalBytesExportedCount;
+
+ /**
+ * See {@link Task#Task(String, boolean, boolean, boolean)}.
+ *
+ * @param title See {@link Task#Task(String, boolean, boolean, boolean)}
+ * @param canCancel See {@link Task#Task(String, boolean, boolean, boolean)}
+ * @param hasProgress See {@link Task#Task(String, boolean, boolean, boolean)}
+ * @param isModal See {@link Task#Task(String, boolean, boolean, boolean)}
+ * @param rootOutputDir base directory where files will be extracted to
+ */
+ public AbstractFileExtractorTask(String title, boolean canCancel, boolean hasProgress,
+ boolean isModal, File rootOutputDir) {
+ super(title, canCancel, hasProgress, isModal);
+ this.rootOutputDirectory = rootOutputDir;
+ }
+
+ /**
+ * Starts the file extraction process.
+ *
+ * @param fs the {@link GFileSystem} that holds the files
+ * @param srcDir the starting directory to extract, if {@code null}, start at root of file system
+ * @param rootOutputDirectory the destination directory
+ * @param monitor {@link TaskMonitor} that will be updated with progress and checked for cancel
+ * @throws CancelledException
+ * @throws IOException
+ */
+ protected void startExtract(GFileSystem fs, GFile srcDir, TaskMonitor monitor)
+ throws CancelledException, IOException {
+ this.fs = fs;
+
+ if (srcDir == null) {
+ srcDir = fs.lookup(null);
+ }
+ processDirectory(srcDir, rootOutputDirectory, monitor);
+ }
+
+ /**
+ * Extract the contents of a directory in a {@link GFileSystem} into a local file system
+ * directory.
+ * <p>
+ * The destination directory is created if not present.
+ *
+ * @param srcGFileDirectory if null, directory is filesystem root
+ * @param destDirectory destination / output directory
+ * @param monitor {@link TaskMonitor} to watch and update with progress
+ * @throws IOException if IO problem.
+ * @throws CancelledException
+ */
+ protected void processDirectory(GFile srcGFileDirectory, File destDirectory,
+ TaskMonitor monitor) throws IOException, CancelledException {
+
+ if (isSpecialDirectory(srcGFileDirectory)) {
+ return;
+ }
+
+ if (!FileUtilities.isPathContainedWithin(rootOutputDirectory, destDirectory)) {
+ // This can happen with hostile relative paths supplied by the data in the src filesystem.
+ String srcPath = (srcGFileDirectory != null) ? srcGFileDirectory.getPath() : "/";
+ throw new IOException("Extracted directory " + srcPath + " [" + destDirectory +
+ "] would be outside of root destination directory: " + rootOutputDirectory);
+ }
+
+ if (!destDirectory.isDirectory() && !destDirectory.mkdirs()) {
+ throw new IOException("Failed to create destination directory " + destDirectory);
+ }
+ totalDirsExportedCount++;
+
+ for (GFile srcFile : fs.getListing(srcGFileDirectory)) {
+ monitor.checkCanceled();
+
+ String destFname = mapSourceFilenameToDest(srcFile);
+
+ File destFSFile = new File(destDirectory, destFname);
+ if (srcFile.isDirectory()) {
+ processDirectory(srcFile, destFSFile, monitor);
+ }
+ else {
+ processFile(srcFile, destFSFile, monitor);
+ }
+ }
+ }
+
+ protected void processFile(GFile srcFile, File destFSFile, TaskMonitor monitor)
+ throws IOException, CancelledException {
+ try {
+ if (!FileUtilities.isPathContainedWithin(this.rootOutputDirectory, destFSFile)) {
+ throw new IOException("Extracted file " + srcFile.getPath() + " [" + destFSFile +
+ "] would be outside of root destination directory: " +
+ this.rootOutputDirectory);
+ }
+ extractFile(srcFile, destFSFile.getCanonicalFile(), monitor);
+ }
+ catch (CancelledException | IOCancelledException e) {
+ throw e;
+ }
+ catch (Exception e) {
+ if (!handleUnexpectedException(srcFile, e)) {
+ throw e;
+ }
+ }
+ }
+
+ /**
+ * Maps the untrusted, potentially hostile, filename of the source file to a name
+ * that is suitable to be used to create a file on the user's local file system.
+ * <p>
+ * NOTE: This base implementation converts relative directory names to spelled-out
+ * versions of that directory, eg. "." becomes "dot".
+ * <p>
+ * If you wish to modify this behavior, override this method and return different
+ * mappings.
+ *
+ * @param srcFile source file
+ * @return String name of the source file, possibly modified to be safer
+ * @throws IOException thrown if name is not mappable and the extract process should stop
+ */
+ protected String mapSourceFilenameToDest(GFile srcFile) throws IOException {
+ return FSUtilities.getSafeFilename(srcFile.getName());
+ }
+
+ /**
+ * Allows custom handling of exceptions that occur during file extraction.
+ * <p>
+ * Return true if the exception should be ignored by the file extraction process,
+ * otherwise return false if it should be propagated up the call stack.
+ *
+ * @param file file that was being extracted when the exception happened
+ * @param e the exception
+ * @return true if the exception should be suppressed, false if the exception should
+ * be thrown
+ */
+ protected boolean handleUnexpectedException(GFile file, Exception e) {
+ return false;
+ }
+
+ private boolean isSpecialDirectory(GFile directory) {
+ if (directory == null) {
+ return false;
+ }
+
+ switch (directory.getName()) {
+ // Mac HFS metadata directories
+ case "\0\0\0\0HFS+ Private Data":
+ case ".HFS+ Private Directory Data\r":
+ return true;
+ }
+ return false;
+ }
+
+ protected void extractFile(GFile srcFile, File outputFile, TaskMonitor monitor)
+ throws CancelledException, CryptoException {
+
+ monitor.setMessage(srcFile.getName());
+ try (InputStream in = getSourceFileInputStream(srcFile, monitor)) {
+ if (in != null) {
+ try (OutputStream out = new FileOutputStream(outputFile)) {
+ long bytesCopied = FileUtilities.copyStreamToStream(in, out, monitor);
+ // only check the bytes copied if the file knows its length. If -1, just allow anything.
+ if (srcFile.getLength() != -1 && bytesCopied != srcFile.getLength()) {
+ throw new IOException("Failed to copy the correct number of bytes from " +
+ srcFile.getFSRL() + " to " + outputFile + ". Expected " +
+ srcFile.getLength() + ", bytes copied " + bytesCopied);
+ }
+ totalBytesExportedCount += bytesCopied;
+ totalFilesExportedCount++;
+ }
+ }
+ }
+ catch (IOException e) {
+ Msg.error(this, "Error when copying file " + srcFile.getFSRL() + " to " + outputFile,
+ e);
+ }
+ }
+
+ protected InputStream getSourceFileInputStream(GFile file, TaskMonitor monitor)
+ throws CancelledException, IOException {
+ return fs.getInputStream(file, monitor);
+ }
+
+ /**
+ * Return the number of files that were exported.
+ * <p>
+ * @return the number of files that were exported
+ */
+ public int getTotalFilesExportedCount() {
+ return totalFilesExportedCount;
+ }
+
+ /**
+ * Return the number of directories that were exported.
+ * <p>
+ * @return the number of directories that were exported
+ */
+ public int getTotalDirsExportedCount() {
+ return totalDirsExportedCount;
+ }
+
+ /**
+ * Return the number of bytes that were exported.
+ * <p>
+ * @return the number of bytes that were exported
+ */
+ public long getTotalBytesExportedCount() {
+ return totalBytesExportedCount;
+ }
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/FileSystemService.java b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/FileSystemService.java
index f0a3afa64f..00dfe29090 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/FileSystemService.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/FileSystemService.java
@@ -690,6 +690,34 @@ public class FileSystemService {
return fsClass.cast(fs);
}
+ /**
+ * Open the file system contained at the specified location.
+ * <p>
+ * The newly constructed / mounted file system is not managed by this FileSystemService
+ * or controlled with {@link FileSystemRef}s.
+ * <p>
+ * The caller is responsible for closing the resultant file system instance when it is
+ * no longer needed.
+ * <p>
+ * @param containerFSRL a reference to the file that contains the file system image
+ * @param monitor {@link TaskMonitor} to allow the user to cancel
+ * @return new {@link GFileSystem} instance, caller is responsible for closing() when done.
+ * @throws CancelledException if user cancels
+ * @throws IOException if file io error or wrong file system type.
+ */
+ public GFileSystem openFileSystemContainer(FSRL containerFSRL, TaskMonitor monitor)
+ throws CancelledException, IOException {
+
+ if (localFS.isLocalSubdir(containerFSRL)) {
+ File localDir = localFS.getLocalFile(containerFSRL);
+ return new LocalFileSystemSub(localDir, localFS);
+ }
+
+ File containerFile = getFile(containerFSRL, monitor);
+ return fsFactoryMgr.probe(containerFSRL, containerFile, this, null,
+ FileSystemInfo.PRIORITY_LOWEST, monitor);
+ }
+
/**
* Returns a cloned copy of the {@code FSRL} that should have MD5 values specified.
* (excluding GFile objects that don't have data streams)
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/GFileSystem.java b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/GFileSystem.java
index f37ca6072c..7fd0519d5a 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/GFileSystem.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/GFileSystem.java
@@ -15,7 +15,9 @@
*/
package ghidra.formats.gfilesystem;
-import java.io.*;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
import java.util.List;
import ghidra.formats.gfilesystem.annotations.FileSystemInfo;
@@ -116,7 +118,8 @@ public interface GFileSystem extends Closeable, ExtensionPoint {
/**
* Retrieves a {@link GFile} from this filesystem based on its full path and filename.
* <p>
- * @param path string path and filename of a file located in this filesystem
+ * @param path string path and filename of a file located in this filesystem. Use
+ * {@code null} or "/" to retrieve the root directory
* @return {@link GFile} instance of requested file, null if not found.
* @throws IOException if IO error when looking up file.
*/
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/tasks/GFileSystemExtractAllTask.java b/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/tasks/GFileSystemExtractAllTask.java
index 5ea580ba20..806061a00d 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/tasks/GFileSystemExtractAllTask.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/tasks/GFileSystemExtractAllTask.java
@@ -16,14 +16,24 @@
package ghidra.plugins.fsbrowser.tasks;
import java.awt.Component;
-import java.io.*;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;
import docking.widgets.OptionDialog;
-import ghidra.formats.gfilesystem.*;
-import ghidra.util.*;
-import ghidra.util.exception.*;
+import ghidra.formats.gfilesystem.AbstractFileExtractorTask;
+import ghidra.formats.gfilesystem.FSRL;
+import ghidra.formats.gfilesystem.FileSystemService;
+import ghidra.formats.gfilesystem.GFile;
+import ghidra.formats.gfilesystem.GFileSystem;
+import ghidra.formats.gfilesystem.RefdFile;
+import ghidra.util.DateUtils;
+import ghidra.util.HTMLUtilities;
+import ghidra.util.Msg;
+import ghidra.util.exception.CancelledException;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
import utilities.util.FileUtilities;
@@ -32,21 +42,16 @@ import utilities.util.FileUtilities;
* {@link Task} that recursively extracts all files from a {@link GFileSystem} directory
* and writes them to a local filesystem.
*/
-public class GFileSystemExtractAllTask extends Task {
+public class GFileSystemExtractAllTask extends AbstractFileExtractorTask {
private FSRL srcFSRL;
- private File outputDirectory;
private Component parentComponent;
- private int totalFilesExportedCount;
- private int totalDirExportedCount;
- private long totalBytesExportedCount;
private boolean skipAllErrors;
private Map<FSRL, String> errorredFiles = new LinkedHashMap<>();
public GFileSystemExtractAllTask(FSRL srcFSRL, File outputDirectory,
Component parentComponent) {
- super("Extracting directory...", true, false, true);
+ super("Extracting directory...", true, false, true, outputDirectory);
this.srcFSRL = srcFSRL;
- this.outputDirectory = outputDirectory;
this.parentComponent = parentComponent;
}
@@ -63,9 +68,8 @@ public class GFileSystemExtractAllTask extends Task {
return;
}
- File destDir = getDestDir(file.getName());
- if (destDir != null) {
- processDirectory(fs, file, destDir, monitor);
+ if (verifyRootOutputDir(file.getName())) {
+ startExtract(fs, file, monitor);
}
}
catch (CancelledException ce) {
@@ -74,8 +78,9 @@ public class GFileSystemExtractAllTask extends Task {
catch (UnsupportedOperationException | IOException e) {
Msg.showError(this, parentComponent, "Error extracting file", e.getMessage());
}
- Msg.info(this, "Exported " + totalFilesExportedCount + " files, " + totalDirExportedCount +
- " directories, " + totalBytesExportedCount + " bytes");
+ Msg.info(this,
+ "Exported " + getTotalFilesExportedCount() + " files, " + getTotalDirsExportedCount() +
+ " directories, " + getTotalBytesExportedCount() + " bytes");
long elapsed = System.currentTimeMillis() - start_ts;
@@ -85,18 +90,19 @@ public class GFileSystemExtractAllTask extends Task {
"<div style='margin-bottom: 20pt'>Source location:</div>" +
"<div style='margin-bottom: 20pt; margin-left: 50pt'>" + HTMLUtilities.friendlyEncodeHTML(srcFSRL.toPrettyString()) + "</div>" +
"<div style='margin-bottom: 20pt;'>Destination:</div>" +
- "<div style='margin-bottom: 20pt; margin-left: 50pt'>" + HTMLUtilities.friendlyEncodeHTML(outputDirectory.getPath() )+ "</div>" +
+ "<div style='margin-bottom: 20pt; margin-left: 50pt'>" + HTMLUtilities.friendlyEncodeHTML(rootOutputDirectory.getPath() )+ "</div>" +
"<div style='margin-bottom: 20pt;'>Elapsed time: " + DateUtils.formatDuration(elapsed) + "</div>" +
"<table style='margin-bottom: 20pt;' width='100%'>" +
"<tr><td></td><td>Files</td><td>Directories</td><td>Bytes</td></tr>" +
- "<tr><td>Successful</td><td>" + totalFilesExportedCount + "</td><td>" + totalDirExportedCount + "</td><td>" + FileUtilities.formatLength(totalBytesExportedCount) + "</td></tr>" +
+ "<tr><td>Successful</td><td>" + getTotalFilesExportedCount() + "</td><td>" + getTotalDirsExportedCount() +
+ "</td><td>" + FileUtilities.formatLength(getTotalBytesExportedCount()) + "</td></tr>" +
"<tr><td>Failed</td><td>" + errorredFiles.size() + "</td><td></td><td></td></tr>" +
"</table>" +
"</div></html>", "OK", "Show exported files");
//@formatter:on
if (option == OptionDialog.OPTION_TWO) {
try {
- FileUtilities.openNative(outputDirectory);
+ FileUtilities.openNative(rootOutputDirectory);
}
catch (IOException e) {
Msg.showError(this, parentComponent, "Problem Starting Explorer",
@@ -106,89 +112,29 @@ public class GFileSystemExtractAllTask extends Task {
}
}
- private File getDestDir(String destDirName) {
- boolean isSameName = destDirName.equals(outputDirectory.getName());
- File destDir = isSameName ? outputDirectory : new File(outputDirectory, destDirName);
- if (destDir.isFile()) {
+ private boolean verifyRootOutputDir(String destDirName) {
+ boolean isSameName = destDirName.equals(rootOutputDirectory.getName());
+ File newRootOutputDir =
+ isSameName ? rootOutputDirectory : new File(rootOutputDirectory, destDirName);
+ if (newRootOutputDir.isFile()) {
Msg.showError(this, parentComponent, "Export Destination Error",
- "Unable to export to " + destDir + " as it is a file");
- return null;
+ "Unable to export to " + newRootOutputDir + " as it is a file");
+ return false;
}
- if (destDir.exists() && destDir.list().length > 0) {
+ if (newRootOutputDir.exists() && newRootOutputDir.list().length > 0) {
int answer = OptionDialog.showYesNoDialog(parentComponent, "Verify Export Destination",
- destDir.getAbsolutePath() + "\n" + "The directory is not empty." + "\n" +
+ newRootOutputDir.getAbsolutePath() + "\n" + "The directory is not empty." + "\n" +
"Do you want to overwrite the contents?");
if (answer == OptionDialog.NO_OPTION) {
- return null;
- }
- }
- return destDir;
- }
-
- /**
- * Extract the contents of a directory in a {@link GFileSystem} into a local file system
- * directory.
- * <p>
- * The destination directory is created if not present.
- *
- * @param fs the {@link GFileSystem} containing the directory.
- * @param srcGFileDirectory if null, directory is filesystem root.
- * @param destDirectory destination / output directory.
- * @param monitor {@link TaskMonitor} to watch and update with progress.
- * @throws IOException if IO problem.
- */
- private void processDirectory(GFileSystem fs, GFile srcGFileDirectory, File destDirectory,
- TaskMonitor monitor) throws IOException, CancelledException {
-
- if (isSpecialDirectory(srcGFileDirectory)) {
- return;
- }
-
- if (!FileUtilities.isPathContainedWithin(outputDirectory, destDirectory)) {
- // This can happen with hostile relative paths supplied by the data in the filesystem.
- String srcPath = (srcGFileDirectory != null) ? srcGFileDirectory.getPath() : "/";
- throw new IOException("Extracted directory " + srcPath + " [" + destDirectory +
- "] would be outside of root destination directory: " + outputDirectory);
- }
-
- if (!destDirectory.isDirectory() && !destDirectory.mkdirs()) {
- throw new IOException("Failed to create destination directory " + destDirectory);
- }
- totalDirExportedCount++;
-
- for (GFile file : fs.getListing(srcGFileDirectory)) {
- monitor.checkCanceled();
-
- // TODO: maybe make this an optional safeguard to allow non-hostile relative paths
- // that safely stay inside the container
- String fname = FSUtilities.getSafeFilename(file.getName());
-
- File destFSFile = new File(destDirectory, fname);
- if (file.isDirectory()) {
- processDirectory(fs, file, destFSFile, monitor);
- }
- else {
- try {
- if (!FileUtilities.isPathContainedWithin(this.outputDirectory, destFSFile)) {
- throw new IOException("Extracted file " + file.getPath() + " [" +
- destFSFile + "] would be outside of root destination directory: " +
- this.outputDirectory);
- }
- extractFile(file, destFSFile.getCanonicalFile(), monitor);
- }
- catch (CancelledException | IOCancelledException e) {
- throw e;
- }
- catch (Exception e) {
- if (!handleUnexpectedException(file, e)) {
- throw e;
- }
- }
+ return false;
}
}
+ rootOutputDirectory = newRootOutputDir;
+ return true;
}
- private boolean handleUnexpectedException(GFile file, Exception e) {
+ @Override
+ protected boolean handleUnexpectedException(GFile file, Exception e) {
errorredFiles.put(file.getFSRL(), e.getMessage());
if (skipAllErrors) {
@@ -209,44 +155,11 @@ public class GFileSystemExtractAllTask extends Task {
return true;
}
- private boolean isSpecialDirectory(GFile directory) {
- if (directory == null) {
- return false;
- }
-
- switch (directory.getName()) {
- // Mac HFS metadata directories
- case "\0\0\0\0HFS+ Private Data":
- case ".HFS+ Private Directory Data\r":
- return true;
- }
- return false;
- }
-
- private void extractFile(GFile file, File outputFile, TaskMonitor monitor)
- throws IOException, CancelledException, CryptoException {
-
- if (file.getLength() == 0) {
- return;
- }
- monitor.setMessage(file.getName());
+ @Override
+ protected InputStream getSourceFileInputStream(GFile file, TaskMonitor monitor)
+ throws CancelledException, IOException {
File cacheFile = FileSystemService.getInstance().getFile(file.getFSRL(), monitor);
- if (cacheFile == null) {
- return;
- }
- try (InputStream in = new FileInputStream(cacheFile);
- OutputStream out = new FileOutputStream(outputFile);) {
- long bytesCopied = FileUtilities.copyStreamToStream(in, out, monitor);
- if (file.getLength() != -1 && bytesCopied != file.getLength()) {
- throw new IOException("Failed to copy the correct number of bytes from " +
- file.getFSRL() + " to " + outputFile + ". Expected " + file.getLength() +
- ", bytes copied " + bytesCopied);
- }
- totalBytesExportedCount += bytesCopied;
- totalFilesExportedCount++;
- }
- catch (IOException e) {
- Msg.error(this, "Error when copying file " + file.getFSRL() + " to " + outputFile, e);
- }
+ return new FileInputStream(cacheFile);
}
+
}