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.

8.9 KB
Raw Blame
package opensuite.core;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * The sites of one scan and how far each has got. A scan of several sites is
 * one task, and every site is in it from the start: one waiting its turn is
 * shown as waiting, not left out until the scan reaches it.
 */
public final class SiteProgress {

    public enum Status {
        WAITING("Waiting"), CRAWLING("Crawling"), QUEUED("Queued"), CRAWLED("Crawled"), AUDITING("Auditing"),
        FINISHED("Finished"), FAILED("Failed"), SKIPPED("Skipped"), STOPPED("Stopped");
        private final String label;
        Status(String label) { this.label = label; }
        public String label() { return label; }
        /** Whether nothing more will be done for a site in this state. */
        public boolean over() { return this == FINISHED || this == FAILED || this == SKIPPED || this == STOPPED; }
    }

    /** One site: its address ("http://host:port"), where its crawl starts, and its progress. */
    public static final class Site {
        private final String site, start;
        private volatile Status status = Status.WAITING;
        private volatile int locations;
        private volatile String note = "";
        private volatile boolean skip;
        private Site(String site, String start) { this.site = site; this.start = start; }
        public String site()     { return site; }
        public String start()    { return start; }
        public Status status()   { return status; }
        public int locations()   { return locations; }
        /** Why the site failed or was skipped, or what it is doing in more words; empty when there is nothing to add. */
        public String note()     { return note; }
        /** Whether the user asked for this site to be left out of the rest of the scan. */
        public boolean skipAsked() { return skip; }
        /** The site without its scheme, as a table shows it: "host" or "host:port". */
        public String host() {
            int i = site.indexOf("://");
            return i < 0 ? site : site.substring(i + 3);
        }
    }

    private final List<Site> sites = new CopyOnWriteArrayList<>();
    private volatile int version;

    /** Add a site in the order given. A site already there is not added again. */
    public synchronized Site add(String site, String start) {
        Site have = get(site);
        if (have != null) return have;
        Site s = new Site(site, start == null ? site : start);
        sites.add(s);
        version++;
        return s;
    }

    public Site get(String site) {
        for (Site s : sites) if (s.site.equalsIgnoreCase(site)) return s;
        return null;
    }

    public List<Site> all() { return new ArrayList<>(sites); }
    public int size() { return sites.size(); }
    /** Whether this is a scan of more than one site, the case a list of sites is worth showing for. */
    public boolean several() { return sites.size() > 1; }
    /** Goes up with every change, so a view can tell whether to draw again. */
    public int version() { return version; }

    public void set(String site, Status status) { set(site, status, null); }

    public void set(String site, Status status, String note) {
        Site s = get(site);
        if (s == null) return;
        s.status = status;
        if (note != null) s.note = note;
        version++;
    }

    public void locations(String site, int n) {
        Site s = get(site);
        if (s == null || n < 0 || s.locations == n) return;
        s.locations = n;
        version++;
    }

    /** Ask for a site to be left out of what remains of the scan. False when the site is already over. */
    public boolean skip(String site) {
        Site s = get(site);
        if (s == null || s.status.over()) return false;
        s.skip = true;
        // One that is only waiting has nothing to stop: it is skipped here and now.
        if (s.status == Status.WAITING || s.status == Status.QUEUED || s.status == Status.CRAWLED) { s.status = Status.SKIPPED; s.note = "Skipped, as asked"; }
        version++;
        return true;
    }

    /** Every site still under way is stopped where it is: the scan ended before reaching or finishing it. */
    public void stopRest() {
        for (Site s : sites) if (!s.status.over()) { s.status = Status.STOPPED; version++; }
    }

    public int count(Status status) {
        int n = 0;
        for (Site s : sites) if (s.status == status) n++;
        return n;
    }

