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.

39.9 KB
Raw Blame
package opensuite.repeater;

import opensuite.core.*;
import opensuite.ui.*;

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.atomic.AtomicInteger;

/** Manual request editing and reissue, one numbered tab per request. */
public class RepeaterTool implements ToolModule {

    private SuiteContext ctx;
    private final JTabbedPane tabs = new JTabbedPane();
    private final AtomicInteger counter = new AtomicInteger(0);

    public RepeaterTool() {}

    /** Each exchange as its request, a blank line, its response, and a line of equals signs between exchanges. */
    static void writeHistory(java.util.List<byte[][]> exchanges, java.io.OutputStream out) throws java.io.IOException {
        byte[] gap = "\n\n".getBytes(java.nio.charset.StandardCharsets.US_ASCII);
        byte[] rule = "======================================================\n".getBytes(java.nio.charset.StandardCharsets.US_ASCII);
        for (int i = 0; i < exchanges.size(); i++) {
            if (i > 0) { out.write(gap); out.write(rule); }
            out.write(exchanges.get(i)[0]);
            if (exchanges.get(i)[1] != null) { out.write(gap); out.write(exchanges.get(i)[1]); }
        }
    }

    @Override public String name() { return "repeater"; }

    @Override public void init(SuiteContext ctx) {
        this.ctx = ctx;
        ctx.registerSink("repeater", (svc, req, resp, cap) ->
            SwingUtilities.invokeLater(() -> newTab(svc, req, cap)));
        SettingsDialog.register("Repeater", () -> new RepeaterSettingsPanel(ctx.settings()));
        opensuite.ui.TabStrip.tabMenu(tabs, this::tabMenu, c -> renameTab(tabs.indexOfComponent(c)));
        // Remember a closed tab's request so it can be reopened.
        tabs.addContainerListener(new java.awt.event.ContainerAdapter() {
            @Override public void componentRemoved(java.awt.event.ContainerEvent e) {
                if (restoring || !(e.getChild() instanceof RepeaterTab t)) return;
                closed.push(new Closed(t.service(), t.reqEditor.bytes()));
                while (closed.size() > 20) closed.removeLast();
            }
        });
    }

    /** A closed tab's target and request, kept so the tab can be reopened. */
    private record Closed(HttpService svc, byte[] request) {}
    private final java.util.ArrayDeque<Closed> closed = new java.util.ArrayDeque<>();
    private boolean restoring;

    private void renameTab(int i) {
        if (i < 0) return;
        String name = JOptionPane.showInputDialog(ctx.frame(), "Enter the new tab name", tabs.getTitleAt(i));
        if (name != null && !name.isBlank()) opensuite.ui.TabStrip.rename(tabs, i, name.trim());
    }

    private void reopenClosed() {
        Closed c = closed.poll();
        if (c != null) newTab(c.svc(), new HttpMessage(c.request()), null);
    }

    /** Every request tab, in order (the "+" tab is not one). */
    private java.util.List<RepeaterTab> requestTabs() {
        java.util.List<RepeaterTab> out = new java.util.ArrayList<>();
        for (int i = 0; i < tabs.getTabCount(); i++) {
            if (tabs.getComponentAt(i) instanceof RepeaterTab t) out.add(t);
        }
        return out;
    }

    private void closeTabs(java.util.function.Predicate<RepeaterTab> which) {
        for (RepeaterTab t : requestTabs()) {
            if (which.test(t) && opensuite.ui.TabStrip.count(tabs) > 1) tabs.remove(t);
        }
    }

    /**
     * Send every tab's request one after another, each on its own connection,
     * waiting for a response before the next is sent. This is what a multi-step
     * process (log in, then act) needs.
     */
    private void sendAllInSequence() {
        java.util.List<RepeaterTab> all = requestTabs();
        Thread t = new Thread(() -> {
            for (RepeaterTab tab : all) {
                try {
                    SwingUtilities.invokeAndWait(tab::send);
                    Thread w = tab.worker;
                    if (w != null) w.join();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                } catch (Exception e) {
                    Debug.log("repeater sequence: " + e);
                }
            }
        }, "repeater-sequence");
        t.setDaemon(true);
        t.start();
    }

    /** Send every tab's request at the same moment, each on its own connection. */
    private void sendAllInParallel() {
        for (RepeaterTab tab : requestTabs()) tab.send();
    }

