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.

32.5 KB
Raw Blame
package opensuite.core;

import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.cert.X509Certificate;
import java.util.Locale;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;

/**
 * Sends a request exactly as given and reads the response.
 *
 * Deliberately byte-exact: no header reordering, no silent Content-Length
 * correction, no normalisation. Callers that want those must ask.
 */
public class HttpClient {

    /** What new options start with; the suite sets these from Settings > Network > Connections > Timeouts. */
    public static volatile int defaultConnectTimeoutMs = 15000;
    public static volatile int defaultReadTimeoutMs = 30000;

    /** Apply the timeouts setting, given in seconds; zero or less means wait without limit. */
    public static void setDefaultTimeouts(int connectSeconds, int readSeconds) {
        defaultConnectTimeoutMs = connectSeconds <= 0 ? Integer.MAX_VALUE : (int) Math.min(Integer.MAX_VALUE, connectSeconds * 1000L);
        defaultReadTimeoutMs = readSeconds <= 0 ? Integer.MAX_VALUE : (int) Math.min(Integer.MAX_VALUE, readSeconds * 1000L);
    }

    /** Settings > Network > HTTP > HTTP/1: whether connections are kept and reused unless a tool says otherwise. */
    public static volatile boolean defaultKeepAlive = false;

    public static class Options {
        public int connectTimeoutMs = defaultConnectTimeoutMs;
        public int readTimeoutMs = defaultReadTimeoutMs;
        public boolean updateContentLength = false;
        public boolean unpackGzip = true;
        public boolean followRedirects = false;
        public int maxRedirects = 5;
        /** Reuse an idle HTTP/1 connection to the same server when one is open. */
        public boolean keepAlive = defaultKeepAlive;
        /** Whether a redirect from the first service to the second is followed; null follows all. */
        public java.util.function.BiPredicate<HttpService, HttpService> redirectFilter;
        /** Carry cookies a redirect sets into the request that follows it. */
        public boolean cookiesInRedirects = false;
        /** Keep the chosen protocol when a redirect leads to another host; otherwise HTTP/1 is used there. */
        public boolean modeAcrossHosts = true;
        /** One HTTP/2 client shared between sends, so its connections are reused. */
        public boolean h2Reuse = true;
        /** Leave the Connection header out of an HTTP/2 request. */
        public boolean h2StripConnection = true;
        /** How long a streaming response is read for, in milliseconds; 0 reads until it ends, -1 uses the read timeout. */
        public int streamTimeoutMs = -1;
        /** Optional session-handling hook; null disables session handling for this send. */
        public SessionHook session;
        /** Which tool is sending, so session rules scoped to a tool can match. */
        public String sessionTool = "";
        /** Protocol to use. HTTP/1.x is the raw byte-exact default. */
        public HttpMode mode = HttpMode.HTTP_1;
        /** Optional upstream override (e.g. the ZAP engine for live passive scanning);
         *  falls back to a direct connection if it cannot be reached. */
        public UpstreamProxy upstream;
    }

    public static class Result {
        public HttpMessage response;
        public String remoteIp = "";
        public long millis;
        /** When the request was written, in epoch milliseconds; 0 when it never was. */
        public long sentAt;
        /** Milliseconds from the request being written to the first byte of the response; -1 when not measured. */
        public long firstByteMillis = -1;
        public String error = "";
        public int redirectsFollowed;
        /** A 100 Continue the server sent before the response, when it is kept rather than removed. */
        public byte[] interim;
        public HttpService finalService;
        public HttpMessage finalRequest;
        public boolean ok() { return error.isEmpty() && response != null; }
    }

    /** Resolves an optional upstream proxy per destination; null routes direct. */
    public interface ProxyProvider { UpstreamProxy proxyFor(HttpService svc); }

    private static volatile ProxyProvider proxyProvider;
    public static void setProxyProvider(ProxyProvider p) { proxyProvider = p; }

    /** Decides whether a request may be sent at all; a reason refuses it, null lets it go. */
    public interface Gate { String refuse(HttpService svc, HttpMessage request); }

    private static volatile Gate gate;
    public static void setGate(Gate g) { gate = g; }

