Skip to content

A free, open-source alternative to Burp Suite: an intercepting proxy and web app security testing suite with Repeater, Intruder, Collaborator and a built-in OWASP ZAP scanner. Linux, AGPL-3.0.

35.1 KB
Raw Blame
package opensuite.ui;

import opensuite.core.*;

import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/** Save and restore the project as a single zip, as the original did. */
public final class StateIO {
    private StateIO() {}

    /** Project file extension. */
    public static final String EXT = ".osuite";
    /** The extension project files had before the suite was renamed; they still open. */
    public static final String OLD_EXT = ".otrap";

    /** Whether a file name is a project file's, under the present extension or the old one. */
    public static boolean isProjectName(String name) {
        if (name == null) return false;
        String n = name.toLowerCase();
        return n.endsWith(EXT) || n.endsWith(OLD_EXT);
    }

    /** A timestamped default project name, matching the startup dialog. */
    public static String defaultProjectFileName() {
        return "project-" + java.time.LocalDateTime.now()
                .format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss")) + EXT;
    }

    private static File withExtension(File f) {
        if (isProjectName(f.getName())) return f;
        return new File(f.getParentFile(), f.getName() + EXT);
    }

    public static void saveDialog(SuiteContext ctx, java.awt.Component parent) {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setDialogTitle("save state");
        // Reuse the project file this session is bound to; otherwise pre-fill a
        // timestamped name (like the startup "new project" option does), so a
        // temporary session never has to have a name typed from scratch.
        if (ctx.projectFile() != null) fc.setSelectedFile(ctx.projectFile());
        else fc.setSelectedFile(new File(defaultProjectFileName()));
        if (fc.showSaveDialog(parent) != JFileChooser.APPROVE_OPTION) return;
        File f = withExtension(fc.getSelectedFile());
        if (f.exists()) {
            int r = JOptionPane.showConfirmDialog(parent,
                    "This file already exists. Overwrite it?", "confirm", JOptionPane.YES_NO_OPTION);
            if (r != JOptionPane.YES_OPTION) return;
        }
        try {
            saveOrBind(ctx, f, SaveOptions.fromSettings(ctx));
            ctx.setProjectFile(f);   // bind the session, so later saves reuse it
            ctx.alert("suite", "state saved to " + f.getName());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(parent, "An error occurred: " + e.getMessage(),
                    "error", JOptionPane.ERROR_MESSAGE);
        }
    }

    public static void restoreDialog(SuiteContext ctx, java.awt.Component parent) {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setDialogTitle("restore state");
        if (fc.showOpenDialog(parent) != JFileChooser.APPROVE_OPTION) return;
        final File file = fc.getSelectedFile();
        restoreAsync(ctx, parent, file, n -> {
            ctx.alert("suite", "restored " + n + " items from " + file.getName());
            JOptionPane.showMessageDialog(parent,
                    "Restore completed. " + n + " history items loaded.",
                    "restore state", JOptionPane.INFORMATION_MESSAGE);
        });
    }

    // One writer at a time: the autosave timer, a finished scan and an explicit
    // save can all ask for a write, and none may interleave with another.
    private static final Object SAVE_LOCK = new Object();
    private static volatile boolean autosaving;
    private static volatile long savedStamp = -1;   // the session change stamp the file holds

    /**
     * What a write keeps. The session's own project is written with
     * {@link #fromSettings}; a saved copy can narrow it further.
     */
    public static final class SaveOptions {
        /** Only history entries and issues inside the target scope. */
        public boolean inScopeOnly;
        /** The tools whose history is kept, by tool tag; null keeps every tool. */
        public java.util.Set<String> tools;
        /** Keep the scan cards from the dashboard. */
        public boolean includeTasks = true;
        /** Keep the full body of audit probe responses. */
        public boolean keepAuditBodies;
        /** Largest response body kept, in bytes; 0 for no cap. */
        public int bodyCapBytes;

