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.8 KB
Raw Blame
package opensuite.core;

import java.util.List;

/**
 * Tells an extension's code from the suite's own when it registers something.
 * The frames on the stack are walked for the first class loaded by an
 * {@link ExtensionCode} loader. This holds from any thread, the event thread
 * included, so a listener registered from one of the extension's own
 * components is still known to be its own.
 */
final class ExtensionCaller {

    private static final StackWalker WALKER =
            StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);

    private ExtensionCaller() {}

    /** The extension whose code is calling into the suite, or null when the caller is the suite's own code. */
    static ExtensionRunner calling() {
        return WALKER.walk(s -> s.map(StackWalker.StackFrame::getDeclaringClass)
                .map(Class::getClassLoader)
                .filter(ExtensionCode.class::isInstance)
                .map(l -> ((ExtensionCode) l).runner())
                .filter(r -> r != null)
                .findFirst()).orElse(null);
    }

    /**
     * {@code listener} as it goes onto {@code list}: itself, or for an
     * extension a stand-in that offers each call to the extension's thread.
     */
    static <T> T admit(List<T> list, Class<? super T> type, T listener) {
        ExtensionRunner r = calling();
        if (r == null) return listener;
        T standIn = r.standIn(type, listener);
        r.onUnload(() -> list.remove(standIn));
        return standIn;
    }

    /**
     * Take {@code listener} off {@code list}: the stand-in when an extension
     * registered it, since an extension only ever holds its own listener.
     */
    static <T> void withdraw(List<T> list, T listener) {
        ExtensionRunner r = calling();
        list.remove(r == null ? listener : r.standInFor(listener));
    }
}