    /**
     * Send, following redirects per the options, and additionally consult the
     * session hook: cookies are applied before the send and learned from the
     * response, and a rule may re-authenticate and ask for one resend.
     */
    /**
     * Open a connected socket to a service, with the suite's trust-all TLS and
     * SNI when secure. Used by the WebSocket relay, which needs a raw persistent
     * socket rather than the request/response send cycle.
     */
    public static Socket openSocket(HttpService svc, int connectTimeoutMs, int readTimeoutMs) throws Exception {
        return connect(svc, connectTimeoutMs, readTimeoutMs);
    }

    /**
     * Connect to a service, routing through an upstream HTTP (CONNECT) or SOCKS
     * proxy when one is configured for the destination, and layering TLS (with
     * SNI) on top when the service is secure.
     */
    private static Socket connect(HttpService svc, int connectTimeoutMs, int readTimeoutMs) throws Exception {
        return connect(svc, connectTimeoutMs, readTimeoutMs, null);
    }

    /**
     * Connect, optionally through an override upstream (used for live passive
     * scanning through the ZAP engine). If the override cannot be reached the
     * connection falls back to direct, so the scan engine being down never breaks
     * the user's traffic.
     */
    private static Socket connect(HttpService svc, int ct, int rt, UpstreamProxy override) throws Exception {
        if (override != null) {
            try { return connectVia(svc, ct, rt, override); }
            catch (Exception e) {
                Debug.log("upstream proxy " + override.host + ":" + override.port
                        + " failed (" + e + "); falling back to a direct connection");
                return connectVia(svc, ct, rt, null); // fail-safe: go direct
            }
        }
        return connectVia(svc, ct, rt, proxyProvider == null ? null : proxyProvider.proxyFor(svc));
    }

    private static Socket connectVia(HttpService svc, int connectTimeoutMs, int readTimeoutMs, UpstreamProxy up) throws Exception {
        // Settings > Network > Connections: with no upstream proxy for the host, the SOCKS proxy if one is on.
        boolean viaSettings = false;
        if (up == null) {
            up = NetworkConfig.socksFor(svc.host());
            viaSettings = up != null;
        }
        Socket base;
        if (up == null) {
            base = new Socket();
            // Settings > Network > DNS: overrides, and the preferred address family.
            base.connect(new InetSocketAddress(NetworkConfig.resolve(svc.host()), svc.port()), connectTimeoutMs);
        } else if (up.type == UpstreamProxy.Type.SOCKS) {
            base = new Socket(new java.net.Proxy(java.net.Proxy.Type.SOCKS, new InetSocketAddress(up.host, up.port)));
            boolean remoteDns = !viaSettings || NetworkConfig.socksResolves();
            base.connect(remoteDns ? InetSocketAddress.createUnresolved(svc.host(), svc.port())
                    : new InetSocketAddress(NetworkConfig.resolve(svc.host()), svc.port()), connectTimeoutMs);
        } else {
            base = new Socket();
            base.connect(new InetSocketAddress(up.host, up.port), connectTimeoutMs);
            httpConnectTunnel(base, svc, up);
        }
        base.setSoTimeout(readTimeoutMs);
        if (!svc.secure()) return base;
        // Settings > Network > TLS: trust, client certificate, protocols and ciphers.
        SSLSocket s = (SSLSocket) NetworkConfig.context(svc.host()).getSocketFactory().createSocket(base, svc.host(), svc.port(), true);
        try {
            SSLParameters p = s.getSSLParameters();
            p.setServerNames(java.util.List.of(new SNIHostName(svc.host())));
            s.setSSLParameters(p);
        } catch (Exception ignored) {}
        NetworkConfig.prepare(s);
        try {
            s.startHandshake();
        } catch (IOException e) {
            try { s.close(); } catch (IOException ignored) { }
            throw e;
        }
        NetworkConfig.handshaken(s, svc.host());
        return s;
    }