        /** The options the project's settings ask for. */
        public static SaveOptions fromSettings(SuiteContext ctx) {
            SaveOptions o = new SaveOptions();
            o.keepAuditBodies = opensuite.core.ProjectOptions.keepAuditBodies(ctx.settings());
            o.bodyCapBytes = opensuite.core.ProjectOptions.bodyCapBytes(ctx.settings());
            return o;
        }
    }

    /**
     * Save the session to the project file it is bound to, in the background,
     * if anything has changed since the file was last written. Does nothing for
     * a temporary session or while another autosave runs. A failure is reported
     * once in the event log; a success is silent apart from {@code onSaved},
     * which gets the file's size in bytes on the event thread.
     */
    public static void autosave(SuiteContext ctx, java.util.function.LongConsumer onSaved) {
        File f = ctx.projectFile();
        if (f == null || autosaving) return;
        final long stamp = ctx.changeStamp();
        if (stamp == savedStamp) return;
        autosaving = true;
        Thread t = new Thread(() -> {
            try {
                save(ctx, f);
                savedStamp = stamp;
                if (onSaved != null) {
                    final long size = f.length();
                    SwingUtilities.invokeLater(() -> onSaved.accept(size));
                }
            } catch (Exception e) {
                ctx.alert("suite", "Could not save the project to " + f.getName() + ": " + e.getMessage());
            } finally {
                autosaving = false;
            }
        }, "project-autosave");
        t.setDaemon(true);
        t.start();
    }

    /**
     * A restart (a scale or theme change replaces this JVM) writes the session
     * to its project file first, exactly as exiting does; without this,
     * everything since the last autosave was lost on the way past. A temporary
     * session with no project file has nothing to write.
     */
    public static void saveBeforeRestart(SuiteContext ctx) {
        File project = ctx.projectFile();
        if (project == null) return;
        try {
            save(ctx, project);
        } catch (Exception e) {
            Debug.error("could not save the project before restarting", e);
            ctx.alert("suite", "could not save the project before restarting: "
                    + e.getMessage() + "; unsaved work will be lost");
        }
    }

    public static void autosave(SuiteContext ctx) { autosave(ctx, null); }

    /** Write the session to {@code file} with the options its settings ask for. */
    public static void save(SuiteContext ctx, File file) throws IOException {
        save(ctx, file, SaveOptions.fromSettings(ctx));
    }

    /**
     * Write the session to {@code file}. When the session is already recording
     * into this file (a v7 project opened or created this run), saving is cheap:
     * the history is already on disk per exchange, so only a fresh session-state
     * snapshot is appended and flushed. Otherwise the project is written to a new
     * single-file store beside its final name and atomic-moved into place, so a
     * crash part-way through never leaves a truncated project behind.
     */
    public static void save(SuiteContext ctx, File file, SaveOptions options) throws IOException {
        final SaveOptions o = options == null ? SaveOptions.fromSettings(ctx) : options;
        synchronized (SAVE_LOCK) {
            ProjectStore live = ctx.store().diskStore();
            if (live != null && sameFile(live.path().toFile(), file)) {
                // Bound v7 project: the entries are already appended as they were
                // recorded; a save is just the small mutable session state plus fsync.
                live.appendSnapshot(sessionStateBytes(ctx, o));
                live.sync();
                // Every changed snapshot leaves the one before it as dead space. Once that is a good part of
                // the file, write the file out afresh, as is done when a bloated project is opened.
                long dead = live.deadSnapshotBytes();
                if (dead > 8L * 1024 * 1024 && dead > live.size() / 4) {
                    try { bindNew(ctx, file, o); }
                    catch (IOException e) { Debug.error("could not compact the project file", e); }
                }
                return;
            }
            File tmp = new File(file.getParentFile(), file.getName() + ".saving");
            ProjectStore target = new ProjectStore(tmp.toPath(), 32L * 1024 * 1024);
            try {
                writeAllTo(ctx, target, o);
                target.sync();
            } finally {
                try { target.close(); } catch (IOException ignore) {}
            }
            try {
                java.nio.file.Files.move(tmp.toPath(), file.toPath(),
                        java.nio.file.StandardCopyOption.REPLACE_EXISTING,
                        java.nio.file.StandardCopyOption.ATOMIC_MOVE);
            } catch (java.nio.file.AtomicMoveNotSupportedException e) {
                java.nio.file.Files.move(tmp.toPath(), file.toPath(),
                        java.nio.file.StandardCopyOption.REPLACE_EXISTING);
            } finally {
                tmp.delete();
            }
        }
    }

