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.

11.9 KB
Raw Blame
package opensuite.extensions;

import opensuite.core.HttpMessage;
import opensuite.core.HttpService;
import opensuite.core.SuiteContext;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

/**
 * An extension's thread. Nothing of an extension runs anywhere else: its
 * methods are called here, one at a time, and every event the suite raises for
 * it is offered here and returns to the caller at once. The queue is bounded,
 * so an extension that cannot keep up loses events, and is told so, rather than
 * holding a suite thread or growing memory without end. A thread that will not
 * stop is left running: it is interrupted, and waited for, but never stopped.
 */
final class ExtensionThread implements opensuite.core.ExtensionRunner {

    /** How many events may wait for the extension. */
    static final int QUEUE_LIMIT = 256;
    /** A dropped event is reported at the first drop, then at every this many after it. */
    static final long DROP_ALERT_EVERY = 1000;

    /** What came of a call the suite waited for. */
    record Attempt<T>(T value, boolean timedOut, boolean failed) {
        boolean ok() { return !timedOut && !failed; }
    }

    private final LoadedExtension ext;
    private final SuiteContext ctx;
    private final AtomicReference<String> threadName;
    private final AtomicReference<Thread> worker = new AtomicReference<>();
    private final ThreadPoolExecutor executor;
    private final IdentityHashMap<Object, Object> standIns = new IdentityHashMap<>();
    private final List<Runnable> undos = new CopyOnWriteArrayList<>();
    private final AtomicLong dropped = new AtomicLong();
    // Set while a drop is being reported: the report itself raises an event,
    // which may be dropped in its turn, and that must not report again.
    private final AtomicBoolean reporting = new AtomicBoolean();
    private final AtomicLong events = new AtomicLong();
    private volatile boolean paused;
    // The event on the thread now, and when it started; 0 for none.
    private volatile long runningEvent;
    private volatile long runningSince;
    /** Run on the extension's thread when it ends, which may be long after the extension was removed. */
    volatile Runnable onTerminated;