    /** Establish an HTTP CONNECT tunnel through the upstream proxy to the target. */
    private static void httpConnectTunnel(Socket s, HttpService target, UpstreamProxy up) throws IOException {
        String hp = target.host() + ":" + target.port();
        StringBuilder sb = new StringBuilder();
        sb.append("CONNECT ").append(hp).append(" HTTP/1.1\r\nHost: ").append(hp).append("\r\n");
        if (up.user != null && !up.user.isEmpty()) {
            String cred = java.util.Base64.getEncoder().encodeToString(
                    (up.user + ":" + up.pass).getBytes(java.nio.charset.StandardCharsets.ISO_8859_1));
            sb.append("Proxy-Authorization: Basic ").append(cred).append("\r\n");
        }
        sb.append("\r\n");
        s.getOutputStream().write(Bytes.bytes(sb.toString()));
        s.getOutputStream().flush();
        ByteArrayOutputStream head = new ByteArrayOutputStream();
        int state = 0;
        InputStream in = s.getInputStream();
        while (state < 4) {
            int b = in.read();
            if (b < 0) break;
            head.write(b);
            if ((state == 0 || state == 2) && b == 13) state++;
            else if ((state == 1 || state == 3) && b == 10) state++;
            else state = 0;
            if (head.size() > 64 * 1024) break;
        }
        HttpMessage resp = new HttpMessage(head.toByteArray());
        if (resp.statusCode() / 100 != 2) {
            throw new IOException("upstream proxy refused CONNECT: " + resp.startLine());
        }
    }

    public Result send(HttpService svc, HttpMessage request, Options opt) {
        Gate g = gate;
        String refused = g == null ? null : g.refuse(svc, request);
        if (refused != null) {
            Result dropped = new Result();
            dropped.error = refused;
            return dropped;
        }
        Result r = null;
        for (int attempt = 0; attempt <= 1; attempt++) {
            HttpMessage start = request.copy();
            if (opt.session != null) {
                try { opt.session.beforeSend(opt.sessionTool, svc, start); }
                catch (Exception e) {
                    // A broken session rule must not be silent: the request goes
                    // out without the cookies or macro the user believes are
                    // applied, which silently changes what a test exercises.
                    Debug.error("session rule " + opt.sessionTool
                            + " beforeSend failed; sending the request without session handling", e);
                }
            }
            r = sendFollowingRedirects(svc, start, opt);
            if (opt.session == null || !r.ok()) break;
            boolean retry;
            try { retry = opt.session.afterResponse(opt.sessionTool, r.finalService, r.finalRequest, r.response); }
            catch (Exception e) {
                Debug.error("session rule " + opt.sessionTool + " afterResponse failed; not retrying", e);
                retry = false;
            }
            if (!retry || attempt >= 1) break;
        }
        return r;
    }

    private Result sendFollowingRedirects(HttpService svc, HttpMessage request, Options opt) {
        Result r = new Result();
        HttpService cur = svc;
        HttpMessage req = request.copy();
        long start = System.currentTimeMillis();

        HttpMode mode = opt.mode;
        for (int hop = 0; ; hop++) {
            if (opt.updateContentLength && req.isRequest() && req.body().length > 0) {
                req.updateContentLength();
            }
            Result one = sendOnce(cur, req, opt, mode);
            // Settings > Network > Connections > Platform authentication: a 401 is answered with the host's credentials.
            if (one.ok() && one.response.statusCode() == 401) {
                final HttpService to = cur;
                Options kept = new Options();
                copy(opt, kept);
                kept.keepAlive = true;   // an NTLM handshake lives on one connection
                kept.mode = HttpMode.HTTP_1;
                one = PlatformAuth.answer(cur, req, one, m -> sendOnce(to, m, kept, HttpMode.HTTP_1));
            }
            r.remoteIp = one.remoteIp;
            r.sentAt = one.sentAt;
            r.firstByteMillis = one.firstByteMillis;
            r.error = one.error;
            r.response = one.response;
            if (one.interim != null) r.interim = one.interim;
            r.finalService = cur;
            r.finalRequest = req;
            if (!one.ok()) break;

            if (!opt.followRedirects || hop >= opt.maxRedirects) break;
            int sc = one.response.statusCode();
            // Settings > Network > HTTP > Allowed redirect types.
            String loc = NetworkConfig.redirectTarget(one.response);
            if (loc == null || loc.isBlank()) break;
            boolean status3xx = sc >= 300 && sc <= 399;

            try {
                URI base = URI.create(cur.url() + req.path());
                URI next = base.resolve(loc.trim());
                boolean sec = "https".equalsIgnoreCase(next.getScheme());
                int port = next.getPort() == -1 ? (sec ? 443 : 80) : next.getPort();
                if (next.getHost() == null) break;
                HttpService to = new HttpService(next.getHost(), port, sec);
                if (opt.redirectFilter != null && !opt.redirectFilter.test(cur, to)) break;
                if (!opt.modeAcrossHosts && !to.host().equalsIgnoreCase(cur.host())) mode = HttpMode.HTTP_1;
                String carried = opt.cookiesInRedirects ? mergeCookies(req.header("Cookie"), one.response) : null;
                cur = to;
                String target = (next.getRawPath() == null || next.getRawPath().isEmpty()) ? "/" : next.getRawPath();
                if (next.getRawQuery() != null) target += "?" + next.getRawQuery();
                HttpMessage nr = req.copy();
                if (sc == 303 || ((sc == 301 || sc == 302 || !status3xx) && !nr.method().equalsIgnoreCase("GET"))) {
                    nr.setMethod("GET");
                    nr.setBody(new byte[0]);
                    nr.removeHeader("Content-Length");
                    nr.removeHeader("Content-Type");
                }
                nr.setRequestTarget(target);
                nr.setHeader("Host", cur.defaultPort() ? cur.host() : cur.host() + ":" + cur.port());
                if (carried != null && !carried.isEmpty()) nr.setHeader("Cookie", carried);
                req = nr;
                r.redirectsFollowed++;
            } catch (Exception e) {
                break;
            }
        }
        r.millis = System.currentTimeMillis() - start;
        return r;
    }