    /** The right-click menu of one tab's header. */
    private JPopupMenu tabMenu(Component c) {
        JPopupMenu m = new JPopupMenu();
        if (!(c instanceof RepeaterTab tab)) return m;
        int index = tabs.indexOfComponent(tab);
        add(m, "Rename tab", () -> renameTab(index));
        add(m, "Duplicate tab", () -> newTab(tab.service(), new HttpMessage(tab.reqEditor.bytes()), null));
        m.addSeparator();
        add(m, "Send all tabs in sequence (separate connections)", this::sendAllInSequence);
        add(m, "Send all tabs in parallel", this::sendAllInParallel);
        m.addSeparator();
        JMenuItem close = add(m, "Close tab", () -> closeTabs(t -> t == tab));
        JMenuItem others = add(m, "Close other tabs", () -> closeTabs(t -> t != tab));
        JMenuItem left = add(m, "Close tabs to the left",
                () -> closeTabs(t -> tabs.indexOfComponent(t) < tabs.indexOfComponent(tab)));
        JMenuItem right = add(m, "Close tabs to the right",
                () -> closeTabs(t -> tabs.indexOfComponent(t) > tabs.indexOfComponent(tab)));
        JMenuItem reopen = add(m, "Reopen closed tab", this::reopenClosed);
        boolean many = opensuite.ui.TabStrip.count(tabs) > 1;
        close.setEnabled(many);
        others.setEnabled(many);
        left.setEnabled(index > 0);
        right.setEnabled(index < requestTabs().size() - 1);
        reopen.setEnabled(!closed.isEmpty());
        return m;
    }

    private static JMenuItem add(JPopupMenu m, String text, Runnable action) {
        JMenuItem mi = new JMenuItem(text);
        mi.setFont(Ui.PLAIN);
        mi.addActionListener(e -> action.run());
        m.add(mi);
        return mi;
    }

    @Override public Tab[] tabs() {
        tabs.setFont(Ui.PLAIN);
        // Before anything has been sent here the page that says how to begin is in front.
        boolean fresh = tabs.getTabCount() == 0 && ctx != null && !ctx.settings().getBool(INTRO_HIDDEN, false);
        if (tabs.getTabCount() == 0) newBlankTab();
        pages.setOpaque(false);
        pages.add(opensuite.ui.TabStrip.wrap(tabs, () -> newBlankTab()), "tabs");
        pages.add(new opensuite.ui.ToolIntro("Repeater",
                "Modify and resend individual requests to test how the server's response changes based on your input.",
                opensuite.ui.ToolIntro.arrows(), 51, 268, this::closeIntro, () -> {
            ctx.settings().setBool(INTRO_HIDDEN, true);
            closeIntro();
        }), "intro");
        introShown = fresh;
        pageCards.show(pages, fresh ? "intro" : "tabs");
        return new Tab[]{ new Tab("repeater", pages) };
    }

    /** Set once "Don't show this again" is chosen on the Repeater's first page. */
    static final String INTRO_HIDDEN = "repeater.introHidden";
    private final CardLayout pageCards = new CardLayout();
    private final JPanel pages = new JPanel(pageCards);
    private boolean introShown;

    /** Put the tabs in front; anything that arrives in the Repeater does this too. */
    private void closeIntro() {
        if (!introShown) return;
        introShown = false;
        pageCards.show(pages, "tabs");
    }

    @Override public java.io.Serializable saveState() {
        java.util.ArrayList<TabState> out = new java.util.ArrayList<>();
        for (int i = 0; i < tabs.getTabCount(); i++) {
            if (tabs.getComponentAt(i) instanceof RepeaterTab rt) {
                TabState s = new TabState();
                s.title = tabs.getTitleAt(i);
                s.host = rt.hostField.getText();
                try { s.port = Integer.parseInt(rt.portField.getText().trim()); } catch (Exception e) { s.port = 80; }
                s.secure = rt.sslBox.isSelected();
                s.req = rt.reqEditor.message().raw();
                s.resp = rt.respEditor.message().raw();
                out.add(s);
            }
        }
        return out.isEmpty() ? null : out;
    }

    @Override public void restoreState(java.io.Serializable state) {
        if (!(state instanceof java.util.List<?> list) || list.isEmpty()) return;
        restoring = true;
        try { tabs.removeAll(); } finally { restoring = false; }
        for (Object o : list) {
            if (!(o instanceof TabState s)) continue;
            HttpService svc = new HttpService(s.host == null ? "127.0.0.1" : s.host, s.port, s.secure);
            newTab(svc, new HttpMessage(s.req == null ? new byte[0] : s.req), s.title);
            if (tabs.getComponentAt(tabs.getTabCount() - 1) instanceof RepeaterTab rt
                    && s.resp != null && s.resp.length > 0) {
                rt.respEditor.setMessage(svc, new HttpMessage(s.resp), rt.reqEditor.message());
            }
        }
    }

    private static final class TabState implements java.io.Serializable {
        private static final long serialVersionUID = 1L;
        String title; String host; int port; boolean secure; byte[] req; byte[] resp;
    }

    @Override public boolean alwaysTabbed() { return false; }

