From 2e36633ed556f00812fce3d8567c10e0ef1797a2 Mon Sep 17 00:00:00 2001
From: Joshua Villalta <93329405+vgoat21@users.noreply.github.com>
Date: Wed, 18 Nov 2026 12:15:09 +0000
Subject: [PATCH] feat(ENG-4705): download plugin updates in the background and
install them on restart
When a newer release is found, download the build for the running Ghidra
version, verify it against GitHub's SHA-256 asset digest and unpack it into
reai-plugin-update/ in the user settings folder. A shutdown hook starts
ExtensionSwapper in its own JVM, which waits for Ghidra to exit and swaps the
staged folder over the installed extension, restoring the old one on failure.
Adds an 'Install updates automatically' option; with it off, or when the
extension is not in the user's Extensions folder, the existing download
prompt is shown.
---
README.md | 8 +
.../services/update/ExtensionSwapper.java | 102 ++++++++
.../core/services/update/UpdateChecker.java | 10 +-
.../core/services/update/UpdateInstaller.java | 246 ++++++++++++++++++
.../ghidra/plugins/ReaiAPIServicePlugin.java | 59 ++++-
.../services/update/ExtensionSwapperTest.java | 72 +++++
.../services/update/UpdateCheckerTest.java | 10 +-
.../services/update/UpdateInstallerTest.java | 84 ++++++
8 files changed, 586 insertions(+), 5 deletions(-)
create mode 100644 src/main/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapper.java
create mode 100644 src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstaller.java
create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapperTest.java
create mode 100644 src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstallerTest.java
diff --git a/README.md b/README.md
index 2c0f44d1..a68b3c2d 100644
--- a/README.md
+++ b/README.md
@@ -63,6 +63,14 @@ Set `GHIDRA_INSTALL_DIR` to target a specific install, or `REVENG_PLUGIN_VERSION
The builds for latest stable version of the RevEng.AI Ghidra plugin for common Ghidra versions can be downloaded from the [Releases](https://github.com/revengai/plugin-ghidra/releases/latest) page.
+### Updating
+
+The plugin checks GitHub for a new release when Ghidra starts. If it finds one, it downloads the build for your Ghidra version in the background and checks it against the SHA-256 checksum GitHub publishes for the release. It then installs that build when you close Ghidra, so the new version runs the next time you start Ghidra.
+The download is kept in `reai-plugin-update/` in your Ghidra user settings folder until it is installed.
+
+This only works when the plugin is installed in your user `Extensions` folder, which is where the install script and `Install Extensions` put it.
+You can turn off the check or the automatic install with `Check for updates` and `Install updates automatically` under `Edit` -> `Tool Options...` -> `RevEngAI Options` in the CodeBrowser. With the automatic install off, the plugin only tells you about new releases and links to the download.
+
### Supported Ghidra versions
We support all versions compatible with Ghidra 11.4+. Ghidra 11.4 through 12.1.x run on Java 21;
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapper.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapper.java
new file mode 100644
index 00000000..5c9490bf
--- /dev/null
+++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapper.java
@@ -0,0 +1,102 @@
+package ai.reveng.toolkit.ghidra.core.services.update;
+
+import java.io.IOException;
+import java.nio.file.FileSystemException;
+import java.nio.file.Files;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.util.Comparator;
+
+/**
+ * Moves a staged update into the Extensions folder once Ghidra has exited.
+ *
+ * Ghidra keeps the installed jars open for as long as it runs (and Windows locks open files), so the
+ * running plugin cannot replace itself. {@link UpdateInstaller} starts this class in a separate JVM as
+ * Ghidra shuts down. Its classpath is a copy of the plugin jar and nothing else, so it must only use
+ * the JDK and must not touch {@link UpdateInstaller} or any Ghidra class.
+ */
+public final class ExtensionSwapper {
+ /** Folder name of the extension, both installed and inside the release zip. */
+ static final String EXTENSION_DIR = "plugin-ghidra";
+ /** Holds the staged release tag. Written last when staging and removed on install or skip. */
+ static final String READY_FILE = "ready";
+ static final String PREVIOUS_DIR = "previous";
+
+ private static final int MOVE_ATTEMPTS = 10;
+
+ private ExtensionSwapper() {}
+
+ /** Arguments: Ghidra's process id, the installed extension folder, the staging folder. */
+ public static void main(String[] args) throws Exception {
+ long ghidraPid = Long.parseLong(args[0]);
+ var installed = Path.of(args[1]);
+ var staging = Path.of(args[2]);
+
+ ProcessHandle.of(ghidraPid).ifPresent(ghidra -> ghidra.onExit().join());
+ try {
+ System.out.println(Instant.now() + " " + swap(installed, staging));
+ } catch (Exception e) {
+ System.out.println(Instant.now() + " Update failed, the previous version is still installed");
+ e.printStackTrace(System.out);
+ }
+ }
+
+ /**
+ * Replaces {@code installed} with the extension staged under {@code staging}, restoring the old
+ * one if the new one cannot be moved in. Returns a line for the update log.
+ */
+ static String swap(Path installed, Path staging) throws IOException, InterruptedException {
+ var ready = staging.resolve(READY_FILE);
+ if (!Files.exists(ready)) {
+ return "No staged update (skipped by the user)";
+ }
+ var version = Files.readString(ready).strip();
+ // Ghidra's uninstall renames extension.properties away; don't bring back what the user removed.
+ if (!Files.exists(installed.resolve("extension.properties"))) {
+ Files.delete(ready);
+ return "Not installing " + version + ": the extension is no longer installed at " + installed;
+ }
+
+ var previous = staging.resolve(PREVIOUS_DIR);
+ deleteRecursively(previous);
+ move(installed, previous);
+ try {
+ move(staging.resolve(EXTENSION_DIR), installed);
+ } catch (IOException e) {
+ move(previous, installed);
+ throw e;
+ }
+ Files.delete(ready);
+ deleteRecursively(previous);
+ return "Installed " + version + " into " + installed;
+ }
+
+ /** Renames {@code from} to {@code to}, retrying while Windows still holds handles from Ghidra. */
+ private static void move(Path from, Path to) throws IOException, InterruptedException {
+ for (int attempt = 1; ; attempt++) {
+ try {
+ Files.move(from, to);
+ return;
+ } catch (NoSuchFileException e) {
+ throw e;
+ } catch (FileSystemException e) {
+ if (attempt == MOVE_ATTEMPTS) {
+ throw e;
+ }
+ Thread.sleep(1000);
+ }
+ }
+ }
+
+ static void deleteRecursively(Path path) throws IOException {
+ if (!Files.exists(path)) {
+ return;
+ }
+ try (var paths = Files.walk(path)) {
+ for (var p : paths.sorted(Comparator.reverseOrder()).toList()) {
+ Files.delete(p);
+ }
+ }
+ }
+}
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateChecker.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateChecker.java
index 07b4daa5..335e2dbd 100644
--- a/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateChecker.java
+++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateChecker.java
@@ -22,7 +22,11 @@ public class UpdateChecker {
private static final String LATEST_RELEASE_URL =
"https://api.github.com/repos/RevEngAI/plugin-ghidra/releases/latest";
- public record UpdateInfo(String version, String releaseUrl, String downloadUrl) {}
+ /**
+ * @param sha256 hex SHA-256 of the download, from GitHub's asset digest, or null when the
+ * release does not carry one
+ */
+ public record UpdateInfo(String version, String releaseUrl, String downloadUrl, String sha256) {}
/**
* The installed plugin's release tag, or {@link #UNKNOWN_VERSION} for local builds.
@@ -69,8 +73,10 @@ static Optional findUpdate(String currentVersion, String ghidraVersi
for (int i = 0; i < assets.length(); i++) {
var asset = assets.getJSONObject(i);
if (assetName.equals(asset.getString("name"))) {
+ var digest = asset.optString("digest", "");
+ var sha256 = digest.startsWith("sha256:") ? digest.substring("sha256:".length()) : null;
return Optional.of(new UpdateInfo(latest, release.getString("html_url"),
- asset.getString("browser_download_url")));
+ asset.getString("browser_download_url"), sha256));
}
}
} catch (JSONException ignored) {
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstaller.java b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstaller.java
new file mode 100644
index 00000000..3a0f42aa
--- /dev/null
+++ b/src/main/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstaller.java
@@ -0,0 +1,246 @@
+package ai.reveng.toolkit.ghidra.core.services.update;
+
+import ai.reveng.toolkit.ghidra.core.services.update.UpdateChecker.UpdateInfo;
+import ghidra.framework.Application;
+import ghidra.util.Msg;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.HexFormat;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.zip.ZipInputStream;
+
+import static ai.reveng.toolkit.ghidra.core.services.update.ExtensionSwapper.EXTENSION_DIR;
+import static ai.reveng.toolkit.ghidra.core.services.update.ExtensionSwapper.READY_FILE;
+
+/**
+ * Downloads a plugin release in the background and installs it when Ghidra closes.
+ *
+ * The release is unpacked into a staging folder in the user settings directory, outside
+ * {@code Extensions/} so Ghidra does not load it as a second copy. As Ghidra shuts down, a shutdown
+ * hook starts {@link ExtensionSwapper} in its own JVM, which waits for Ghidra to exit and then moves
+ * the staged folder over the installed one.
+ */
+public final class UpdateInstaller {
+ private static final String STAGING_DIR = "reai-plugin-update";
+ private static final String DOWNLOAD_FILE = "download.zip";
+ // The swapper runs from a copy, so it doesn't hold the jar it is about to replace open.
+ private static final String UPDATER_JAR = "updater.jar";
+ private static final String LOG_FILE = "update.log";
+ private static final String PLUGIN_JAR = "lib/plugin-ghidra.jar";
+
+ // Every CodeBrowser runs its own update check; these keep it to one download and one hook per JVM.
+ private static final Map> downloads = new HashMap<>();
+ private static boolean startupHandled = false;
+ private static Thread shutdownHook;
+
+ private UpdateInstaller() {}
+
+ /**
+ * The folder this plugin runs from, if it is one this user can replace: a {@code plugin-ghidra}
+ * folder in the user's own {@code Extensions/} directory. Empty for a local build or an
+ * extension installed into the Ghidra installation.
+ */
+ public static Optional installedExtension() {
+ try {
+ var installed = Application.getMyModuleRootDirectory().getFile(false).toPath().toRealPath();
+ var extensions = Application.getUserSettingsDirectory().toPath().resolve("Extensions").toRealPath();
+ if (extensions.equals(installed.getParent())
+ && installed.getFileName().toString().equals(EXTENSION_DIR)
+ && Files.isRegularFile(installed.resolve(PLUGIN_JAR))) {
+ return Optional.of(installed);
+ }
+ } catch (IOException | RuntimeException e) {
+ Msg.debug(UpdateInstaller.class, "Cannot locate the installed extension", e);
+ }
+ return Optional.empty();
+ }
+
+ /**
+ * Logs the result of the last install and then either keeps a staged release newer than
+ * {@code currentVersion} (so it installs when this session closes, even offline) or removes
+ * whatever is staged. Only the first call per JVM does anything.
+ */
+ public static synchronized void handleStartup(String currentVersion, Optional installed) {
+ if (startupHandled) {
+ return;
+ }
+ startupHandled = true;
+ var staging = stagingDir();
+ try {
+ var log = staging.resolve(LOG_FILE);
+ if (Files.exists(log)) {
+ Msg.info(UpdateInstaller.class, "RevEng.AI plugin update: " + Files.readString(log).strip());
+ Files.delete(log);
+ }
+ var staged = stagedVersion(staging);
+ if (installed.isPresent() && staged.isPresent() && UpdateChecker.isNewer(staged.get(), currentVersion)) {
+ registerShutdownHook(installed.get(), staging);
+ } else {
+ ExtensionSwapper.deleteRecursively(staging);
+ }
+ } catch (IOException e) {
+ Msg.warn(UpdateInstaller.class, "Cannot clean up the RevEng.AI update folder " + staging, e);
+ }
+ }
+
+ /**
+ * Downloads, verifies and unpacks {@code update}, then arranges for it to be installed over
+ * {@code installed} when Ghidra exits. Completes exceptionally if any step fails, leaving
+ * nothing staged.
+ */
+ public static synchronized CompletableFuture stage(UpdateInfo update, Path installed) {
+ return downloads.computeIfAbsent(update.version(), version -> CompletableFuture.runAsync(() -> {
+ var staging = stagingDir();
+ try {
+ if (!stagedVersion(staging).orElse("").equals(version)) {
+ download(update, installed, staging);
+ }
+ } catch (IOException e) {
+ deleteQuietly(staging);
+ throw new UncheckedIOException(e);
+ } catch (InterruptedException e) {
+ deleteQuietly(staging);
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ registerShutdownHook(installed, staging);
+ }));
+ }
+
+ /** Drops the staged release so nothing is installed on exit. */
+ public static synchronized void cancel() {
+ downloads.clear();
+ deleteQuietly(stagingDir());
+ }
+
+ private static void download(UpdateInfo update, Path installed, Path staging) throws IOException, InterruptedException {
+ ExtensionSwapper.deleteRecursively(staging);
+ Files.createDirectories(staging);
+
+ var zip = staging.resolve(DOWNLOAD_FILE);
+ var request = HttpRequest.newBuilder(URI.create(update.downloadUrl()))
+ .timeout(Duration.ofMinutes(5))
+ .build();
+ var response = HttpClient.newBuilder()
+ .followRedirects(HttpClient.Redirect.NORMAL)
+ .connectTimeout(Duration.ofSeconds(10))
+ .build()
+ .send(request, HttpResponse.BodyHandlers.ofFile(zip));
+ if (response.statusCode() != 200) {
+ throw new IOException("Downloading " + update.downloadUrl() + " returned HTTP " + response.statusCode());
+ }
+ verifySha256(zip, update.sha256());
+ extract(zip, staging);
+ Files.delete(zip);
+
+ Files.copy(installed.resolve(PLUGIN_JAR), staging.resolve(UPDATER_JAR));
+ Files.writeString(staging.resolve(READY_FILE), update.version());
+ }
+
+ static void verifySha256(Path file, String expected) throws IOException {
+ if (expected == null) {
+ throw new IOException("The release does not publish a checksum for " + file.getFileName());
+ }
+ try (var in = Files.newInputStream(file)) {
+ var digest = MessageDigest.getInstance("SHA-256");
+ var buffer = new byte[64 * 1024];
+ for (int n; (n = in.read(buffer)) != -1; ) {
+ digest.update(buffer, 0, n);
+ }
+ var actual = HexFormat.of().formatHex(digest.digest());
+ if (!actual.equalsIgnoreCase(expected)) {
+ throw new IOException("Checksum mismatch for " + file.getFileName() + ": expected " + expected + ", got " + actual);
+ }
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ /** Unpacks the {@code plugin-ghidra/} folder of a release zip into {@code staging}. */
+ static void extract(Path zip, Path staging) throws IOException {
+ var root = staging.resolve(EXTENSION_DIR).normalize();
+ try (var in = new ZipInputStream(Files.newInputStream(zip))) {
+ for (var entry = in.getNextEntry(); entry != null; entry = in.getNextEntry()) {
+ var target = staging.resolve(entry.getName()).normalize();
+ if (!target.startsWith(root)) {
+ throw new IOException("Unexpected entry in release zip: " + entry.getName());
+ }
+ if (entry.isDirectory()) {
+ Files.createDirectories(target);
+ } else {
+ Files.createDirectories(target.getParent());
+ // Release zips list some files twice.
+ Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
+ }
+ }
+ }
+ if (!Files.isRegularFile(root.resolve("extension.properties")) || !Files.isRegularFile(root.resolve(PLUGIN_JAR))) {
+ throw new IOException(zip.getFileName() + " is not a " + EXTENSION_DIR + " build");
+ }
+ }
+
+ private static synchronized void registerShutdownHook(Path installed, Path staging) {
+ if (shutdownHook != null) {
+ return;
+ }
+ shutdownHook = new Thread(() -> launchSwapper(installed, staging), "RevEng.AI plugin update");
+ Runtime.getRuntime().addShutdownHook(shutdownHook);
+ }
+
+ private static void launchSwapper(Path installed, Path staging) {
+ if (!Files.exists(staging.resolve(READY_FILE))) {
+ return;
+ }
+ var bin = Path.of(System.getProperty("java.home"), "bin");
+ // javaw has no console window, so nothing flashes up on Windows after Ghidra closes.
+ var java = Files.exists(bin.resolve("javaw.exe")) ? bin.resolve("javaw.exe")
+ : Files.exists(bin.resolve("java.exe")) ? bin.resolve("java.exe")
+ : bin.resolve("java");
+ try {
+ new ProcessBuilder(java.toString(), "-cp", staging.resolve(UPDATER_JAR).toString(),
+ ExtensionSwapper.class.getName(),
+ Long.toString(ProcessHandle.current().pid()), installed.toString(), staging.toString())
+ .redirectErrorStream(true)
+ .redirectOutput(ProcessBuilder.Redirect.appendTo(staging.resolve(LOG_FILE).toFile()))
+ .start();
+ } catch (IOException e) {
+ // Ghidra is shutting down, so stderr is the only place left to report this.
+ System.err.println("RevEng.AI: cannot start the plugin updater: " + e);
+ }
+ }
+
+ private static Path stagingDir() {
+ return Application.getUserSettingsDirectory().toPath().resolve(STAGING_DIR);
+ }
+
+ static Optional stagedVersion(Path staging) {
+ try {
+ var ready = staging.resolve(READY_FILE);
+ return Files.exists(ready) ? Optional.of(Files.readString(ready).strip()) : Optional.empty();
+ } catch (IOException e) {
+ return Optional.empty();
+ }
+ }
+
+ private static void deleteQuietly(Path path) {
+ try {
+ ExtensionSwapper.deleteRecursively(path);
+ } catch (IOException e) {
+ Msg.warn(UpdateInstaller.class, "Cannot delete " + path, e);
+ }
+ }
+}
diff --git a/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java b/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java
index 22c8a0c5..30615fec 100644
--- a/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java
+++ b/src/main/java/ai/reveng/toolkit/ghidra/plugins/ReaiAPIServicePlugin.java
@@ -6,6 +6,7 @@
import ai.reveng.toolkit.ghidra.core.services.api.types.ApiInfo;
import ai.reveng.toolkit.ghidra.core.services.update.UpdateChecker;
import ai.reveng.toolkit.ghidra.core.services.update.UpdateChecker.UpdateInfo;
+import ai.reveng.toolkit.ghidra.core.services.update.UpdateInstaller;
import ai.reveng.toolkit.ghidra.core.ui.WebBrowser;
import ai.reveng.toolkit.ghidra.core.ui.wizard.SetupWizardManager;
import ai.reveng.toolkit.ghidra.core.ui.wizard.SetupWizardStateKey;
@@ -49,6 +50,7 @@ public class ReaiAPIServicePlugin extends Plugin {
public static final String REAI_WIZARD_RUN_PREF = "REAISetupWizardRun";
public static final String CHECK_FOR_UPDATES_PREF = "Check for updates";
public static final String SKIPPED_UPDATE_PREF = "Skipped update version";
+ public static final String INSTALL_UPDATES_PREF = "Install updates automatically";
public ReaiAPIServicePlugin(PluginTool tool) {
super(tool);
@@ -56,6 +58,7 @@ public ReaiAPIServicePlugin(PluginTool tool) {
tool.getOptions(REAI_OPTIONS_CATEGORY).registerOption(REAI_WIZARD_RUN_PREF, "false", null, "If the setup wizard has been run");
tool.getOptions(REAI_OPTIONS_CATEGORY).registerOption(CHECK_FOR_UPDATES_PREF, true, null, "Check GitHub for a newer plugin release on startup");
tool.getOptions(REAI_OPTIONS_CATEGORY).registerOption(SKIPPED_UPDATE_PREF, "", null, "Release the user chose not to be prompted about");
+ tool.getOptions(REAI_OPTIONS_CATEGORY).registerOption(INSTALL_UPDATES_PREF, true, null, "Download new releases in the background and install them when Ghidra closes");
// Try to get API info from config file or tool options
Optional apiInfoOpt = getApiInfoFromConfig()
@@ -80,12 +83,64 @@ public ReaiAPIServicePlugin(PluginTool tool) {
private void checkForUpdates() {
var currentVersion = UpdateChecker.currentVersion();
- if (!tool.getOptions(REAI_OPTIONS_CATEGORY).getBoolean(CHECK_FOR_UPDATES_PREF, true)
+ var options = tool.getOptions(REAI_OPTIONS_CATEGORY);
+ if (!options.getBoolean(CHECK_FOR_UPDATES_PREF, true)
|| currentVersion.equals(UpdateChecker.UNKNOWN_VERSION)) {
return;
}
+ // Empty when updates can't be installed automatically, which also discards anything staged.
+ var installed = options.getBoolean(INSTALL_UPDATES_PREF, true)
+ ? UpdateInstaller.installedExtension()
+ : Optional.empty();
+ UpdateInstaller.handleStartup(currentVersion, installed);
UpdateChecker.check(currentVersion, Application.getApplicationVersion())
- .thenAccept(result -> result.ifPresent(u -> Swing.runLater(() -> notifyUpdate(u))));
+ .thenAccept(result -> result.ifPresent(u -> Swing.runLater(() -> handleUpdate(u, installed))));
+ }
+
+ private void handleUpdate(UpdateInfo u, Optional installed) {
+ var skipped = u.version().equals(tool.getOptions(REAI_OPTIONS_CATEGORY).getString(SKIPPED_UPDATE_PREF, ""));
+ if (installed.isEmpty() || u.sha256() == null || skipped) {
+ notifyUpdate(u);
+ return;
+ }
+ UpdateInstaller.stage(u, installed.get()).whenComplete((ignored, error) -> Swing.runLater(() -> {
+ if (error != null) {
+ Msg.warn(this, "Could not download RevEng.AI plugin " + u.version() + ", offering a manual download", error);
+ notifyUpdate(u);
+ } else {
+ notifyUpdateReady(u);
+ }
+ }));
+ }
+
+ private void notifyUpdateReady(UpdateInfo u) {
+ if (isDisposed()) {
+ return;
+ }
+ update = Optional.of(u);
+
+ var message = "RevEng.AI plugin " + u.version() + " has been downloaded. You have " + UpdateChecker.currentVersion()
+ + ".\nIt will be installed when you close Ghidra. Restart Ghidra to start using it.";
+ var action = new ActionBuilder("Update ready", this.toString())
+ .withContext(ActionContext.class)
+ .onAction(context -> Msg.showInfo(this, tool.getToolFrame(), "RevEng.AI update ready", message))
+ .menuPath(new String[] { ReaiPluginPackage.MENU_GROUP_NAME, "Update ready (" + u.version() + ") - restart Ghidra" })
+ .menuGroup(REAI_PLUGIN_SETUP_MENU_GROUP, "050")
+ .buildAndInstall(tool);
+ tool.setStatusInfo("RevEng.AI plugin " + u.version() + " will be installed when Ghidra restarts");
+
+ if (updatePromptShown) {
+ return;
+ }
+ updatePromptShown = true;
+ int choice = OptionDialog.showOptionNoCancelDialog(tool.getToolFrame(), "RevEng.AI update ready",
+ message, "OK", "Skip this version", OptionDialog.INFORMATION_MESSAGE);
+ if (choice == OptionDialog.OPTION_TWO) {
+ UpdateInstaller.cancel();
+ tool.getOptions(REAI_OPTIONS_CATEGORY).setString(SKIPPED_UPDATE_PREF, u.version());
+ tool.removeAction(action);
+ tool.setStatusInfo("RevEng.AI plugin " + u.version() + " will not be installed");
+ }
}
private void notifyUpdate(UpdateInfo u) {
diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapperTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapperTest.java
new file mode 100644
index 00000000..67cf58d6
--- /dev/null
+++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/ExtensionSwapperTest.java
@@ -0,0 +1,72 @@
+package ai.reveng.toolkit.ghidra.core.services.update;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+/** Unit tests for {@link ExtensionSwapper#swap}. */
+public class ExtensionSwapperTest {
+ @Rule
+ public TemporaryFolder temp = new TemporaryFolder();
+
+ private Path installed;
+ private Path staging;
+
+ @Before
+ public void setUp() throws IOException {
+ installed = temp.newFolder("Extensions", "plugin-ghidra").toPath();
+ Files.writeString(installed.resolve("extension.properties"), "old");
+ staging = temp.newFolder("reai-plugin-update").toPath();
+ Files.createDirectories(staging.resolve("plugin-ghidra"));
+ Files.writeString(staging.resolve("plugin-ghidra/extension.properties"), "new");
+ Files.writeString(staging.resolve(ExtensionSwapper.READY_FILE), "v1.3.0");
+ }
+
+ @Test
+ public void installsStagedExtension() throws Exception {
+ var result = ExtensionSwapper.swap(installed, staging);
+
+ assertTrue(result, result.startsWith("Installed v1.3.0"));
+ assertEquals("new", Files.readString(installed.resolve("extension.properties")));
+ assertFalse(Files.exists(staging.resolve(ExtensionSwapper.READY_FILE)));
+ assertFalse(Files.exists(staging.resolve(ExtensionSwapper.PREVIOUS_DIR)));
+ }
+
+ @Test
+ public void doesNothingWhenSkipped() throws Exception {
+ Files.delete(staging.resolve(ExtensionSwapper.READY_FILE));
+
+ ExtensionSwapper.swap(installed, staging);
+
+ assertEquals("old", Files.readString(installed.resolve("extension.properties")));
+ }
+
+ @Test
+ public void doesNotReinstallAnUninstalledExtension() throws Exception {
+ Files.move(installed.resolve("extension.properties"), installed.resolve("extension.properties.uninstalled"));
+
+ ExtensionSwapper.swap(installed, staging);
+
+ assertFalse(Files.exists(installed.resolve("extension.properties")));
+ assertFalse(Files.exists(staging.resolve(ExtensionSwapper.READY_FILE)));
+ }
+
+ @Test
+ public void restoresPreviousVersionWhenStagedFolderIsMissing() throws Exception {
+ ExtensionSwapper.deleteRecursively(staging.resolve("plugin-ghidra"));
+
+ assertThrows(IOException.class, () -> ExtensionSwapper.swap(installed, staging));
+
+ assertEquals("old", Files.readString(installed.resolve("extension.properties")));
+ }
+}
diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateCheckerTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateCheckerTest.java
index f1d83225..00229e07 100644
--- a/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateCheckerTest.java
+++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateCheckerTest.java
@@ -4,6 +4,7 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/** Unit tests for the pure parts of {@link UpdateChecker}. */
@@ -14,7 +15,8 @@ public class UpdateCheckerTest {
"html_url": "https://github.com/RevEngAI/plugin-ghidra/releases/tag/v1.2.0",
"assets": [
{"name": "ghidra_12.1.3_plugin-ghidra.zip", "browser_download_url": "https://example/12.1.3.zip"},
- {"name": "ghidra_12.2_plugin-ghidra.zip", "browser_download_url": "https://example/12.2.zip"}
+ {"name": "ghidra_12.2_plugin-ghidra.zip", "browser_download_url": "https://example/12.2.zip",
+ "digest": "sha256:abc123"}
]}
""";
@@ -40,6 +42,12 @@ public void findsAssetForGhidraVersion() {
assertEquals("v1.2.0", update.version());
assertEquals("https://github.com/RevEngAI/plugin-ghidra/releases/tag/v1.2.0", update.releaseUrl());
assertEquals("https://example/12.2.zip", update.downloadUrl());
+ assertEquals("abc123", update.sha256());
+ }
+
+ @Test
+ public void missingDigestLeavesChecksumUnset() {
+ assertNull(UpdateChecker.findUpdate("v1.1.0", "12.1.3", RELEASE).orElseThrow().sha256());
}
@Test
diff --git a/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstallerTest.java b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstallerTest.java
new file mode 100644
index 00000000..5f25dd92
--- /dev/null
+++ b/src/test/java/ai/reveng/toolkit/ghidra/core/services/update/UpdateInstallerTest.java
@@ -0,0 +1,84 @@
+package ai.reveng.toolkit.ghidra.core.services.update;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.MessageDigest;
+import java.util.HexFormat;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+/** Unit tests for the file handling in {@link UpdateInstaller}. */
+public class UpdateInstallerTest {
+ @Rule
+ public TemporaryFolder temp = new TemporaryFolder();
+
+ private Path zip(String... namesAndContents) throws IOException {
+ var zip = temp.newFile("release.zip").toPath();
+ try (var out = new ZipOutputStream(Files.newOutputStream(zip))) {
+ for (int i = 0; i < namesAndContents.length; i += 2) {
+ out.putNextEntry(new ZipEntry(namesAndContents[i]));
+ out.write(namesAndContents[i + 1].getBytes(StandardCharsets.UTF_8));
+ out.closeEntry();
+ }
+ }
+ return zip;
+ }
+
+ @Test
+ public void extractsReleaseZip() throws IOException {
+ var zip = zip("plugin-ghidra/extension.properties", "name=plugin-ghidra",
+ "plugin-ghidra/lib/plugin-ghidra.jar", "jar");
+ var staging = temp.newFolder("staging").toPath();
+
+ UpdateInstaller.extract(zip, staging);
+
+ assertEquals("name=plugin-ghidra", Files.readString(staging.resolve("plugin-ghidra/extension.properties")));
+ assertEquals("jar", Files.readString(staging.resolve("plugin-ghidra/lib/plugin-ghidra.jar")));
+ }
+
+ @Test
+ public void rejectsEntriesOutsideTheExtension() throws IOException {
+ var zip = zip("plugin-ghidra/../../escaped.txt", "x");
+ var staging = temp.newFolder("staging").toPath();
+
+ assertThrows(IOException.class, () -> UpdateInstaller.extract(zip, staging));
+ assertFalse(Files.exists(staging.getParent().resolve("escaped.txt")));
+ }
+
+ @Test
+ public void rejectsZipWithoutPluginJar() throws IOException {
+ var zip = zip("plugin-ghidra/extension.properties", "name=plugin-ghidra");
+ assertThrows(IOException.class, () -> UpdateInstaller.extract(zip, temp.newFolder("staging").toPath()));
+ }
+
+ @Test
+ public void verifiesChecksum() throws Exception {
+ var file = temp.newFile("download.zip").toPath();
+ Files.writeString(file, "release");
+ var sha256 = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest("release".getBytes(StandardCharsets.UTF_8)));
+
+ UpdateInstaller.verifySha256(file, sha256);
+ UpdateInstaller.verifySha256(file, sha256.toUpperCase());
+ assertThrows(IOException.class, () -> UpdateInstaller.verifySha256(file, "0".repeat(64)));
+ assertThrows(IOException.class, () -> UpdateInstaller.verifySha256(file, null));
+ }
+
+ @Test
+ public void readsStagedVersion() throws IOException {
+ var staging = temp.newFolder("staging").toPath();
+ assertTrue(UpdateInstaller.stagedVersion(staging).isEmpty());
+ Files.writeString(staging.resolve(ExtensionSwapper.READY_FILE), "v1.3.0\n");
+ assertEquals("v1.3.0", UpdateInstaller.stagedVersion(staging).orElseThrow());
+ }
+}