    /**
     * Save to {@code file}: a cheap snapshot when the session is already bound to
     * it, otherwise write the project there and bind the session to it (a Save As
     * onto a new file), so from then on its saves are cheap too.
     */
    public static void saveOrBind(SuiteContext ctx, File file, SaveOptions options) throws IOException {
        ProjectStore live = ctx.store().diskStore();
        if (live != null && sameFile(live.path().toFile(), file)) save(ctx, file, options);
        else bindNew(ctx, file, options);
    }

    private static boolean sameFile(File a, File b) {
        if (a == null || b == null) return false;
        try { return a.getCanonicalFile().equals(b.getCanonicalFile()); }
        catch (IOException e) { return a.getAbsoluteFile().equals(b.getAbsoluteFile()); }
    }

    /**
     * Create a new single-file project at {@code file} and bind the session to
     * it, so from now on every exchange is appended to this file as it is
     * recorded and saving is a cheap snapshot flush. Any traffic recorded before
     * the project was chosen is migrated into the new file.
     */
    public static void bindNew(SuiteContext ctx, File file, SaveOptions options) throws IOException {
        final SaveOptions o = options == null ? SaveOptions.fromSettings(ctx) : options;
        synchronized (SAVE_LOCK) {
            file.delete();   // a new project starts empty even if the name was reused
            ProjectStore store = new ProjectStore(file.toPath(), 32L * 1024 * 1024);
            List<LogEntry> migrated = new ArrayList<>();
            for (LogEntry e : ctx.store().all()) {
                boolean drop = !o.keepAuditBodies && opensuite.core.ProjectOptions.AUDIT_TOOL.equals(e.tool());
                LogEntry rec = e.writtenTo(store, drop, o.bodyCapBytes);
                store.append(ProjectStore.ENTRY, rec.indexBytes());
                migrated.add(rec);
            }
            List<WebSocketMessage> frames = new ArrayList<>();
            for (WebSocketMessage m : ctx.wsStore().all()) {
                WebSocketMessage rec = m.writtenTo(store);
                store.append(ProjectStore.WS, rec.indexBytes());
                frames.add(rec);
            }
            store.append(ProjectStore.SNAPSHOT, sessionStateBytes(ctx, o));
            store.sync();
            ctx.wsStore().useStore(store);
            ctx.wsStore().replaceAll(frames);
            ctx.store().useStore(store);
            if (!migrated.isEmpty()) ctx.store().replaceAll(migrated);
        }
    }