    /**
     * A request whose header lines end in a bare line feed, rewritten to end
     * in carriage return and line feed. The body is left as it is.
     */
    public static byte[] normaliseLineEndings(byte[] raw) {
        ByteArrayOutputStream out = new ByteArrayOutputStream(raw.length + 16);
        int i = 0, lineStart = 0;
        for (; i < raw.length; i++) {
            byte b = raw[i];
            if (b != 10) { out.write(b); continue; }
            boolean hadCr = i > 0 && raw[i - 1] == 13;
            if (!hadCr) out.write(13);
            out.write(10);
            int len = i - lineStart - (hadCr ? 1 : 0);
            lineStart = i + 1;
            if (len == 0) { i++; break; }   // the blank line: the body follows untouched
        }
        if (i < raw.length) out.write(raw, i, raw.length - i);
        return out.toByteArray();
    }

    /** The request's cookies with the ones the response sets laid over them, as a Cookie header value. */
    static String mergeCookies(String existing, HttpMessage response) {
        java.util.Map<String, String> jar = new java.util.LinkedHashMap<>();
        if (existing != null) for (String pair : existing.split(";")) {
            int eq = pair.indexOf('=');
            if (eq > 0) jar.put(pair.substring(0, eq).trim(), pair.substring(eq + 1).trim());
        }
        for (String line : response.headerLines()) {
            if (!line.regionMatches(true, 0, "Set-Cookie:", 0, 11)) continue;
            String first = line.substring(11).split(";", 2)[0];
            int eq = first.indexOf('=');
            if (eq > 0) jar.put(first.substring(0, eq).trim(), first.substring(eq + 1).trim());
        }
        StringBuilder sb = new StringBuilder();
        for (java.util.Map.Entry<String, String> e : jar.entrySet()) {
            if (sb.length() > 0) sb.append("; ");
            sb.append(e.getKey()).append('=').append(e.getValue());
        }
        return sb.toString();
    }

    /** An idle HTTP/1 connection kept for reuse, and when it was put by. */
    private record Idle(Socket socket, long since) {}
    private static final java.util.concurrent.ConcurrentHashMap<String, Idle> IDLE = new java.util.concurrent.ConcurrentHashMap<>();
    private static final long IDLE_MILLIS = 30_000;

    private static String idleKey(HttpService svc, Options opt) {
        return svc.host().toLowerCase(Locale.ROOT) + ":" + svc.port() + ":" + svc.secure()
                + (opt.upstream == null ? "" : "@" + opt.upstream.host + ":" + opt.upstream.port);
    }

    private Result sendOnce(HttpService svc, HttpMessage request, Options opt, HttpMode mode) {
        if (mode != null && mode != HttpMode.HTTP_1) {
            if (mode == opt.mode) return Http2Client.send(svc, request, opt);
            Options other = new Options();
            copy(opt, other);
            other.mode = mode;
            return Http2Client.send(svc, request, other);
        }
        // A kept connection is tried first; if it has gone stale the request is sent again on a new one.
        String key = idleKey(svc, opt);
        Idle idle = opt.keepAlive ? IDLE.remove(key) : null;
        if (idle != null && (idle.socket().isClosed() || System.currentTimeMillis() - idle.since() > IDLE_MILLIS)) {
            try { idle.socket().close(); } catch (IOException ignored) {}
            idle = null;
        }
        if (idle != null) {
            Result reused = exchange(svc, request, opt, idle.socket(), key);
            if (reused.ok()) return reused;
        }
        return exchange(svc, request, opt, null, key);
    }