    /** The reference's Repeater menu: the front tab's settings, then its request's actions. Filled each time it opens. */
    @Override public JMenu[] menus() {
        JMenu menu = new JMenu("repeater");
        menu.addMenuListener(new javax.swing.event.MenuListener() {
            @Override public void menuSelected(javax.swing.event.MenuEvent e) { fillMenu(menu); }
            @Override public void menuDeselected(javax.swing.event.MenuEvent e) { }
            @Override public void menuCanceled(javax.swing.event.MenuEvent e) { }
        });
        fillMenu(menu);
        return new JMenu[]{ menu };
    }

    /** Move a popup's rows into a menu, from the row at {@code from}. */
    private static void move(JPopupMenu from, int first, JMenu into) {
        java.awt.Component[] rows = from.getComponents();
        for (int k = first; k < rows.length; k++) {
            if (rows[k] instanceof JMenuItem mi) { mi.setFont(Ui.PLAIN); into.add(mi); }
            else if (rows[k] instanceof JSeparator) into.addSeparator();
        }
    }

    private void fillMenu(JMenu menu) {
        menu.removeAll();
        if (tabs.getSelectedComponent() instanceof RepeaterTab t) {
            // The first two rows of the tab's own menu are its heading; the last is the HTTP version, which the tab shows as a chip.
            JPopupMenu settings = t.tabSettingsMenu();
            java.awt.Component[] rows = settings.getComponents();
            for (int k = 2; k < rows.length - 1; k++) if (rows[k] instanceof JMenuItem mi) menu.add(mi);
            menu.addSeparator();
            JMenu action = new JMenu("Action");
            action.setFont(Ui.PLAIN);
            move(t.reqEditor.buildMenu(), 0, action);
            menu.add(action);
            menu.addSeparator();
        }
        JMenuItem seq = new JMenuItem("Send all tabs in sequence (separate connections)");
        seq.addActionListener(e -> sendAllInSequence());
        JMenuItem par = new JMenuItem("Send all tabs in parallel");
        par.addActionListener(e -> sendAllInParallel());
        JMenuItem reopen = new JMenuItem("Reopen closed tab");
        reopen.addActionListener(e -> reopenClosed());
        for (JMenuItem m : new JMenuItem[]{ seq, par, reopen }) { m.setFont(Ui.PLAIN); menu.add(m); }
    }

    /** Settings > Repeater: how a reissued request is prepared and followed. */
    /** A tab as the "+" makes it: no request yet and no target, to be filled in or pasted into. */
    private void newBlankTab() {
        newTab(new HttpService("", 80, false), new HttpMessage(new byte[0]), null);
    }

    private void newTab(HttpService svc, HttpMessage req, String caption) {
        if (svc == null) svc = new HttpService("127.0.0.1", 80, false);
        if (req == null) req = new HttpMessage(Bytes.bytes("GET / HTTP/1.1\r\nHost: " + svc.host() + "\r\n\r\n"));
        RepeaterTab tab = new RepeaterTab(svc, req);
        String title = caption != null && !caption.isBlank() ? caption : String.valueOf(counter.incrementAndGet());
        closeIntro();
        tabs.addTab(title, tab);
        opensuite.ui.TabStrip.closable(tabs, tabs.indexOfComponent(tab));
        tabs.setSelectedComponent(tab);
    }

    private class RepeaterTab extends JPanel {
        private final MessageEditor reqEditor;
        private final MessageEditor respEditor;
        private final JTextField hostField;
        private final JTextField portField;
        private final JCheckBox sslBox;
        private final JComboBox<HttpMode> modeCombo = Ui.combo(HttpMode.values());
        private final JLabel status = Ui.label("ready");
        private final JLabel lengthLabel = Ui.label("");
        private final JButton go = Ui.primaryButton("Send", "Send the request");
        private final JButton cancel = Ui.button("Cancel");
        private final opensuite.ui.SplitButton prev = new opensuite.ui.SplitButton(false, "Previous request and response in this tab");
        private final opensuite.ui.SplitButton next = new opensuite.ui.SplitButton(true, "Next request and response in this tab");
        private final JLabel histLabel = Ui.label("");
        private JLabel targetLabel;
        private final JLabel versionChip = new JLabel("HTTP/1");
        /** The hairline before the protocol and the gaps round it; all hidden until the tab has a target. */
        private final JComponent versionBar = new JComponent() {
            @Override public Dimension getPreferredSize() { return new Dimension(1, Ui.tall(23)); }
            @Override protected void paintComponent(Graphics g) { g.setColor(Theme.BORDER); g.fillRect(0, 0, 1, getHeight()); }
        };
        private final Component versionGap = Box.createHorizontalStrut(11), versionGap2 = Box.createHorizontalStrut(10),
                tailGap = Box.createHorizontalStrut(1);
        private boolean overrideSni;
        private volatile Thread worker;

        /** Show the protocol the tab is set to send with; a response over HTTP/2 corrects it. */
        private void refreshVersion() {
            Object m = modeCombo.getSelectedItem();
            versionChip.setText(m == HttpMode.HTTP_2 || m == HttpMode.HTTP_2_IGNORE_ALPN ? "HTTP/2" : "HTTP/1");
        }