    /**
     * Where the scan as a whole stands, in a few words, for the task's card:
     * the number of sites, then every state that has sites in it with how
     * many, so the counts always add up to the total and match the list of
     * sites row for row. "5 sites: 1 auditing, 1 crawling, 1 queued, 2
     * failed". A site that failed is said to have failed, never to be done.
     * Empty for a scan of one site, which the card already describes.
     */
    public String summary() {
        String[] parts = summaryParts();
        return parts[1].isEmpty() ? parts[0] : parts[0].endsWith(":") ? parts[0] + " " + parts[1] : parts[0] + ", " + parts[1];
    }

    /**
     * The summary in two halves: the sites and every state but failed, then
     * the sites that failed, which a card may show in another colour. Both
     * empty for a scan of one site.
     */
    public String[] summaryParts() {
        if (!several()) return new String[] {"", ""};
        int n = sites.size();
        // In the order the work goes, so the line reads from what is furthest on to what has not begun.
        Status[] order = {Status.FINISHED, Status.AUDITING, Status.CRAWLED, Status.CRAWLING, Status.QUEUED, Status.WAITING, Status.SKIPPED, Status.STOPPED};
        StringBuilder b = new StringBuilder(n + " sites:");
        boolean any = false;
        for (Status st : order) {
            int c = count(st);
            if (c == 0) continue;
            b.append(any ? ", " : " ").append(c).append(' ').append(st.label().toLowerCase(Locale.ROOT));
            any = true;
        }
        int failed = count(Status.FAILED);
        return new String[] {b.toString(), failed == 0 ? "" : failed + " failed"};
    }

    /**
     * The start addresses with repeats taken out, in the order given. Two are
     * the same when their scheme, host, port and path are: capitals in the
     * scheme and host make no difference, nor a default port written out, nor
     * a closing slash.
     */
    public static List<String> withoutRepeats(List<String> urls) {
        Set<String> seen = new LinkedHashSet<>();
        List<String> out = new ArrayList<>();
        for (String raw : urls) {
            if (raw == null || raw.isBlank()) continue;
            String url = raw.trim();
            if (seen.add(key(url))) out.add(url);
        }
        return out;
    }

    static String key(String url) {
        try {
            java.net.URI u = java.net.URI.create(url);
            String scheme = u.getScheme() == null ? "" : u.getScheme().toLowerCase(Locale.ROOT);
            String host = u.getHost() == null ? "" : u.getHost().toLowerCase(Locale.ROOT);
            if (host.isEmpty()) return url.toLowerCase(Locale.ROOT);
            int port = u.getPort();
            if (port < 0 || (port == 80 && scheme.equals("http")) || (port == 443 && scheme.equals("https"))) port = 0;
            String path = u.getRawPath() == null ? "" : u.getRawPath();
            while (path.endsWith("/")) path = path.substring(0, path.length() - 1);
            String query = u.getRawQuery() == null ? "" : "?" + u.getRawQuery();
            return scheme + "://" + host + (port == 0 ? "" : ":" + port) + path + query;
        } catch (RuntimeException e) {
            return url.toLowerCase(Locale.ROOT);
        }
    }

    /** The sites as text for a project file, one to a line. */
    public String save() {
        StringBuilder sb = new StringBuilder();
        for (Site s : sites)
            sb.append(s.site).append('\t').append(s.start).append('\t').append(s.status.name()).append('\t')
              .append(s.locations).append('\t').append(s.note.replace('\t', ' ').replace('\n', ' ')).append('\n');
        return sb.toString();
    }

    /** Take the sites from a project file. A site still under way when it was saved is not under way now. */
    public void load(String text) {
        sites.clear();
        if (text == null || text.isEmpty()) return;
        for (String line : text.split("\n")) {
            String[] f = line.split("\t", -1);
            if (f.length < 4) continue;
            Site s = new Site(f[0], f[1]);
            try { s.status = Status.valueOf(f[2]); } catch (IllegalArgumentException e) { s.status = Status.STOPPED; }
            if (!s.status.over()) s.status = Status.STOPPED;
            try { s.locations = Integer.parseInt(f[3]); } catch (NumberFormatException e) { /* none */ }
            if (f.length > 4) s.note = f[4];
            sites.add(s);
        }
        version++;
    }
}