    private static void copy(Options from, Options to) {
        to.connectTimeoutMs = from.connectTimeoutMs; to.readTimeoutMs = from.readTimeoutMs;
        to.updateContentLength = from.updateContentLength; to.unpackGzip = from.unpackGzip;
        to.followRedirects = from.followRedirects; to.maxRedirects = from.maxRedirects; to.keepAlive = from.keepAlive;
        to.session = from.session; to.sessionTool = from.sessionTool; to.mode = from.mode; to.upstream = from.upstream;
        to.redirectFilter = from.redirectFilter; to.cookiesInRedirects = from.cookiesInRedirects;
        to.modeAcrossHosts = from.modeAcrossHosts; to.h2Reuse = from.h2Reuse;
        to.h2StripConnection = from.h2StripConnection; to.streamTimeoutMs = from.streamTimeoutMs;
    }

    /** One request and its response on {@code kept} (an idle connection) or, when null, a new connection. */
    private Result exchange(HttpService svc, HttpMessage request, Options opt, Socket kept, String key) {
        Result r = new Result();
        Socket sock = kept;
        boolean keep = false;
        try {
            if (sock == null) sock = connect(svc, opt.connectTimeoutMs, opt.readTimeoutMs, opt.upstream);
            else sock.setSoTimeout(opt.readTimeoutMs);
            try { r.remoteIp = ((InetSocketAddress) sock.getRemoteSocketAddress()).getAddress().getHostAddress(); }
            catch (Exception ignored) {}

            OutputStream out = sock.getOutputStream();
            out.write(request.raw());
            out.flush();
            final long sent = System.currentTimeMillis();
            r.sentAt = sent;
            // The moment the first byte of the response arrives is noted as it is read.
            InputStream timed = new java.io.FilterInputStream(sock.getInputStream()) {
                private void seen(int n) { if (n > 0 && r.firstByteMillis < 0) r.firstByteMillis = System.currentTimeMillis() - sent; }
                @Override public int read() throws IOException { int b = super.read(); seen(b >= 0 ? 1 : 0); return b; }
                @Override public int read(byte[] b, int off, int len) throws IOException { int n = super.read(b, off, len); seen(n); return n; }
                @Override public void close() { }   // the socket is closed or kept by its owner
            };

            boolean[] framed = new boolean[2];
            boolean streamUrl = NetworkConfig.streams(svc, request.path());
            byte[] raw = readResponse(timed, request.method(), sock, opt.streamTimeoutMs, framed, streamUrl);
            // Settings > Network > HTTP > Status 100 response handling: the real response follows the interim one.
            for (int n = 0; n < 5 && raw.length > 0 && NetworkConfig.understands100() && new HttpMessage(raw).statusCode() == 100; n++) {
                if (!NetworkConfig.removes100()) r.interim = raw;
                raw = readResponse(timed, request.method(), sock, opt.streamTimeoutMs, framed, streamUrl);
            }
            if (raw.length == 0) { r.error = "empty response"; return r; }
            HttpMessage resp = new HttpMessage(raw);
            // A streaming response that is not to be stored keeps its headers only.
            if (framed[1] && !NetworkConfig.storesStreams() && resp.body().length > 0) resp.setBody(new byte[0]);
            // Only a response with its own framing leaves the connection fit for another request.
            keep = opt.keepAlive && framed[0] && !closes(request) && !closes(resp);
            if (opt.unpackGzip) unpack(resp);
            r.response = resp;
            return r;
        } catch (UnknownHostException e) {
            r.error = "unknown host: " + svc.host();
        } catch (SocketTimeoutException e) {
            r.error = "timeout";
        } catch (ConnectException e) {
            r.error = "failed to connect to " + svc.host() + ":" + svc.port();
        } catch (SSLException e) {
            r.error = "TLS error: " + e.getMessage();
        } catch (Exception e) {
            r.error = String.valueOf(e.getMessage());
        } finally {
            if (sock != null) {
                if (keep) {
                    Idle old = IDLE.put(key, new Idle(sock, System.currentTimeMillis()));
                    if (old != null) try { old.socket().close(); } catch (IOException ignored) {}
                } else {
                    try { sock.close(); } catch (IOException ignored) {}
                }
            }
        }
        return r;
    }

