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.

4.6 KB
Raw Blame
package opensuite.core;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.TreeMap;

/**
 * Notices when the window has stopped answering and writes down where every
 * thread of the program is at that moment, so a freeze leaves something to
 * work from. A small task runs on the window's own thread once a second; when
 * it has not run for several seconds, that thread is stuck.
 *
 * <p>What is written is where the program is in its own code, and nothing of
 * what it is working on: no addresses, requests or settings. The file goes to
 * {@code ~/.opensuite/logs/}.
 */
public final class FreezeWatch {

    static final long BEAT_MS = 1000, CHECK_MS = 2000, STUCK_MS = 6000;

    private static volatile long lastBeat;
    private static boolean started;

    private FreezeWatch() {}

    /** Begin watching. Called once the window is up. */
    public static synchronized void start() {
        if (started) return;
        started = true;
        lastBeat = System.currentTimeMillis();
        javax.swing.Timer beat = new javax.swing.Timer((int) BEAT_MS, e -> lastBeat = System.currentTimeMillis());
        beat.start();
        Thread t = new Thread(() -> {
            long lastCheck = System.currentTimeMillis();
            boolean told = false;
            long since = 0;
            while (true) {
                try { Thread.sleep(CHECK_MS); } catch (InterruptedException e) { return; }
                long now = System.currentTimeMillis();
                boolean stuck = stuck(now, lastBeat, lastCheck);
                lastCheck = now;
                if (stuck && !told) {
                    told = true;
                    since = lastBeat;
                    write(report(Thread.getAllStackTraces(), now - lastBeat));
                } else if (!stuck && told && now - lastBeat < STUCK_MS) {
                    told = false;
                    Debug.error("the window became responsive again after " + (now - since) / 1000 + " seconds", null);
                }
            }
        }, "freeze-watch");
        t.setDaemon(true);
        t.start();
    }

    /**
     * Whether the window's thread is stuck: its task is long overdue, and this
     * watcher has itself been running on time. A watcher that was held up too
     * (the machine was asleep, or everything was starved) proves nothing.
     */
    static boolean stuck(long now, long lastBeat, long lastCheck) {
        if (now - lastCheck > CHECK_MS * 3) return false;
        return now - lastBeat >= STUCK_MS;
    }

    /** Where every thread is, the window's own thread first. */
    static String report(Map<Thread, StackTraceElement[]> threads, long stuckForMs) {
        StringBuilder sb = new StringBuilder();
        sb.append("The window was unresponsive for ").append(stuckForMs / 1000).append(" seconds or more.\n");
        sb.append("Open Suite ").append(version()).append(", Java ").append(System.getProperty("java.version")).append("\n\n");
        Map<String, Map.Entry<Thread, StackTraceElement[]>> byName = new TreeMap<>();
        for (Map.Entry<Thread, StackTraceElement[]> e : threads.entrySet())
            byName.put((e.getKey().getName().startsWith("AWT-EventQueue") ? "0 " : "1 ") + e.getKey().getName() + " #" + e.getKey().getId(), e);
        for (Map.Entry<Thread, StackTraceElement[]> e : byName.values()) {
            if (e.getValue().length == 0) continue;
            sb.append('"').append(e.getKey().getName()).append("\" ").append(e.getKey().getState()).append('\n');
            for (StackTraceElement at : e.getValue()) sb.append("    at ").append(at).append('\n');
            sb.append('\n');
        }
        return sb.toString();
    }

    private static String version() {
        try { return opensuite.ui.Main.VERSION; } catch (Throwable t) { return "?"; }
    }

    private static void write(String report) {
        try {
            Path dir = logDir();
            Files.createDirectories(dir);
            Path f = dir.resolve("freeze-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss")) + ".txt");
            Files.write(f, report.getBytes(StandardCharsets.UTF_8));
            System.err.println("[freeze] the window became unresponsive; a thread dump was written to " + f);
        } catch (Exception e) {
            System.err.println("[freeze] the window became unresponsive, and the report could not be written: " + e);
        }
    }

    static Path logDir() { return Path.of(System.getProperty("user.home"), ".opensuite", "logs"); }
}