Skip to content

XHTTP: add opt-in downlink keepalive (scStreamDownServerSecs) - #6422

Closed
vadimsky-ctrl wants to merge 1 commit into
XTLS:mainfrom
vadimsky-ctrl:xhttp-downlink-keepalive
Closed

vadimsky-ctrl wants to merge 1 commit into
XTLS:mainfrom
vadimsky-ctrl:xhttp-downlink-keepalive

Conversation

@vadimsky-ctrl

Copy link
Copy Markdown

Refs #4846.

Motivation

XHTTP's server→client ("download") leg is a single long-lived HTTP response whose body is a raw byte stream. Many CDNs / reverse proxies keep an idle streaming response open only for a limited time and then cut it (Cloudflare's documented limit is 100s; some edges are much shorter). Traffic that sends a request and then waits quietly for a delayed or server-pushed response — interactive apps, long-poll, anything that idles between messages — gets its download stream torn down during the quiet window; the session then looks dead and the app times out. Continuous/bulk traffic never idles long enough to trip it, which is why this only bites some workloads.

There is no server→client keepalive in any XHTTP mode today:

  • the download branch in hub.go writes response headers, flushes once, then blocks on select{ctx.Done()/Wait()}; bytes flow only on real proxied data;
  • scStreamUpServerSecs writes padding into the uplink POST's response — a different stream, discarded by the client — so it can't keep the download alive;
  • the client reads the download as a raw stream (resp.Body), so injecting keepalive bytes into it would corrupt the tunnel;
  • the edge→origin hop is frequently HTTP/1.1, so there's no byte-less HTTP/2 frame to lean on — a keepalive has to be real bytes the client can identify and strip.

This is exactly the prerequisite named in #4846:

Once there's a custom downlink wrapping format, HTTP downlink can stay alive, won't be cut off by CDN's 100s inactivity.

This PR adds that minimal wrapping format and uses it for keepalive. It is intentionally scoped to keepalive; the broader #4846 goals (multi-path downlink aggregation, retransmission, ACK/connection-migration) are out of scope and the frame type space is left open for them.

What it does

A new opt-in xhttpSettings field scStreamDownServerSecs (RangeConfig, mirroring scStreamUpServerSecs):

  • Unset / To == 0 (default): OFF. The download stays a raw byte stream, byte-for-byte identical to current releases. Zero behavior change.
  • Set on both ends: the server wraps the download body in a minimal length-prefixed frame format and emits a keepalive frame whenever the download has been idle for the (randomised) interval; the client strips the framing. The value is the server keepalive interval in seconds (a range → jitter); choose it below the intermediary's idle-cut threshold. Like mode / padding, it must match on both ends.

Wire format (download body, when enabled)

+--------+-----------------+==========================+
| type   | length (uint16) | payload (length bytes)   |
| 1 byte | big-endian      |                          |
+--------+-----------------+==========================+
  type 0x00 DATA       payload = proxied downlink bytes
  type 0x01 KEEPALIVE  payload = padding, discarded by the client

Only the response body is framed; HTTP status / headers are unchanged. The keepalive is idle-gated — an active download carries zero keepalive overhead — and the goroutine mirrors the existing scStreamUpServerSecs goroutine idiom, exiting promptly on request-context cancel / stream close.

Changes

  • transport/internet/splithttp/downlink.go (new): frame constants, downlinkWriter (server encode + idle-gated keepalive), downlinkReader (client decode / strip). Plus downlink_test.go (round-trip, >64KB chunking, byte-at-a-time reassembly, unknown-type rejection, clean EOF).
  • hub.go: in the download branch, when enabled, wrap conn.writer and start the keepalive goroutine.
  • client.go: wrap the !uploadOnly download resp.Body (one site covers packet-up, stream-up and stream-one downlinks).
  • config.proto / config.pb.go, config.go (DownlinkKeepAliveEnabled()), infra/conf/transport_internet.go (JSON field).

(The larger line counts in config.pb.go and transport_internet.go are gofmt re-aligning the struct-tag column because the new field name is longer than the alignment width — no logic there.)

Back-compat