        /** Take the target of a URL pasted as a request. */
        private void useTarget(HttpService target) {
            hostField.setText(target.host());
            portField.setText(String.valueOf(target.port()));
            sslBox.setSelected(target.secure());
            refreshTarget();
        }

        /** Every request this tab has sent and the response to each, in order, to one file. */
        private void saveEntireHistory() {
            if (history.isEmpty()) {
                JOptionPane.showMessageDialog(this, "This tab has not sent anything yet.", "Save entire history", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            JFileChooser fc = new opensuite.ui.FileChooser();
            fc.setDialogTitle("Save entire history");
            if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return;
            try (java.io.OutputStream out = java.nio.file.Files.newOutputStream(fc.getSelectedFile().toPath())) {
                writeHistory(history.stream().map(h -> new byte[][]{h.request(), h.response() == null ? null : h.response().raw()}).toList(), out);
            } catch (java.io.IOException ex) {
                JOptionPane.showMessageDialog(this, "Could not write the file: " + ex.getMessage(), "Save entire history", JOptionPane.ERROR_MESSAGE);
            }
        }

        private void refreshTarget() {
            String host = hostField.getText().trim();
            String port = portField.getText().trim();
            boolean tls = sslBox.isSelected();
            boolean defPort = (tls && "443".equals(port)) || (!tls && "80".equals(port));
            boolean known = !host.isEmpty();
            targetLabel.setText(known ? "Target: " + (tls ? "https://" : "http://") + host + (defPort ? "" : ":" + port)
                    : "Target: Not specified");
            versionChip.setVisible(known);
            versionBar.setVisible(known);
            versionGap.setVisible(known);
            versionGap2.setVisible(known);
            tailGap.setVisible(!known);
        }

        /** "Configure target details": host, SNI override, port, HTTPS. */
        private void configureTarget() {
            // With no target yet, offer the request's own Host header.
            String known = hostField.getText().trim();
            if (known.isEmpty()) {
                String h = new HttpMessage(reqEditor.bytes()).header("Host");
                if (h != null) known = h.trim().replaceFirst(":\\d+$", "");
            }
            JTextField host = Ui.field(known);
            host.addAncestorListener(new javax.swing.event.AncestorListener() {
                @Override public void ancestorAdded(javax.swing.event.AncestorEvent e) {
                    SwingUtilities.invokeLater(() -> { host.requestFocusInWindow(); host.selectAll(); });
                }
                @Override public void ancestorRemoved(javax.swing.event.AncestorEvent e) {}
                @Override public void ancestorMoved(javax.swing.event.AncestorEvent e) {}
            });
            JCheckBox sni = Ui.check("Override SNI", overrideSni);
            JTextField port = Ui.shortField(portField.getText());
            JCheckBox https = Ui.check("Use HTTPS", sslBox.isSelected());
            https.addActionListener(e -> {
                String p = port.getText().trim();
                if (p.equals("80") && https.isSelected()) port.setText("443");
                else if (p.equals("443") && !https.isSelected()) port.setText("80");
            });
            JTextArea about = Ui.note("Specify the details of the server to which the request will be sent.");
            Ui.sizeNote(about, 420);
            JPanel form = Ui.vbox(about,
                    Ui.form("Host:", host), sni, Ui.form("Port:", port), https);
            form.setBorder(Ui.pad(10, 10, 10, 10));
            int ok = JOptionPane.showConfirmDialog(this, form, "Configure target details", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
            if (ok != JOptionPane.OK_OPTION) return;
            hostField.setText(host.getText().trim());
            portField.setText(port.getText().trim());
            sslBox.setSelected(https.isSelected());
            overrideSni = sni.isSelected();
            refreshTarget();
        }

        /** This tab's value of a Repeater setting: its own override, else the project's, else the default. */
        private String setting(String key) {
            String mine = overrides.get(key);
            return mine != null ? mine : ctx.settings().get(key, RepeaterSettingsPanel.defaultOf(key));
        }
        private boolean on(String key) { return "true".equals(setting(key)); }

        private JCheckBoxMenuItem toggle(String text, String key) {
            JCheckBoxMenuItem it = new JCheckBoxMenuItem(text, on(key));
            it.addActionListener(e -> overrides.put(key, String.valueOf(it.isSelected())));
            return it;
        }

        /** The per-tab settings menu: the project defaults can be overridden here for this tab only. */
        private JPopupMenu tabSettingsMenu() {
            JPopupMenu m = new JPopupMenu();
            JPanel head = new JPanel(new BorderLayout(10, 0));
            head.setOpaque(false);
            head.setBorder(Ui.pad(4, 10, 4, 10));
            head.add(Ui.bold("Repeater settings for this tab"), BorderLayout.WEST);
            JButton restore = Ui.button("Restore global defaults");
            restore.addActionListener(e -> { overrides.clear(); m.setVisible(false); });
            head.add(restore, BorderLayout.EAST);
            m.add(head);
            m.addSeparator();
            JMenu follow = new JMenu("Follow redirections");
            ButtonGroup fg = new ButtonGroup();
            for (int i = 0; i < RepeaterSettingsPanel.FOLLOW_VALUES.length; i++) {
                String value = RepeaterSettingsPanel.FOLLOW_VALUES[i];
                JRadioButtonMenuItem r = new JRadioButtonMenuItem(RepeaterSettingsPanel.FOLLOW_LABELS[i],
                        value.equals(setting(RepeaterSettingsPanel.FOLLOW)));
                r.addActionListener(e -> overrides.put(RepeaterSettingsPanel.FOLLOW, value));
                fg.add(r); follow.add(r);
            }
            JMenu timeout = new JMenu("Streaming response timeout");
            ButtonGroup tg = new ButtonGroup();
            String current = setting(RepeaterSettingsPanel.STREAM_TIMEOUT);
            String[] names = { "30 seconds", "1 minute", "5 minutes", "10 minutes", "Never" };
            String[] seconds = { "30", "60", "300", "600", "0" };
            boolean listed = false;
            for (int i = 0; i < names.length; i++) {
                String value = seconds[i];
                JRadioButtonMenuItem r = new JRadioButtonMenuItem(names[i], value.equals(current));
                listed |= value.equals(current);
                r.addActionListener(e -> overrides.put(RepeaterSettingsPanel.STREAM_TIMEOUT, value));
                tg.add(r); timeout.add(r);
            }
            JRadioButtonMenuItem custom = new JRadioButtonMenuItem(listed ? "Custom..." : "Custom (" + current + " seconds)...", !listed);
            custom.addActionListener(e -> {
                String typed = JOptionPane.showInputDialog(ctx.frame(), "Streaming response timeout in seconds (0 for never)", current);
                if (typed == null) return;
                try { overrides.put(RepeaterSettingsPanel.STREAM_TIMEOUT, String.valueOf(Math.max(0, Integer.parseInt(typed.trim())))); }
                catch (NumberFormatException ex) { status.setText("Invalid number of seconds: " + typed.trim()); }
            });
            tg.add(custom); timeout.add(custom);
            JMenu version = new JMenu("HTTP version");
            ButtonGroup vg = new ButtonGroup();
            for (HttpMode mode : HttpMode.values()) {
                JRadioButtonMenuItem r = new JRadioButtonMenuItem(String.valueOf(mode), mode == modeCombo.getSelectedItem());
                r.addActionListener(e -> modeCombo.setSelectedItem(mode));
                vg.add(r); version.add(r);
            }
            for (JMenuItem it : new JMenuItem[] {
                    toggle("Update Content-Length", RepeaterSettingsPanel.UPDATE_LENGTH),
                    toggle("Unpack compressed responses", RepeaterSettingsPanel.UNPACK),
                    follow,
                    toggle("Process cookies in redirections", RepeaterSettingsPanel.REDIRECT_COOKIES),
                    toggle("Enforce protocol choice on cross-domain redirections", RepeaterSettingsPanel.REDIRECT_PROTOCOL),
                    toggle("Normalize HTTP/1 line endings", RepeaterSettingsPanel.NORMALISE),
                    toggle("Enable HTTP/1 connection reuse", RepeaterSettingsPanel.H1_REUSE),
                    toggle("Enable HTTP/2 connection reuse", RepeaterSettingsPanel.H2_REUSE),
                    toggle("Strip Connection header over HTTP/2", RepeaterSettingsPanel.STRIP_CONNECTION),
                    toggle("Allow HTTP/2 ALPN override", RepeaterSettingsPanel.ALPN_OVERRIDE),
                    timeout, version }) { it.setFont(Ui.PLAIN); m.add(it); }
            return m;
        }

        /** A dropdown of this tab's history around the current position. */
        private void historyMenu(Component anchor, int dir) {
            JPopupMenu m = new JPopupMenu();
            int from = dir < 0 ? historyPos - 1 : historyPos + 1;
            for (int i = from; i >= 0 && i < history.size(); i += dir) {
                final int idx = i;
                Snapshot sn = history.get(i);
                String first = new String(sn.request(), java.nio.charset.StandardCharsets.ISO_8859_1).split("\\r?\\n", 2)[0];
                JMenuItem mi = new JMenuItem((i + 1) + ". " + Ui.truncate(first, 60));
                mi.setFont(Ui.PLAIN);
                mi.addActionListener(e -> navigate(idx - historyPos));
                m.add(mi);
            }
            if (m.getComponentCount() == 0) { JMenuItem none = new JMenuItem("No " + (dir < 0 ? "earlier" : "later") + " requests"); none.setEnabled(false); m.add(none); }
            m.show(anchor, 0, anchor.getHeight());
        }

        /** Repeater settings this tab has changed for itself, by key. */
        private final java.util.Map<String, String> overrides = new java.util.concurrent.ConcurrentHashMap<>();

        // Per-tab history of sends, with a browser-style position for back/forward.
        private record Snapshot(HttpService svc, byte[] request, HttpMessage response, String status, String size) {}
        private final java.util.List<Snapshot> history = new java.util.ArrayList<>();
        private int historyPos = -1;

        RepeaterTab(HttpService svc, HttpMessage req) {
            super(new BorderLayout());
            reqEditor = new MessageEditor(ctx, MessageEditor.REQUEST, true);
            respEditor = new MessageEditor(ctx, MessageEditor.RESPONSE, false);
            // The parts of the editor menu that are Repeater's own.
            for (MessageEditor ed : new MessageEditor[]{reqEditor, respEditor}) {
                ed.setToolDocs("Repeater");
                ed.setHistorySaver(this::saveEntireHistory);
            }
            reqEditor.setTargetSetter(this::useTarget);
            reqEditor.setMessage(svc, req);
            // "Default to HTTP/2 if the server supports it": asked off the event thread, and
            // only applied while the tab is still on the protocol it opened with.
            if (svc != null && svc.secure() && ctx.settings().getBool(NetworkConfig.HTTP2_DEFAULT, true)) {
                Thread ask = new Thread(() -> {
                    HttpMode mode = NetworkConfig.defaultMode(svc);
                    if (mode != HttpMode.HTTP_1) SwingUtilities.invokeLater(() -> {
                        if (modeCombo.getSelectedItem() == HttpMode.HTTP_1 && history.isEmpty()) modeCombo.setSelectedItem(mode);
                    });
                }, "repeater-http2-default");
                ask.setDaemon(true);
                ask.start();
            }

            // Layout, as in the reference: Send, gear, Cancel, back / forward with
            // history menus and the AI-free toolbar on the left; the target with
            // its edit pencil, the HTTP version chip and help on the right.
            cancel.setEnabled(false);
            hostField = Ui.field(svc.host());
            portField = Ui.shortField(String.valueOf(svc.port()));
            sslBox = Ui.check("SSL", svc.secure());
            prev.setEnabled(false);
            next.setEnabled(false);
            prev.onAction(() -> navigate(-1));
            next.onAction(() -> navigate(1));
            prev.onMenu(() -> historyMenu(prev, -1));
            next.onMenu(() -> historyMenu(next, 1));
            // The gear sits in its own grey 23px square.
            JButton gear = new JButton(opensuite.ui.Glyphs.gear(17, Theme.TEXT));
            gear.setToolTipText("Repeater settings for this tab");
            gear.setFocusable(false);
            gear.setMargin(new Insets(0, 0, 0, 0));
            gear.setBorder(Ui.pad(0, 0, 0, 0));
            gear.setPreferredSize(new Dimension(Ui.tall(23), Ui.tall(23)));
            gear.addActionListener(e -> tabSettingsMenu().show(gear, 0, gear.getHeight()));
            modeCombo.setToolTipText("HTTP/1 is raw and byte-exact; HTTP/2 and auto use the JDK transport");
            go.setBorder(Ui.pad(0, 0, 0, 0));
            cancel.setBorder(Ui.pad(0, 0, 0, 0));
            go.setPreferredSize(new Dimension(Ui.column(61, go.getFont(), "Send"), Ui.tall(23)));
            cancel.setPreferredSize(new Dimension(Ui.column(79, cancel.getFont(), "Cancel"), Ui.tall(23)));

            JPanel left = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
            left.setOpaque(false);
            left.add(go);
            left.add(Box.createHorizontalStrut(5));
            left.add(gear);
            left.add(Box.createHorizontalStrut(5));
            left.add(cancel);
            left.add(Box.createHorizontalStrut(5));
            left.add(prev);
            left.add(Box.createHorizontalStrut(5));
            left.add(next);
            left.add(Box.createHorizontalStrut(10));
            histLabel.setPreferredSize(new Dimension(60, Ui.tall(23)));
            left.add(histLabel);

            targetLabel = Ui.bold("");
            refreshTarget();
            JButton help = opensuite.ui.Glyphs.button(opensuite.ui.Glyphs.help(), "About Repeater", () -> JOptionPane.showMessageDialog(this,
                    "Edit the request in the left pane and click Send. The response is shown in the right pane.\n"
                  + "Use the arrows to navigate this tab's history and the pencil to edit the target.", "Repeater", JOptionPane.INFORMATION_MESSAGE));
            JButton pencil = opensuite.ui.Glyphs.button(opensuite.ui.Glyphs.trimmed(opensuite.ui.Glyphs.pencil(25, Theme.TEXT)), "Configure target details", this::configureTarget);
            pencil.setBorder(null);
            help.setIcon(opensuite.ui.Glyphs.help(21 + Ui.fontGrowth() / 2, Theme.TEXT));
            help.setBorder(null);
            // The protocol the tab sends with, parted from the target by a hairline;
            // clicking it chooses another.
            versionChip.setFont(Ui.PLAIN);
            versionChip.setForeground(Theme.TEXT);
            versionChip.setToolTipText("HTTP version used by this tab; click to change");
            versionChip.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            versionChip.addMouseListener(new java.awt.event.MouseAdapter() {
                @Override public void mousePressed(java.awt.event.MouseEvent e) {
                    JPopupMenu m = new JPopupMenu();
                    for (HttpMode mode : HttpMode.values()) {
                        JRadioButtonMenuItem r = new JRadioButtonMenuItem(String.valueOf(mode), mode == modeCombo.getSelectedItem());
                        r.setFont(Ui.PLAIN);
                        r.addActionListener(a -> modeCombo.setSelectedItem(mode));
                        m.add(r);
                    }
                    m.show(versionChip, 0, versionChip.getHeight());
                }
            });
            modeCombo.addActionListener(e -> refreshVersion());
            refreshVersion();
            JPanel right = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
            right.setOpaque(false);
            right.add(targetLabel);
            right.add(Box.createHorizontalStrut(10));
            right.add(pencil);
            right.add(versionGap);
            right.add(versionBar);
            right.add(versionGap2);
            right.add(versionChip);
            right.add(Box.createHorizontalStrut(10));
            right.add(tailGap);
            right.add(help);
            // Keeps the row 23px tall when the protocol and its hairline are hidden.
            right.add(Box.createRigidArea(new Dimension(0, Ui.tall(23))));

            // 42px of page colour over a hairline, the buttons 10px down.
            JPanel north = new JPanel(new BorderLayout());
            north.setBackground(Theme.BG);
            north.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createMatteBorder(0, 0, 1, 0, Theme.BORDER), Ui.pad(10, 10, 9, 10)));
            north.add(left, BorderLayout.WEST);
            north.add(right, BorderLayout.EAST);
            add(north, BorderLayout.NORTH);

            // Request and response side by side, with the layout switch on the
            // response's heading and the side dock beside both.
            opensuite.ui.MessagePair pair = new opensuite.ui.MessagePair(reqEditor, respEditor);
            pair.setBlank(false);
            // Until a response arrives its pane is only a heading; an empty
            // request opens on the raw text, ready to type or paste into.
            respEditor.setHideWhenEmpty(true);
            if (req.raw().length == 0) reqEditor.selectView("Raw");
            respEditor.setCustomActionsVisible(true);
            add(pair, BorderLayout.CENTER);

            JPanel south = new JPanel(new BorderLayout());
            // A 26px line under a hairline, across the whole tab.
            south.setBackground(Theme.BG);
            south.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createMatteBorder(1, 0, 0, 0, Theme.BORDER), Ui.pad(0, 5, 0, 5)));
            south.setPreferredSize(new Dimension(10, 27));
            status.setText("Ready");
            south.add(status, BorderLayout.CENTER);
            south.add(lengthLabel, BorderLayout.EAST);
            add(south, BorderLayout.SOUTH);