    /** The small mutable session state a snapshot record holds (everything but the history). */
    static byte[] sessionStateBytes(SuiteContext ctx, SaveOptions o) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(ctx.scope());
        oos.writeObject(projectSettings(ctx.settings().snapshot()));
        oos.writeObject(ctx.sessions().snapshot());
        oos.writeObject(ctx.organizer().snapshot());
        List<opensuite.core.Issue> issues = new ArrayList<>();
        for (opensuite.core.Issue i : ctx.issues()) {
            if (o.inScopeOnly && !ctx.scope().isInScope(i.service(), i.path())) continue;
            issues.add(i);
        }
        oos.writeObject(issues);
        java.util.LinkedHashMap<String, java.io.Serializable> toolStates = new java.util.LinkedHashMap<>();
        for (opensuite.core.ToolModule t : ctx.tools()) {
            java.io.Serializable s = t.saveState();
            if (s != null) toolStates.put(t.name(), s);
        }
        oos.writeObject(toolStates);
        oos.writeObject(o.includeTasks ? new ArrayList<>(ctx.taskSnapshots()) : new ArrayList<>());
        oos.flush();
        return baos.toByteArray();
    }

    /**
     * Write every live entry (filtered by scope and tool, bodies slimmed) and a
     * session-state snapshot into {@code target}. The live entries are copied,
     * not moved, so the running session is never disturbed. WebSocket frames
     * are copied whole, like the history.
     */
    static void writeAllTo(SuiteContext ctx, ProjectStore target, SaveOptions o) throws IOException {
        for (LogEntry e : ctx.store().all()) {
            if (o.tools != null && !o.tools.contains(e.tool())) continue;
            if (o.inScopeOnly && !ctx.scope().isInScope(e)) continue;
            boolean drop = !o.keepAuditBodies && opensuite.core.ProjectOptions.AUDIT_TOOL.equals(e.tool());
            LogEntry rec = e.writtenTo(target, drop, o.bodyCapBytes);
            target.append(ProjectStore.ENTRY, rec.indexBytes());
        }
        for (WebSocketMessage m : ctx.wsStore().all()) {
            WebSocketMessage rec = m.writtenTo(target);
            target.append(ProjectStore.WS, rec.indexBytes());
        }
        target.append(ProjectStore.SNAPSHOT, sessionStateBytes(ctx, o));
    }

    /**
     * Open a project, routing to the single-file store format or, for a file
     * saved by an older build, the previous zip format.
     */
    public static int restore(SuiteContext ctx, File file) throws Exception {
        opening = file;
        installId(ctx.settings());
        if (ProjectStore.looksLikeStore(file)) return openV7(ctx, file);
        int n = restoreV6(ctx, file);
        // Migrate the old zip format to the single-file store in place and bind
        // the session to it, so the project opens disk-backed from now on and its
        // saves are the cheap incremental kind.
        try { bindNew(ctx, file, SaveOptions.fromSettings(ctx)); }
        catch (IOException e) { Debug.error("could not migrate project to the single-file format", e); }
        return n;
    }

    /**
     * Read the history out of a project file without opening it as the project:
     * nothing in the running project changes. The store is handed to
     * {@code keep} and must stay open for as long as the items are looked at,
     * since their bodies are read from it when wanted.
     */
    public static List<LogEntry> readHistory(File file, java.util.function.Consumer<java.io.Closeable> keep) throws Exception {
        if (!ProjectStore.looksLikeStore(file)) throw new IOException("Not an Open Suite project file.");
        ProjectStore store = new ProjectStore(file.toPath(), 8L * 1024 * 1024);
        keep.accept(store);
        java.util.LinkedHashMap<Integer, LogEntry> byNumber = new java.util.LinkedHashMap<>();
        store.scan((type, offset, data) -> {
            try {
                if (type == ProjectStore.ENTRY) {
                    LogEntry le = LogEntry.fromIndex(data, store);
                    byNumber.put(le.number(), le);
                } else if (type == ProjectStore.TOMBSTONE) {
                    byNumber.remove(((data[0] & 0xFF) << 24) | ((data[1] & 0xFF) << 16) | ((data[2] & 0xFF) << 8) | (data[3] & 0xFF));
                }
            } catch (Exception ex) {
                Debug.error("skipping a project record at " + offset + " that could not be read", ex);
            }
        });
        return new ArrayList<>(byNumber.values());
    }

    /**
     * Open a v7 single-file project: scan the record log to rebuild the history
     * index (reading only the small index records, seeking over the bodies) and
     * the latest session-state snapshot, then keep recording into the same file.
     */
    static int openV7(SuiteContext ctx, File file) throws Exception {
        ProjectStore store = new ProjectStore(file.toPath(), 32L * 1024 * 1024);
        java.util.LinkedHashMap<Integer, LogEntry> byNumber = new java.util.LinkedHashMap<>();
        List<WebSocketMessage> frames = new ArrayList<>();
        byte[][] snapshot = { null };
        int[] refused = { 0 };
        store.scan((type, offset, data) -> {
            try {
                if (type == ProjectStore.ENTRY) {
                    LogEntry le = LogEntry.fromIndex(data, store);
                    byNumber.put(le.number(), le);
                } else if (type == ProjectStore.TOMBSTONE) {
                    int n = ((data[0] & 0xFF) << 24) | ((data[1] & 0xFF) << 16)
                            | ((data[2] & 0xFF) << 8) | (data[3] & 0xFF);
                    byNumber.remove(n);
                } else if (type == ProjectStore.WS) {
                    frames.add(WebSocketMessage.fromIndex(data, store));
                } else if (type == ProjectStore.SNAPSHOT) {
                    snapshot[0] = data;
                }
            } catch (InvalidClassException ice) {
                // One record holding something a project file has no business holding:
                // nothing of it was created, so it is left out and the rest still opens.
                refused[0]++;
                Debug.error("skipped a project record at " + offset + " that contains a class not allowed in project files", ice);
            } catch (Exception ex) {
                Debug.error("skipping a corrupt project record at " + offset, ex);
            }
        });
        // The settings block is all or nothing: if any of it is refused the file is not opened at all.
        if (snapshot[0] != null) {
            try {
                ProjectObjectFilter.checkSnapshot(snapshot[0], 7);
            } catch (InvalidClassException ice) {
                try { store.close(); } catch (IOException ignore) {}
                throw ice;
            } catch (Exception other) {
                // Anything else is dealt with where the block is applied, as before.
            }
        }
        if (refused[0] > 0) {
            ctx.alert("suite", refused[0] + (refused[0] == 1 ? " record" : " records") + " in this project file contained data "
                    + "that is not allowed in project files and " + (refused[0] == 1 ? "was" : "were") + " excluded.");
        }
        List<LogEntry> entries = new ArrayList<>(byNumber.values());
        ctx.store().useStore(store);   // keep recording into this same file
        ctx.wsStore().useStore(store); // the WebSocket frames too
        ctx.setRestoring(true);
        try {
            ctx.store().replaceAll(entries);
            ctx.wsStore().replaceAll(frames);
            if (snapshot[0] != null) applySessionState(ctx, snapshot[0]);
            int max = 0;
            for (LogEntry le : entries) max = Math.max(max, le.number());
            LogEntry.setCounter(max);
            ctx.scopeChanged();
            ctx.siteMapReloaded(entries);
        } finally {
            ctx.setRestoring(false);
        }
        // Reclaim dead space (superseded index records, tombstoned bodies, old
        // snapshots) by rewriting the file compactly when it has grown well past
        // the live data, so a long-churning project does not bloat without bound.
        if (shouldCompact(file, entries)) {
            try { bindNew(ctx, file, SaveOptions.fromSettings(ctx)); }
            catch (IOException e) { Debug.error("compaction on open failed", e); }
        }
        return entries.size();
    }

    /** True when {@code file} holds enough dead space to be worth rewriting on open. */
    private static boolean shouldCompact(File file, List<LogEntry> entries) {
        long live = 0;
        for (LogEntry e : entries) live += e.bytes();
        long size = file.length();
        // Only for files large enough to matter, and only when more than half is dead.
        return size > 16L * 1024 * 1024 && size > live * 2 + 4L * 1024 * 1024;
    }

    // ---- trust (Settings > Suite > Startup behavior > Unrecognized project files) ----

    /** Marks the installation that saved a project; it travels in the file with the other settings. */
    public static final String INSTALL_ID = "suite.installId";
    public static final String ALWAYS_TRUST = "startup.trustProjects";
    private static final java.util.Set<String> TRUSTED_ONCE = java.util.concurrent.ConcurrentHashMap.newKeySet();

    /** This installation's mark, made the first time it is asked for. */
    public static String installId(opensuite.core.Settings s) {
        String id = s.get(INSTALL_ID, "");
        if (id.isEmpty()) { id = java.util.UUID.randomUUID().toString(); s.set(INSTALL_ID, id); }
        return id;
    }

    /** The owner chose to trust this file for the open that follows. */
    public static void trustOnce(File f) { if (f != null) TRUSTED_ONCE.add(f.getAbsolutePath()); }

    private static volatile File opening;

    /** Whether the settings a file brings are taken as they are: it was saved here, or the owner trusts it. */
    static boolean trusted(SuiteContext ctx, java.util.Map<String, String> saved) {
        File f = opening;
        boolean once = f != null && TRUSTED_ONCE.remove(f.getAbsolutePath());
        if (once || ctx.settings().getBool(ALWAYS_TRUST, true)) return true;
        String theirs = saved == null ? null : saved.get(INSTALL_ID);
        return theirs != null && theirs.equals(installId(ctx.settings()));
    }

    /**
     * What an untrusted file may still set: only what describes the project
     * itself. Everything that could make this machine do something (services,
     * paths, the browser, upstream proxies, hotkeys, session rules) stays as it is here.
     */
    static java.util.Map<String, String> harmless(java.util.Map<String, String> saved) {
        java.util.Map<String, String> out = new java.util.LinkedHashMap<>();
        if (saved == null) return out;
        for (java.util.Map.Entry<String, String> e : saved.entrySet()) {
            String k = e.getKey();
            if (k == null) continue;
            if (k.startsWith("project.") || k.equals(ProjectOptionsKeys.LOG_OUT_OF_SCOPE) || k.equals(ProjectOptionsKeys.OUT_OF_SCOPE_CHOICE)
                    || k.equals(ProjectOptionsKeys.SCOPE_ADVANCED)) out.put(k, e.getValue());
        }
        return out;
    }

    /**
     * The blocks with an "Override options for this project only" switch, by
     * the prefix their settings share. Each is a user-level block: its values
     * go into a project file, and come out of one, only while its switch is on.
     */
    static final String[] OVERRIDABLE = { "auth.", "upstream.", "socks.", "tls.client.", "oast." };

    /**
     * Settings that name files on this computer, and so never travel in a
     * project file: where extensions are loaded from and what they are run
     * with. A project file that could set these could have the next start run
     * a jar of its choosing.
     */
    static final String[] NEVER_IN_A_PROJECT = { "ext." };

    /** The settings a project file carries: everything, less the overridable blocks whose switch is off and the settings that stay with the computer. */
    static java.util.Map<String, String> projectSettings(java.util.Map<String, String> all) {
        java.util.Map<String, String> out = new java.util.LinkedHashMap<>();
        if (all == null) return out;
        for (java.util.Map.Entry<String, String> e : all.entrySet()) {
            String k = e.getKey();
            boolean dropped = staysHere(k);
            if (!dropped && k != null) for (String prefix : OVERRIDABLE) {
                if (k.startsWith(prefix) && !"true".equals(all.get(prefix + "overrideProject"))) { dropped = true; break; }
            }
            if (!dropped) out.put(k, e.getValue());
        }
        return out;
    }

    private static boolean staysHere(String key) {
        if (key == null) return false;
        for (String prefix : NEVER_IN_A_PROJECT) if (key.startsWith(prefix)) return true;
        return false;
    }

    private static final class ProjectOptionsKeys {
        static final String LOG_OUT_OF_SCOPE = opensuite.core.ProjectOptions.LOG_OUT_OF_SCOPE;
        static final String OUT_OF_SCOPE_CHOICE = opensuite.core.ProjectOptions.OUT_OF_SCOPE_CHOICE;
        static final String SCOPE_ADVANCED = opensuite.core.ProjectOptions.SCOPE_ADVANCED;
    }

    /** Restore a file's settings and session rules, in full if it is trusted and pared down if not. */
    private static void applySettings(SuiteContext ctx, java.util.Map<String, String> settings,
                                      opensuite.session.SessionManager.State session) {
        if (trusted(ctx, settings)) {
            // The mark of the installation that saved it is theirs, not ours.
            // A block the file does not override is left out, so this user's own values for it stand.
            java.util.Map<String, String> all = settings == null ? null : projectSettings(settings);
            if (all != null) all.remove(INSTALL_ID);
            ctx.settings().restore(all);
            if (session != null) ctx.sessions().restore(session);
        } else {
            ctx.settings().restore(harmless(settings));
            ctx.alert("suite", "This project file was saved by another installation and is not trusted: its history, scope and "
                    + "issues were loaded; its settings and session handling rules were not applied (Settings > Suite > Startup behavior).");
        }
        installId(ctx.settings());
    }

    /** Apply a session-state snapshot (everything but the history) to the context. */
    @SuppressWarnings("unchecked")
    static void applySessionState(SuiteContext ctx, byte[] block) throws Exception {
        Scope scope;
        java.util.Map<String, String> settings;
        opensuite.session.SessionManager.State session;
        java.util.List<opensuite.organizer.OrganizerItem> organizer;
        java.util.List<opensuite.core.Issue> issues;
        java.util.Map<String, java.io.Serializable> toolStates;
        java.util.List<opensuite.core.ScanTask.Snapshot> tasks;
        try (ObjectInputStream ois = ProjectObjectFilter.forSnapshot(new ByteArrayInputStream(block))) {
            scope = (Scope) ois.readObject();
            settings = (java.util.Map<String, String>) ois.readObject();
            session = (opensuite.session.SessionManager.State) ois.readObject();
            organizer = (java.util.List<opensuite.organizer.OrganizerItem>) ois.readObject();
            issues = (java.util.List<opensuite.core.Issue>) ois.readObject();
            toolStates = (java.util.Map<String, java.io.Serializable>) ois.readObject();
            tasks = (java.util.List<opensuite.core.ScanTask.Snapshot>) ois.readObject();
        }
        if (scope != null) {
            ctx.scope().include().clear();
            ctx.scope().include().addAll(scope.include());
            ctx.scope().exclude().clear();
            ctx.scope().exclude().addAll(scope.exclude());
        }
        applySettings(ctx, settings, session);
        if (organizer != null) ctx.organizer().restore(organizer);
        if (issues != null) ctx.restoreIssues(issues);
        if (tasks != null) ctx.restoreTasks(tasks);
        restoreToolStates(ctx, toolStates);
    }

    /**
     * Give every tool the state the file saved for it. One whose tool is not
     * registered, an extension that is not loaded yet or is not installed
     * here, is kept by the context until the tool registers rather than
     * dropped.
     */
    private static void restoreToolStates(SuiteContext ctx, java.util.Map<String, java.io.Serializable> toolStates) {
        if (toolStates == null) return;
        java.util.Map<String, ToolModule> byName = new java.util.HashMap<>();
        for (ToolModule t : ctx.tools()) byName.putIfAbsent(t.name(), t);
        for (java.util.Map.Entry<String, java.io.Serializable> saved : toolStates.entrySet()) {
            ToolModule t = byName.get(saved.getKey());
            if (t == null) {
                ctx.holdToolState(saved.getKey(), saved.getValue());
                continue;
            }
            // A tool puts its state back into its own components, so this is done
            // on the event thread. A project is read on a thread of its own, and a
            // tool filling a text box from there while the window laid itself out
            // could leave each waiting for the other, with the window frozen on
            // "Reading ...".
            Runnable put = () -> {
                try { t.restoreState(saved.getValue()); }
                catch (Exception ex) {
                    // Name the tool: a panel that comes up empty after a project
                    // opens is otherwise mystifying.
                    Debug.error("tool '" + t.name() + "' failed to restore its saved state", ex);
                }
            };
            if (SwingUtilities.isEventDispatchThread()) put.run();
            else {
                try { SwingUtilities.invokeAndWait(put); }
                catch (InterruptedException ex) { Thread.currentThread().interrupt(); return; }
                catch (java.lang.reflect.InvocationTargetException ex) {
                    Debug.error("tool '" + t.name() + "' failed to restore its saved state", ex.getCause());
                }
            }
        }
    }

    @SuppressWarnings("unchecked")
    static int restoreV6(SuiteContext ctx, File file) throws Exception {
        try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)))) {
            ZipEntry e = zis.getNextEntry();
            if (e == null) throw new IOException("Input file is not in correct format");
            ObjectInputStream ois = ProjectObjectFilter.forArchive(zis);
            int version = ois.readInt();
            if (version > 6) {
                ctx.alert("suite", "This file was saved by a later version - restore may fail");
            }
            List<LogEntry> entries = (List<LogEntry>) ois.readObject();
            Scope scope = (Scope) ois.readObject();
            java.util.Map<String, String> settings = (java.util.Map<String, String>) ois.readObject();
            opensuite.session.SessionManager.State session = null;
            if (version >= 2) {
                session = (opensuite.session.SessionManager.State) ois.readObject();
            }
            java.util.List<opensuite.organizer.OrganizerItem> organizer = null;
            if (version >= 3) {
                organizer = (java.util.List<opensuite.organizer.OrganizerItem>) ois.readObject();
            }
            java.util.List<opensuite.core.Issue> savedIssues = null;
            java.util.Map<String, java.io.Serializable> toolStates = null;
            if (version >= 4) {
                savedIssues = (java.util.List<opensuite.core.Issue>) ois.readObject();
                toolStates = (java.util.Map<String, java.io.Serializable>) ois.readObject();
            }
            java.util.List<opensuite.core.ScanTask.Snapshot> savedTasks = null;
            if (version >= 5) {
                savedTasks = (java.util.List<opensuite.core.ScanTask.Snapshot>) ois.readObject();
            }

            ctx.setRestoring(true);
            try {
            ctx.store().replaceAll(entries == null ? new ArrayList<>() : entries);
            if (scope != null) {
                ctx.scope().include().clear();
                ctx.scope().include().addAll(scope.include());
                ctx.scope().exclude().clear();
                ctx.scope().exclude().addAll(scope.exclude());
            }
            applySettings(ctx, settings, session);
            if (organizer != null) ctx.organizer().restore(organizer);
            if (savedIssues != null) ctx.restoreIssues(savedIssues);
            if (savedTasks != null) ctx.restoreTasks(savedTasks);
            restoreToolStates(ctx, toolStates);
            int max = 0;
            List<LogEntry> all = ctx.store().all();
            for (LogEntry le : all) max = Math.max(max, le.number());
            LogEntry.setCounter(max);
            ctx.scopeChanged();
            // One bulk rebuild of the site map, not one tree sync per entry.
            ctx.siteMapReloaded(all);
            return all.size();
            } finally {
                ctx.setRestoring(false);
            }
        }
    }

    /**
     * Restore off the event thread, with a small progress dialog, so a large
     * project never freezes the window. The UI fans the restored data out in
     * bulk on the event thread. {@code onDone} runs on the event thread with
     * the number of history items restored.
     */
    public static void restoreAsync(SuiteContext ctx, java.awt.Component parent, File file,
                                    java.util.function.IntConsumer onDone) {
        java.awt.Window owner = parent == null ? null : SwingUtilities.getWindowAncestor(parent);
        if (owner == null && parent instanceof java.awt.Window w) owner = w;
        final JDialog progress = new JDialog(owner, "Opening project", java.awt.Dialog.ModalityType.MODELESS);
        JProgressBar bar = new JProgressBar();
        bar.setIndeterminate(true);
        JLabel label = Ui.label("Reading " + file.getName() + " (" + (file.length() / (1024 * 1024)) + " MB)...");
        JPanel body = new JPanel(new java.awt.BorderLayout(0, 8));
        body.setBorder(Ui.pad(16, 20, 16, 20));
        body.add(label, java.awt.BorderLayout.NORTH);
        body.add(bar, java.awt.BorderLayout.CENTER);
        progress.setContentPane(body);
        progress.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        progress.pack();
        progress.setSize(Math.max(380, progress.getWidth()), progress.getHeight());
        progress.setLocationRelativeTo(owner);
        progress.setVisible(true);

        Thread t = new Thread(() -> {
            int n = -1;
            Exception failure = null;
            try { n = restore(ctx, file); } catch (Exception e) { failure = e; }
            final int count = n;
            final Exception err = failure;
            SwingUtilities.invokeLater(() -> {
                progress.dispose();
                if (err != null) {
                    JOptionPane.showMessageDialog(parent, "An error occurred: " + err.getMessage(),
                            "error", JOptionPane.ERROR_MESSAGE);
                } else if (onDone != null) {
                    onDone.accept(count);
                }
            });
        }, "project-restore");
        t.setDaemon(true);
        t.start();
    }
}