OFF by default and gated on ScStreamDownServerSecs != nil && To > 0, so both proto- and JSON-built configs default to OFF and are unchanged. Enabling requires setting the field on both ends (documented). Browser-dialer downlink uses a separate read path and is out of scope (don't enable it there).

Evidence

Measured against a real caching CDN edge that force-buffers and idle-cuts the XHTTP download at ~30s (edge→origin was plain HTTP/1.1, so the keepalive frames are visible on the wire). One request whose response is deliberately delayed 40s (download idle 40s), 5 concurrent tunnels, classified by whether the post-idle response arrived:

path keepalive 40s-idle response
direct (no CDN) off 3/3 arrive (t≈40s)
via the CDN edge off 0/5 arrive — cut at t≈30s
via the CDN edge on 5/5 arrive (t≈40s)

Direct proves the origin / xray never cuts an idle download; via-edge-OFF reproduces the CDN idle-cut (stock behavior); via-edge-ON fixes it. A short (3s) request survives in all cases, confirming framing doesn't disturb normal traffic.

Wire capture on the edge→origin hop during the 40s idle (plain HTTP, so the keepalive frames are in cleartext) — origin→edge packets:

t+0s   len=107,197   request setup + response headers
t+5s   len=13        keepalive
t+7s   len=12        keepalive
t+9s   len=13        keepalive
t+7s   len=15        keepalive
t+5s   len=11        keepalive
t+7s   len=14        keepalive
t+5s   len=151       the delayed response (arrives at t≈40s)

Six keepalive frames at 5–10s (the configured randomised interval) held the edge's ~30s idle timer off; the response then arrived intact.

Notes for review

  • The format is deliberately minimal and forward-compatible via the type byte; happy to align the wire format with your broader "multi-path downlink" / packet-down plans for [feature request] XHTTP Support packet down & retransmission #4846 (SEQ / ACK / retransmission frame types), or to change naming / placement — this PR only intends to land the keepalive primitive that [feature request] XHTTP Support packet down & retransmission #4846 identifies as the first payoff of a downlink wrapping format.
  • downlinkWriter.Write currently allocates + copies each frame to emit header and payload in one write; a small buffer pool is an easy follow-up if the throughput of the enabled path matters.

Adds a minimal, opt-in downlink wrapping format so the XHTTP server->client stream can carry in-band keepalive frames, keeping an otherwise-idle download from being cut by buffering / inactivity-timeout intermediaries (e.g. CDNs). OFF by default; when off the download is a raw byte stream, byte-for-byte identical to before. Refs XTLS#4846.
@Fangliding

Copy link
Copy Markdown
Member

仅仅为了保活过久不活动的下行连接引入一个帧格式是不合适的(

@Fangliding Fangliding closed this Jul 2, 2026
Medium1992 pushed a commit to Medium1992/Xray-core-fork that referenced this pull request Sep 13, 2026
The stream-down GET is the lifetime of a session, so a middlebox that resets it
takes the tunneled connection with it. CDN edges do exactly that: XTLS#4846 measures
an idle timer on the response stream at 10s (VK Cloud), 30s (Timeweb), 60s
(Yandex Cloud) and 125.5s (Cloudflare), and none of them tells the origin. The
case that bites hardest is an upload, where the download leg carries nothing,
idles for the whole transfer, and is cut; the upload dies with it.

scDownlinkResume lets a session outlive individual stream-down requests. The
server retains what the client has not acknowledged, a reconnecting client asks
to continue from the offset it actually received, and every uplink request
carries that offset so retention is released as it is confirmed.
scMaxDownlinkSecs additionally closes the stream before the edge does, the
rotation named in XTLS#4846.

Retention covers what a cut can lose, not throughput: an idling downlink holds
almost nothing, while a transfer at full rate outruns any window a server can
afford per session and falls back to today's behaviour. The default is 256 KiB
of pooled buffers per session, returned to the pool as they are acknowledged.

Because a resuming client cannot tell a cut stream from a finished one, the
session outlives the tunnel for a grace period: a client that reconnects after
the last bytes is answered with 204 and ends as it would on a complete
response, and anything it had not received yet is still replayed.

This needs no downlink wrapping format, unlike XTLS#6422: the offset travels in the
placement already used for sessionID and the response body is untouched. A
Range request would be the obvious alternative, but CDN edges answer those
themselves and strip them before the origin, which would silently replay a
stream from the wrong offset. The server therefore echoes the offset only when
it arrived, so a path that drops it is indistinguishable from a server without
the feature, and a stream-down request for a session that has already sent
something but carries no offset is refused rather than replayed from zero.

Off by default and gated on both ends like mode. If only one side enables it,
the client sees the server did not acknowledge it, stops resuming and behaves as
it does today. A resume the server can no longer serve is answered with 410 and
the connection fails cleanly rather than retrying.
Medium1992 pushed a commit to Medium1992/Xray-core-fork that referenced this pull request Sep 13, 2026
The stream-down GET is the lifetime of a session, so a middlebox that resets it
takes the tunneled connection with it. CDN edges do exactly that: XTLS#4846 measures
an idle timer on the response stream at 10s (VK Cloud), 30s (Timeweb), 60s
(Yandex Cloud) and 125.5s (Cloudflare), and none of them tells the origin. The
case that bites hardest is an upload, where the download leg carries nothing,
idles for the whole transfer, and is cut; the upload dies with it.

scDownlinkResume lets a session outlive individual stream-down requests. The
server retains what the client has not acknowledged, a reconnecting client asks
to continue from the offset it actually received, and every uplink request
carries that offset so retention is released as it is confirmed.
scMaxDownlinkSecs additionally closes the stream before the edge does, the
rotation named in XTLS#4846.

Retention covers what a cut can lose, not throughput: an idling downlink holds
almost nothing, while a transfer at full rate outruns any window a server can
afford per session and falls back to today's behaviour. The default is 256 KiB
of pooled buffers per session, returned to the pool as they are acknowledged.

Because a resuming client cannot tell a cut stream from a finished one, the
session outlives the tunnel for a grace period: a client that reconnects after
the last bytes is answered with 204 and ends as it would on a complete
response, and anything it had not received yet is still replayed.

This needs no downlink wrapping format, unlike XTLS#6422: the offset travels in the
placement already used for sessionID and the response body is untouched. A
Range request would be the obvious alternative, but CDN edges answer those
themselves and strip them before the origin, which would silently replay a
stream from the wrong offset. The server therefore echoes the offset only when
it arrived, so a path that drops it is indistinguishable from a server without
the feature, and a stream-down request for a session that has already sent
something but carries no offset is refused rather than replayed from zero.

Off by default and gated on both ends like mode. If only one side enables it,
the client sees the server did not acknowledge it, stops resuming and behaves as
it does today. A resume the server can no longer serve is answered with 410 and
the connection fails cleanly rather than retrying.
Medium1992 added a commit to Medium1992/Xray-core-fork that referenced this pull request Sep 28, 2026
The stream-down GET is the lifetime of a session, so a middlebox that resets it
takes the tunneled connection with it. CDN edges do exactly that: XTLS#4846 measures
an idle timer on the response stream at 10s (VK Cloud), 30s (Timeweb), 60s
(Yandex Cloud) and 125.5s (Cloudflare), and none of them tells the origin. The
case that bites hardest is an upload, where the download leg carries nothing,
idles for the whole transfer, and is cut; the upload dies with it.

scDownlinkResume lets a session outlive individual stream-down requests. The
server retains what the client has not acknowledged, a reconnecting client asks
to continue from the offset it actually received, and every uplink request
carries that offset so retention is released as it is confirmed.
scMaxDownlinkSecs additionally closes the stream before the edge does, the
rotation named in XTLS#4846.

Retention covers what a cut can lose, not throughput: an idling downlink holds
almost nothing, while a transfer at full rate outruns any window a server can
afford per session and falls back to today's behaviour. The default is 256 KiB
of pooled buffers per session, returned to the pool as they are acknowledged.

Because a resuming client cannot tell a cut stream from a finished one, the
session outlives the tunnel for a grace period: a client that reconnects after
the last bytes is answered with 204 and ends as it would on a complete
response, and anything it had not received yet is still replayed.

This needs no downlink wrapping format, unlike XTLS#6422: the offset travels in the
placement already used for sessionID and the response body is untouched. A
Range request would be the obvious alternative, but CDN edges answer those
themselves and strip them before the origin, which would silently replay a
stream from the wrong offset. The server therefore echoes the offset only when
it arrived, so a path that drops it is indistinguishable from a server without
the feature, and a stream-down request for a session that has already sent
something but carries no offset is refused rather than replayed from zero.

Off by default and gated on both ends like mode. If only one side enables it,
the client sees the server did not acknowledge it, stops resuming and behaves as
it does today. A resume the server can no longer serve is answered with 410 and
the connection fails cleanly rather than retrying.
Medium1992 added a commit to Medium1992/Xray-core-fork that referenced this pull request Sep 28, 2026
The stream-down GET is the lifetime of a session, so a middlebox that resets it
takes the tunneled connection with it. CDN edges do exactly that: XTLS#4846 measures
an idle timer on the response stream at 10s (VK Cloud), 30s (Timeweb), 60s
(Yandex Cloud) and 125.5s (Cloudflare), and none of them tells the origin. The
case that bites hardest is an upload, where the download leg carries nothing,
idles for the whole transfer, and is cut; the upload dies with it.

scDownlinkResume lets a session outlive individual stream-down requests. The
server retains what the client has not acknowledged, a reconnecting client asks
to continue from the offset it actually received, and every uplink request
carries that offset so retention is released as it is confirmed.
scMaxDownlinkSecs additionally closes the stream before the edge does, the
rotation named in XTLS#4846.

Retention covers what a cut can lose, not throughput: an idling downlink holds
almost nothing, while a transfer at full rate outruns any window a server can
afford per session and falls back to today's behaviour. The default is 256 KiB
of pooled buffers per session, returned to the pool as they are acknowledged.

Because a resuming client cannot tell a cut stream from a finished one, the
session outlives the tunnel for a grace period: a client that reconnects after
the last bytes is answered with 204 and ends as it would on a complete
response, and anything it had not received yet is still replayed.

This needs no downlink wrapping format, unlike XTLS#6422: the offset travels in the
placement already used for sessionID and the response body is untouched. A
Range request would be the obvious alternative, but CDN edges answer those
themselves and strip them before the origin, which would silently replay a
stream from the wrong offset. The server therefore echoes the offset only when
it arrived, so a path that drops it is indistinguishable from a server without
the feature, and a stream-down request for a session that has already sent
something but carries no offset is refused rather than replayed from zero.

Off by default and gated on both ends like mode. If only one side enables it,
the client sees the server did not acknowledge it, stops resuming and behaves as
it does today. A resume the server can no longer serve is answered with 410 and
the connection fails cleanly rather than retrying.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants