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.

1.9 KB
Raw Blame
package opensuite.script;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;

/**
 * Runs a script on a thread of its own within a time limit. At the limit, or
 * on a stop, the thread is interrupted; one that ignores that cannot be
 * ended, so it is left running and counted.
 */
final class ScriptRunner {

    static final int MAX_ABANDONED = 3;
    private static final long GRACE_MILLIS = 1000;

    enum Outcome { DONE, TIMEOUT, STOPPED }

    private final long timeoutMillis;
    private volatile int abandoned;

    ScriptRunner(long timeoutMillis) { this.timeoutMillis = timeoutMillis; }

    long timeoutMillis() { return timeoutMillis; }

    /** Scripts that were stopped but would not end. */
    int abandoned() { return abandoned; }

    /** Run {@code body} and wait for it, until the limit or until {@code stopped} is true. */
    Outcome run(Runnable body, BooleanSupplier stopped) {
        CountDownLatch done = new CountDownLatch(1);
        Thread t = new Thread(() -> {
            try { body.run(); } finally { done.countDown(); }
        }, "opensuite-script");
        t.setDaemon(true);
        t.start();

        long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
        try {
            while (!done.await(25, TimeUnit.MILLISECONDS)) {
                boolean stop = stopped.getAsBoolean();
                if (stop || System.nanoTime() >= deadline) {
                    t.interrupt();
                    if (!done.await(GRACE_MILLIS, TimeUnit.MILLISECONDS)) abandoned++;
                    return stop ? Outcome.STOPPED : Outcome.TIMEOUT;
                }
            }
        } catch (InterruptedException e) {
            t.interrupt();
            Thread.currentThread().interrupt();
            return Outcome.STOPPED;
        }
        return Outcome.DONE;
    }
}