            go.addActionListener(e -> send());
            cancel.addActionListener(e -> { if (worker != null) worker.interrupt(); });
        }

        private JLabel bold(String s) {
            JLabel l = Ui.bold(s);
            l.setBorder(Ui.pad(3, 2, 3, 2));
            return l;
        }

        /** The target as the tab currently has it; a bad port falls back to the scheme's default. */
        HttpService service() {
            int port;
            try { port = Integer.parseInt(portField.getText().trim()); }
            catch (NumberFormatException e) { port = sslBox.isSelected() ? 443 : 80; }
            return new HttpService(hostField.getText().trim(), port, sslBox.isSelected());
        }

        private void send() {
            // No target yet: ask for one, as the reference does, and send once it is given.
            if (hostField.getText().trim().isEmpty()) {
                configureTarget();
                if (hostField.getText().trim().isEmpty()) return;
            }
            HttpService svc;
            try {
                svc = new HttpService(hostField.getText().trim(),
                        Integer.parseInt(portField.getText().trim()), sslBox.isSelected());
            } catch (NumberFormatException ex) {
                status.setText("Invalid port number");
                return;
            }
            HttpMode chosen = (HttpMode) modeCombo.getSelectedItem();
            byte[] typed = reqEditor.bytes();
            if (chosen == HttpMode.HTTP_1 && on(RepeaterSettingsPanel.NORMALISE)) typed = HttpClient.normaliseLineEndings(typed);
            HttpMessage req = new HttpMessage(typed);
            boolean updateLength = on(RepeaterSettingsPanel.UPDATE_LENGTH);
            if (updateLength && req.body().length > 0) req.updateContentLength();
            // The settings are read here, on the event thread, as they stand when Send is pressed.
            String follow = setting(RepeaterSettingsPanel.FOLLOW);
            HttpClient.Options opt = new HttpClient.Options();
            opt.updateContentLength = updateLength;
            opt.unpackGzip = on(RepeaterSettingsPanel.UNPACK);
            opt.followRedirects = !"never".equals(follow);
            if ("onsite".equals(follow)) {
                opt.redirectFilter = (from, to) -> from.host().equalsIgnoreCase(to.host()) && from.port() == to.port();
            } else if ("inscope".equals(follow)) {
                opt.redirectFilter = (from, to) -> ctx.scope().isInScope(to, "/");
            }
            opt.cookiesInRedirects = on(RepeaterSettingsPanel.REDIRECT_COOKIES);
            opt.modeAcrossHosts = on(RepeaterSettingsPanel.REDIRECT_PROTOCOL);
            opt.keepAlive = on(RepeaterSettingsPanel.H1_REUSE);
            opt.h2Reuse = on(RepeaterSettingsPanel.H2_REUSE);
            opt.h2StripConnection = on(RepeaterSettingsPanel.STRIP_CONNECTION);
            int seconds;
            try { seconds = Integer.parseInt(setting(RepeaterSettingsPanel.STREAM_TIMEOUT).trim()); }
            catch (NumberFormatException ex) { seconds = 600; }
            opt.streamTimeoutMs = (int) Math.min(Integer.MAX_VALUE, Math.max(0, seconds) * 1000L);
            opt.session = ctx.sessions();
            opt.sessionTool = "repeater";
            opt.mode = chosen == HttpMode.HTTP_2 && on(RepeaterSettingsPanel.ALPN_OVERRIDE) ? HttpMode.HTTP_2_IGNORE_ALPN : chosen;

            status.setText("Waiting");
            lengthLabel.setText("");
            go.setEnabled(false);
            cancel.setEnabled(true);

            worker = new Thread(() -> {
                try {
                    long t0 = System.currentTimeMillis();
                    HttpClient.Result r = new HttpClient().send(svc, req, opt);
                    long ms = System.currentTimeMillis() - t0;
                    SwingUtilities.invokeLater(() -> {
                        go.setEnabled(true);
                        cancel.setEnabled(false);
                        if (!r.ok()) {
                            status.setText(r.error);
                            return;
                        }
                        respEditor.setMessage(svc, r.response, req);
                        versionChip.setText(r.response.startLine().startsWith("HTTP/2") ? "HTTP/2" : "HTTP/1");
                        int redirs = r.redirectsFollowed;
                        String statusText = "Done" + (redirs > 0 ? " (followed " + redirs + " redirect"
                                + (redirs == 1 ? "" : "s") + ")" : "");
                        String size = String.format("%,d bytes | %,d millis", r.response.length(), ms);
                        status.setText(statusText);
                        lengthLabel.setText(size);
                        pushHistory(new Snapshot(svc, req.raw().clone(), r.response, statusText, size));

                        LogEntry entry = new LogEntry("repeater", svc, req);
                        entry.setResponse(r.response);
                        entry.setRemoteIp(r.remoteIp);
                        entry.setDurationMillis(ms);
                        ctx.store().add(entry);
                        ctx.siteMapChanged(entry);
                    });
                } catch (Exception e) {
                    // Without this the Go button stays disabled and the tab
                    // reads "waiting" forever; nothing else would report it.
                    Debug.error("repeater request failed", e);
                    SwingUtilities.invokeLater(() -> {
                        go.setEnabled(true);
                        cancel.setEnabled(false);
                        status.setText("Failed: " + e.getMessage());
                    });
                }
            }, "repeater-send");
            worker.setDaemon(true);
            worker.start();
        }