    private static boolean closes(HttpMessage m) {
        String c = m.header("Connection");
        if (c != null && c.toLowerCase(Locale.ROOT).contains("close")) return true;
        return m.startLine().contains("HTTP/1.0") && (c == null || !c.toLowerCase(Locale.ROOT).contains("keep-alive"));
    }

    /**
     * A stream that gives up at a deadline: the socket is polled a quarter of a
     * second at a time and, once the deadline has passed, the stream reports
     * its end, so a response that never finishes is returned as far as it got.
     */
    private static final class UntilDeadline extends InputStream {
        private final InputStream in;
        private final long deadline;
        UntilDeadline(InputStream in, Socket sock, long deadline) throws IOException {
            this.in = in;
            this.deadline = deadline;
            sock.setSoTimeout(250);
        }
        @Override public int read() throws IOException {
            byte[] one = new byte[1];
            int k = read(one, 0, 1);
            return k < 0 ? -1 : one[0] & 0xFF;
        }
        @Override public int read(byte[] b, int off, int len) throws IOException {
            while (true) {
                try { return in.read(b, off, len); }
                catch (SocketTimeoutException e) { if (System.currentTimeMillis() >= deadline) return -1; }
            }
        }
    }

    public static byte[] readResponse(InputStream in, String requestMethod) throws IOException {
        return readResponse(in, requestMethod, null, -1, null);
    }

    /**
     * Read headers, then body framed by Content-Length, chunked, or close.
     *
     * @param sock            the connection, for the streaming timeout; may be null
     * @param streamTimeoutMs how long a streaming response (an event stream, or one that only ends when the
     *                        server closes) is read for: 0 for as long as it runs, -1 for the socket's own timeout
     * @param framed          if not null, element 0 is set when the response carried its own framing
     */
    public static byte[] readResponse(InputStream in, String requestMethod, Socket sock, int streamTimeoutMs,
                                      boolean[] framed) throws IOException {
        return readResponse(in, requestMethod, sock, streamTimeoutMs, framed, false);
    }