    ExtensionThread(LoadedExtension ext, SuiteContext ctx) {
        this.ext = ext;
        this.ctx = ctx;
        this.threadName = new AtomicReference<>("opensuite-ext-" + LoadedExtension.baseName(ext.file));
        this.executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(QUEUE_LIMIT), r -> {
                    Thread t = new Thread(r, threadName.get());
                    t.setDaemon(true);
                    // The extension's loader is this thread's context loader for as long as it lives. No suite thread has its context loader changed.
                    t.setContextClassLoader(ext.loader);
                    worker.set(t);
                    return t;
                }) {
            @Override protected void terminated() {
                Runnable after = onTerminated;
                if (after != null) after.run();
            }
        };
    }

    String threadName() { return threadName.get(); }
    Thread worker() { return worker.get(); }

    /** Name the thread for the extension, once its own name is known. */
    void rename(String name) {
        threadName.set("opensuite-ext-" + name);
        Thread t = worker.get();
        if (t != null) t.setName(threadName.get());
    }

    // ---- events ----

    @Override public void offer(Runnable call) {
        if (paused) { drop(); return; }
        if (executor.isShutdown()) return;
        try { executor.execute(() -> runEvent(call)); }
        catch (RejectedExecutionException notTaken) {
            if (executor.isShutdown()) return;
            drop();
        }
    }

    private void runEvent(Runnable call) {
        long id = events.incrementAndGet();
        runningEvent = id;
        runningSince = System.nanoTime();
        try { asExtension(call); }
        finally { runningEvent = 0; }
    }

    /** Run extension code with the extension's loader as the context loader, and put the context loader back afterwards. */
    private void asExtension(Runnable call) {
        Thread t = Thread.currentThread();
        ClassLoader before = t.getContextClassLoader();
        t.setContextClassLoader(ext.loader);
        try { call.run(); }
        catch (Throwable e) { ext.error("an event it was offered threw", e); }
        finally { t.setContextClassLoader(before); }
    }

    private void drop() {
        long n = dropped.incrementAndGet();
        if (n != 1 && (n - 1) % DROP_ALERT_EVERY != 0) return;
        String said = n + " events have been dropped" + (paused ? " while it is paused" : " because it is not keeping up") + ".";
        ext.errors.line(said);
        if (!reporting.compareAndSet(false, true)) return;
        try { ctx.alert("extensions", "Extension " + ext.name + ": " + said); }
        finally { reporting.set(false); }
    }

    // ---- calls the suite waits for ----

    /**
     * Call the extension and wait at most {@code limitMillis}. The call runs on
     * the extension's thread whatever thread is waiting. A call that is not
     * done in time is taken back if it has not started and interrupted if it
     * has; the thread itself is never stopped.
     */
    <T> Attempt<T> call(String label, Callable<T> body, long limitMillis) {
        FutureTask<T> task = new FutureTask<>(() -> {
            Thread t = Thread.currentThread();
            ClassLoader before = t.getContextClassLoader();
            t.setContextClassLoader(ext.loader);
            try { return body.call(); }
            finally { t.setContextClassLoader(before); }
        });
        if (executor.isShutdown()) return new Attempt<>(null, false, true);
        try { executor.execute(task); }
        catch (RejectedExecutionException notTaken) { return new Attempt<>(null, false, true); }
        try {
            return new Attempt<>(task.get(limitMillis, TimeUnit.MILLISECONDS), false, false);
        } catch (TimeoutException e) {
            executor.remove(task);
            task.cancel(true);
            ext.error(label + " did not finish in " + limitMillis + " ms", null);
            return new Attempt<>(null, true, false);
        } catch (ExecutionException e) {
            ext.error(label + " threw", e.getCause() == null ? e : e.getCause());
            return new Attempt<>(null, false, true);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return new Attempt<>(null, false, true);
        }
    }

    // ---- what the extension registers ----

    @Override public <T> T standIn(Class<? super T> type, T listener) {
        Object standIn = Proxy.newProxyInstance(loaderOf(type), new Class<?>[]{type},
                new Offers(listener, type.getSimpleName()));
        synchronized (standIns) { standIns.put(listener, standIn); }
        @SuppressWarnings("unchecked") T typed = (T) standIn;
        return typed;
    }

    @Override public <T> T standInFor(T listener) {
        synchronized (standIns) {
            @SuppressWarnings("unchecked") T typed = (T) standIns.get(listener);
            return typed;
        }
    }

    @Override public SuiteContext.MessageSink sink(SuiteContext.MessageSink sink) {
        // Read here and now, on the extension's own thread, since the menus ask for it without waiting.
        boolean single = false;
        try { single = sink.singleItem(); }
        catch (Throwable t) { ext.error("singleItem() threw", t); }
        final boolean takesOne = single;
        SuiteContext.MessageSink standIn = new SuiteContext.MessageSink() {
            @Override public void receive(HttpService svc, HttpMessage req, HttpMessage resp, String caption) {
                offer(() -> {
                    try { sink.receive(svc, req, resp, caption); }
                    catch (Throwable t) { ext.error("its sink threw on a message sent to it", t); }
                });
            }
            @Override public boolean singleItem() { return takesOne; }
        };
        synchronized (standIns) { standIns.put(sink, standIn); }
        return standIn;
    }

    @Override public void onUnload(Runnable undo) { undos.add(undo); }

    /** Take every stand-in off the suite's lists. Those lists are safe to change from the thread that calls this. */
    void unregisterEverything() {
        for (Runnable undo : undos) {
            try { undo.run(); }
            catch (Throwable t) { ext.error("taking something it had registered off a suite list failed", t); }
        }
        undos.clear();
        synchronized (standIns) { standIns.clear(); }
    }

    /** How many registrations of the extension are still to be undone. */
    int registrations() { return undos.size(); }

    // ---- watchdog ----

    /** How long the event on the thread now has been running, or 0 when none is. */
    long runningMillis() {
        long id = runningEvent;
        return id == 0 ? 0 : TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - runningSince);
    }

    /** Pause events: one has run for too long. They stay paused until the owner resumes the extension. */
    void pause() { paused = true; }

    /** Take events again, and start the time limit over for an event still running. The count of drops stands since the extension loaded. */
    void resume() {
        paused = false;
        if (runningEvent != 0) runningSince = System.nanoTime();
    }

    boolean isPaused() { return paused; }
    long droppedEvents() { return dropped.get(); }

    // ---- lifecycle ----

    void shutdownNow() { executor.shutdownNow(); }

    boolean awaitTermination(long millis) throws InterruptedException {
        return executor.awaitTermination(millis, TimeUnit.MILLISECONDS);
    }

    boolean isAlive() {
        Thread t = worker.get();
        return t != null && t.isAlive();
    }

    private static ClassLoader loaderOf(Class<?> type) {
        ClassLoader l = type.getClassLoader();
        return l != null ? l : ExtensionThread.class.getClassLoader();
    }

    /** Answers for a listener the extension registered: each call is offered to the extension and the caller returns at once. */
    private final class Offers implements InvocationHandler {
        private final Object target;
        private final String kind;
        Offers(Object target, String kind) { this.target = target; this.kind = kind; }

        @Override public Object invoke(Object proxy, Method method, Object[] args) {
            // A stand-in is its own object on a suite list: it is found and removed by identity.
            if (method.getDeclaringClass() == Object.class) {
                return switch (method.getName()) {
                    case "equals" -> proxy == args[0];
                    case "hashCode" -> System.identityHashCode(proxy);
                    default -> "a stand-in for a " + kind + " of extension " + ext.name;
                };
            }
            offer(() -> {
                try { method.invoke(target, args); }
                catch (InvocationTargetException e) { ext.error("its " + kind + " callback threw", e.getCause()); }
                catch (ReflectiveOperationException e) { ext.error("its " + kind + " callback could not be called", e); }
            });
            return null;
        }
    }
}