        /** Append a send to this tab's history, truncating any forward entries. */
        private void pushHistory(Snapshot s) {
            while (history.size() > historyPos + 1) history.remove(history.size() - 1);
            history.add(s);
            historyPos = history.size() - 1;
            updateNav();
        }

        private void navigate(int delta) {
            int target = historyPos + delta;
            if (target < 0 || target >= history.size()) return;
            historyPos = target;
            Snapshot s = history.get(historyPos);
            hostField.setText(s.svc().host());
            portField.setText(String.valueOf(s.svc().port()));
            sslBox.setSelected(s.svc().secure());
            refreshTarget();
            reqEditor.setMessage(s.svc(), new HttpMessage(s.request().clone()));
            if (s.response() != null) {
                respEditor.setMessage(s.svc(), s.response(), new HttpMessage(s.request().clone()));
                lengthLabel.setText(s.size());
            } else {
                respEditor.setMessage(s.svc(), new HttpMessage(new byte[0]));
            }
            status.setText(s.status());
            updateNav();
        }

        private void updateNav() {
            prev.setEnabled(historyPos > 0);
            next.setEnabled(historyPos >= 0 && historyPos < history.size() - 1);
            histLabel.setText(history.isEmpty() ? "" : (historyPos + 1) + "/" + history.size());
        }
    }
}