    /**
     * As above; {@code streamUrl} says the URL is one of those listed as returning a streaming response.
     * If {@code framed} has a second element it is set when the response was read as a stream.
     */
    public static byte[] readResponse(InputStream in, String requestMethod, Socket sock, int streamTimeoutMs,
                                      boolean[] framed, boolean streamUrl) throws IOException {
        ByteArrayOutputStream head = new ByteArrayOutputStream();
        int state = 0;
        while (state < 4) {
            int b = in.read();
            if (b < 0) break;
            head.write(b);
            if ((state == 0 || state == 2) && b == 13) state++;
            else if ((state == 1 || state == 3) && b == 10) state++;
            else if (b == 10) state = (state == 2) ? 4 : 2;
            else state = 0;
            if (head.size() > 512 * 1024) break;
        }
        byte[] headBytes = head.toByteArray();
        if (headBytes.length == 0) return new byte[0];

        HttpMessage probe = new HttpMessage(headBytes);
        int status = probe.statusCode();
        boolean noBody = "HEAD".equalsIgnoreCase(requestMethod)
                || status == 204 || status == 304 || (status >= 100 && status < 200);
        if (noBody) { if (framed != null) framed[0] = true; return headBytes; }

        ByteArrayOutputStream body = new ByteArrayOutputStream();
        // One scratch buffer for every body framing below; sizes claimed in
        // framing headers are never trusted for allocation.
        byte[] buf = new byte[8192];
        String te = probe.header("Transfer-Encoding");
        String cl = probe.header("Content-Length");
        boolean chunked = te != null && te.toLowerCase(Locale.ROOT).contains("chunked");
        String type = probe.header("Content-Type");
        boolean endless = streamUrl || (NetworkConfig.eventStreamsStream() && type != null
                && type.toLowerCase(Locale.ROOT).contains("text/event-stream"));
        boolean streaming = endless || (!chunked && cl == null);
        if (streaming && sock != null && streamTimeoutMs >= 0) {
            if (streamTimeoutMs == 0) sock.setSoTimeout(0);
            else in = new UntilDeadline(in, sock, System.currentTimeMillis() + streamTimeoutMs);
        } else if (streaming && sock != null) {
            // A tool that does not follow streams: one that never ends is given a moment and then left;
            // an open-ended response is read until the server has been quiet for the open-ended timeout.
            if (endless) in = new UntilDeadline(in, sock, System.currentTimeMillis() + 2000);
            else { int quiet = NetworkConfig.openEndedMs(); if (quiet > 0) sock.setSoTimeout(quiet); }
        }
        if (framed != null) framed[0] = !streaming && (chunked || cl != null);
        if (framed != null && framed.length > 1) framed[1] = endless;

        if (te != null && te.toLowerCase(Locale.ROOT).contains("chunked")) {
            // A streaming response may keep its chunk framing, so each piece is seen as the server sent it.
            boolean keepFraming = endless && !NetworkConfig.stripsChunked();
            while (true) {
                String line = readLine(in);
                if (line == null) break;
                if (keepFraming) body.write(Bytes.bytes((line.endsWith("\r") ? line.substring(0, line.length() - 1) : line) + "\r\n"));
                String sz = line.trim();
                int semi = sz.indexOf(';');
                if (semi >= 0) sz = sz.substring(0, semi);
                int n;
                try { n = Integer.parseInt(sz.trim(), 16); } catch (Exception e) { break; }
                if (n < 0) break;
                if (n == 0) { readLine(in); if (keepFraming) body.write(Bytes.bytes("\r\n")); break; }
                // Never allocate from the server's chunk-size claim; stream the
                // bytes that actually arrive through a small buffer.
                int remaining = n;
                boolean complete = true;
                while (remaining > 0) {
                    int k = in.read(buf, 0, Math.min(buf.length, remaining));
                    if (k < 0) { complete = false; break; }
                    body.write(buf, 0, k);
                    remaining -= k;
                }
                readLine(in);
                if (!complete) break;
                if (keepFraming) body.write(Bytes.bytes("\r\n"));
            }
            if (keepFraming) return Bytes.concat(headBytes, body.toByteArray());
            byte[] merged = Bytes.concat(headBytes, body.toByteArray());
            HttpMessage m = new HttpMessage(merged);
            m.removeHeader("Transfer-Encoding");
            m.setHeader("Content-Length", String.valueOf(body.size()));
            return m.raw();
        }

        if (cl != null) {
            int n;
            try { n = Integer.parseInt(cl.trim()); } catch (Exception e) { n = -1; }
            if (n >= 0) {
                int remaining = n;
                while (remaining > 0) {
                    int k = in.read(buf, 0, Math.min(buf.length, remaining));
                    if (k < 0) break;
                    body.write(buf, 0, k);
                    remaining -= k;
                }
                return Bytes.concat(headBytes, body.toByteArray());
            }
        }

        try {
            int k;
            while ((k = in.read(buf)) > 0) body.write(buf, 0, k);
        } catch (SocketTimeoutException ignored) {
        }
        return Bytes.concat(headBytes, body.toByteArray());
    }

    private static String readLine(InputStream in) throws IOException {
        ByteArrayOutputStream b = new ByteArrayOutputStream();
        int c;
        while ((c = in.read()) >= 0) {
            if (c == 10) break;
            b.write(c);
        }
        if (c < 0 && b.size() == 0) return null;
        return Bytes.str(b.toByteArray());
    }

    /** Replace a compressed body with its plaintext, dropping the header. */
    public static void unpack(HttpMessage m) {
        String ce = m.header("Content-Encoding");
        if (ce == null) return;
        String enc = ce.trim().toLowerCase(Locale.ROOT);
        byte[] body = m.body();
        if (body.length == 0) return;
        try {
            InputStream src = new ByteArrayInputStream(body);
            InputStream dec;
            if (enc.contains("gzip")) dec = new GZIPInputStream(src);
            else if (enc.contains("deflate")) dec = new InflaterInputStream(src);
            else if (enc.contains("br")) dec = new org.brotli.dec.BrotliInputStream(src);
            else return;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[8192];
            int k;
            while ((k = dec.read(buf)) > 0) out.write(buf, 0, k);
            m.removeHeader("Content-Encoding");
            m.setBody(out.toByteArray());
            m.setHeader("Content-Length", String.valueOf(out.size()));
        } catch (Exception | LinkageError e) {
            // A body that will not decode stays as received; trace it rather
            // than dropping the failure silently. LinkageError covers a
            // missing decoder jar, which must not kill the calling thread.
            Debug.log("could not decode " + enc + " body: " + e);
        }
    }
}