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.

14.5 KB
Raw Blame
package opensuite.ui;

import java.util.Locale;
import java.util.Set;

/**
 * Pretty-printing for the Pretty view of a read-only message: JSON and markup
 * bodies are re-indented for reading, the way the reference shows them. Only
 * the text on screen changes; the message bytes are untouched, and an editable
 * message is never reformatted, because its Pretty view is what gets sent.
 *
 * <p>Pure text functions, so they are unit tested. Each one returns its input
 * unchanged when the body is not what it expects, so a malformed body is shown
 * as it arrived instead of being mangled.
 */
public final class PrettyPrint {
    private PrettyPrint() {}

    /** Bodies above this size are shown as they arrived: formatting them is slow and nobody reads them whole. */
    static final int MAX_CHARS = 400_000;

    /**
     * Break lines longer than {@code max} into display lines. This is Pretty
     * view formatting only: the message bytes are untouched, and Raw still
     * shows them as they are. A minified body can be one line of hundreds of
     * kilobytes, which Swing's paragraph views measure quadratically.
     */
    public static String wrapLongLines(String text, int max) {
        if (text == null || max <= 0 || text.length() <= max) return text;
        StringBuilder out = new StringBuilder(text.length() + text.length() / max + 16);
        int chars = 0;
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            out.append(c);
            if (c == '\r' || c == '\n') { chars = 0; continue; }
            if (++chars >= max) {
                // Do not add a blank line before a line ending that is already there.
                boolean ending = i + 1 < text.length() && (text.charAt(i + 1) == '\r' || text.charAt(i + 1) == '\n');
                if (!ending) out.append('\n');
                chars = 0;
            }
        }
        return out.toString();
    }

    private static final String INDENT = "  ";

    /** Reformat a whole message: the head is kept, the body is pretty-printed by content type. */
    public static String message(String text, String contentType) {
        if (text == null || text.length() > MAX_CHARS) return text;
        int sep = text.indexOf("\r\n\r\n");
        int len = 4;
        if (sep < 0) { sep = text.indexOf("\n\n"); len = 2; }
        if (sep < 0) return text;
        String head = text.substring(0, sep + len);
        String body = text.substring(sep + len);
        if (body.isBlank()) return text;
        String ct = contentType == null ? "" : contentType.toLowerCase(Locale.ROOT);
        String trimmed = body.trim();
        String out;
        if (ct.contains("json") || trimmed.startsWith("{") || trimmed.startsWith("[")) out = json(body);
        else if (ct.contains("html") || ct.contains("xml") || trimmed.startsWith("<")) out = markup(body);
        else return text;
        // A body that ended its last line still does: the line after it stays.
        if (out != null && !out.equals(body) && body.endsWith("\n") && !out.endsWith("\n")) out += "\n";
        return head + out;
    }

    /**
     * Which line of the message each line of its pretty form came from, so the
     * gutter can number the message's own lines and leave the lines the
     * formatting added without a number: entry {@code i} is the 1-based source
     * line that pretty line {@code i} begins, or 0 where it continues one
     * already numbered. Null when the two are the same text, or when they
     * differ in more than white space and no such account can be given.
     */
    public static int[] sourceLines(String raw, String pretty) {
        if (raw == null || pretty == null) return null;
        String r = raw.replace("\r\n", "\n"), p = pretty.replace("\r\n", "\n");
        if (r.equals(p)) return null;
        String[] rawLines = r.split("\n", -1), lines = p.split("\n", -1);
        int[] out = new int[lines.length];
        int ri = 0, rline = 1, cur = 0, last = 0;
        for (int k = 0; k < lines.length; k++) {
            String line = lines[k];
            boolean begun = false;
            for (int j = 0; j < line.length(); j++) {
                char c = line.charAt(j);
                if (Character.isWhitespace(c)) continue;
                while (ri < r.length() && Character.isWhitespace(r.charAt(ri))) { if (r.charAt(ri) == '\n') rline++; ri++; }
                if (ri >= r.length() || r.charAt(ri) != c) return null;
                if (!begun) {
                    begun = true;
                    if (rline > last) { out[k] = rline; last = rline; }
                }
                ri++;
                cur = rline;
            }
            if (!begun) {
                // An empty line is the source's own when the next source line is empty too.
                int next = cur + 1;
                if (next > last && next <= rawLines.length && rawLines[next - 1].isBlank()) { out[k] = next; last = next; cur = next; }
            }
        }
        return out;
    }

    /**
     * Re-indent JSON: one member per line, two spaces a level, no space after
     * the colon. Returns the input unchanged if the brackets do not balance.
     */
    public static String json(String body) {
        if (body == null) return null;
        String s = body.trim();
        if (s.isEmpty() || (s.charAt(0) != '{' && s.charAt(0) != '[')) return body;
        StringBuilder out = new StringBuilder(s.length() + s.length() / 4);
        int depth = 0;
        boolean inString = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (inString) {
                out.append(c);
                if (c == '\\' && i + 1 < s.length()) out.append(s.charAt(++i));
                else if (c == '"') inString = false;
                continue;
            }
            switch (c) {
                case '"' -> { inString = true; out.append(c); }
                case '{', '[' -> {
                    out.append(c);
                    int next = skipSpace(s, i + 1);
                    if (next < s.length() && (s.charAt(next) == '}' || s.charAt(next) == ']')) {
                        // An empty object or array still opens and closes on its own lines, as the reference shows it.
                        newline(out, depth);
                        out.append(s.charAt(next));
                        i = next;
                    } else {
                        depth++;
                        newline(out, depth);
                    }
                }
                case '}', ']' -> {
                    depth--;
                    if (depth < 0) return body;
                    newline(out, depth);
                    out.append(c);
                }
                case ',' -> { out.append(c); newline(out, depth); }
                case ':' -> out.append(c);
                default -> { if (!Character.isWhitespace(c)) out.append(c); }
            }
        }
        if (depth != 0 || inString) return body;
        return out.toString();
    }

    private static int skipSpace(String s, int i) {
        while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
        return i;
    }

    private static void newline(StringBuilder out, int depth) {
        out.append('\n');
        for (int i = 0; i < depth; i++) out.append(INDENT);
    }

    private static final Set<String> VOID = Set.of("area", "base", "br", "col", "embed", "hr", "img", "input",
            "link", "meta", "param", "source", "track", "wbr");
    private static final Set<String> RAW_TEXT = Set.of("script", "style");

    /**
     * Re-indent HTML or XML: each tag on its own line, two spaces a level, text
     * between tags on a line of its own. Script content is kept as written; a
     * style sheet is set out one declaration to a line. The document's first line keeps its declaration and root tag
     * together, as the reference does.
     */
    public static String markup(String body) {
        if (body == null) return null;
        String s = body.trim();
        if (s.isEmpty() || s.charAt(0) != '<') return body;
        StringBuilder out = new StringBuilder(s.length() + s.length() / 3);
        int depth = 0;
        int i = 0;
        boolean first = true;
        boolean afterDeclaration = false;
        while (i < s.length()) {
            if (s.charAt(i) == '<') {
                int end;
                boolean comment = s.startsWith("<!--", i);
                if (comment) {
                    end = s.indexOf("-->", i);
                    end = end < 0 ? s.length() : end + 3;
                } else {
                    end = tagEnd(s, i);
                }
                String tag = s.substring(i, end);
                String name = tagName(tag);
                boolean closing = tag.startsWith("</");
                boolean declaration = tag.startsWith("<!") || tag.startsWith("<?");
                boolean selfClosing = tag.endsWith("/>") || declaration || comment || VOID.contains(name);
                if (closing) depth = Math.max(0, depth - 1);
                if (first) first = false;
                else if (afterDeclaration) { /* the root tag stays on the declaration's line */ }
                else newline(out, depth);
                out.append(tag);
                afterDeclaration = declaration && !comment && out.indexOf("\n") < 0;
                i = end;
                if (!closing && !selfClosing) {
                    depth++;
                    if (RAW_TEXT.contains(name)) {
                        // Keep script and style content as written, indented as one block.
                        int close = indexOfIgnoreCase(s, "</" + name, i);
                        if (close < 0) close = s.length();
                        String raw = s.substring(i, close).strip();
                        if (!raw.isEmpty() && name.equals("style")) {
                            css(raw, out, depth);
                        } else if (!raw.isEmpty()) {
                            for (String line : raw.split("\r?\n")) {
                                newline(out, depth);
                                out.append(line.strip());
                            }
                        }
                        i = close;
                    }
                }
            } else {
                int next = s.indexOf('<', i);
                if (next < 0) next = s.length();
                String text = s.substring(i, next).strip();
                if (!text.isEmpty()) {
                    afterDeclaration = false;
                    newline(out, depth);
                    out.append(text.replaceAll("\\s*\r?\n\\s*", " "));
                }
                i = next;
            }
        }
        return out.toString();
    }

    /**
     * A style sheet set out as the reference sets it out: the selector and its
     * opening brace on one line, one declaration to a line inside, the closing
     * brace on its own. Strings, comments and bracketed values are passed
     * through whole, and the space inside a value is kept, so what is shown
     * still means what was sent.
     */
    static void css(String raw, StringBuilder out, int depth) {
        int level = 0;
        StringBuilder line = new StringBuilder();
        int n = raw.length();
        for (int i = 0; i < n; i++) {
            char c = raw.charAt(i);
            if (c == '"' || c == '\'') {
                int j = i + 1;
                while (j < n && raw.charAt(j) != c) j += raw.charAt(j) == '\\' ? 2 : 1;
                j = Math.min(n, j + 1);
                line.append(raw, i, j);
                i = j - 1;
            } else if (c == '/' && i + 1 < n && raw.charAt(i + 1) == '*') {
                int j = raw.indexOf("*/", i + 2);
                j = j < 0 ? n : j + 2;
                line.append(raw, i, j);
                i = j - 1;
            } else if (c == '(') {
                // url(...) and the like: taken whole, so a ; or } inside is not a break.
                int open = 1, j = i + 1;
                while (j < n && open > 0) {
                    char d = raw.charAt(j);
                    if (d == '(') open++; else if (d == ')') open--;
                    j++;
                }
                line.append(raw.substring(i, j).replaceAll("\\s*\r?\n\\s*", " "));
                i = j - 1;
            } else if (c == '{') {
                cssLine(out, depth + level, line, "{");
                level++;
            } else if (c == ';') {
                cssLine(out, depth + level, line, ";");
            } else if (c == '}') {
                if (!line.toString().isBlank()) cssLine(out, depth + level, line, "");
                level = Math.max(0, level - 1);
                line.setLength(0);
                cssLine(out, depth + level, line, "}");
            } else if (Character.isWhitespace(c)) {
                // Runs of space collapse to one; none is kept at the start of a line or after a colon or comma.
                int len = line.length();
                if (len > 0 && " :,".indexOf(line.charAt(len - 1)) < 0) line.append(' ');
            } else {
                if ((c == ':' || c == ',') && line.length() > 0 && line.charAt(line.length() - 1) == ' ' && level > 0) line.setLength(line.length() - 1);
                line.append(c);
            }
        }
        if (!line.toString().isBlank()) cssLine(out, depth + level, line, "");
    }

    private static void cssLine(StringBuilder out, int depth, StringBuilder line, String end) {
        String text = line.toString().strip();
        line.setLength(0);
        if (text.isEmpty() && end.isEmpty()) return;
        // A lone ; after a closing brace adds nothing.
        if (text.isEmpty() && end.equals(";")) return;
        newline(out, depth);
        out.append(text).append(end);
    }

    /** One past the closing {@code >} of the tag starting at {@code from}, honouring quoted attribute values. */
    private static int tagEnd(String s, int from) {
        char quote = 0;
        for (int i = from + 1; i < s.length(); i++) {
            char c = s.charAt(i);
            if (quote != 0) { if (c == quote) quote = 0; }
            else if (c == '"' || c == '\'') quote = c;
            else if (c == '>') return i + 1;
        }
        return s.length();
    }

    private static String tagName(String tag) {
        int i = tag.startsWith("</") ? 2 : 1;
        int j = i;
        while (j < tag.length() && (Character.isLetterOrDigit(tag.charAt(j)) || tag.charAt(j) == '-' || tag.charAt(j) == ':')) j++;
        return tag.substring(i, j).toLowerCase(Locale.ROOT);
    }

    private static int indexOfIgnoreCase(String s, String needle, int from) {
        return s.toLowerCase(Locale.ROOT).indexOf(needle.toLowerCase(Locale.ROOT), from);
    }
}