Skip to content

Hysteria client: Honor cancellation during dialing - #7119

Merged
RPRX merged 3 commits into
XTLS:mainfrom
svlavr:codex/hysteria-dial-cancellation
Oct 12, 2026
Merged

RPRX merged 3 commits into
XTLS:mainfrom
svlavr:codex/hysteria-dial-cancellation

Conversation

@svlavr

@svlavr svlavr commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #7107. This preserves its cleanup of clients owned by stopped instances and fixes cancellation of pending Hysteria dials.

When a Hysteria endpoint does not respond, closing a SOCKS5 UDP association cancels its context, but the transport can keep waiting for authentication or for another dial to release the shared client until the connection attempt completes or reaches its transport timeout.

This change:

  • passes the operation context to the HTTP/3 authentication request;
  • makes waiting for the client cancellable, using the existing semaphore implementation;
  • rechecks cancellation after acquiring access to the client;
  • waits for the asynchronous HTTP/3 dial callback before releasing provisional resources on authentication failure.

Reconnection after failure and forced closure from #7107 are preserved.

Validation on Windows/amd64, Go 1.27.0 (tests codex Astra 6.0):

  • New tests cover authentication cancellation and rejection, canceled/deadline-expired TCP and UDP waiters, reuse, and forced cleanup. They passed 10 ordinary and 10 race runs before rebasing; the 10 race runs were repeated on the current main base.
  • A separate local integration check uses an unmodified upstream SOCKS5 inbound, two UDP associations, and a silent UDP endpoint. Before the fix, both outbound dials remain after the associations close; with the fix, each dial exits when its association closes. This check was also repeated on the current main base.
  • Tests for transport/internet/hysteria/... and proxy/hysteria, targeted go vet, and formatting checks passed. proxy/hysteria has no package tests.

@RPRX

RPRX commented Oct 10, 2026

Copy link
Copy Markdown
Member

Dial 的 timeout 一般挺短的吧所以不急,发版后再看看

@Fangliding @LjhAUMEM

@RPRX
RPRX requested review from Fangliding and LjhAUMEM October 10, 2026 09:14
@svlavr

svlavr commented Oct 10, 2026

Copy link
Copy Markdown
Contributor Author

I tested the final code after #7107 was merged. I also looked at the extended version with tests in another fork. This PR builds on the merged fix.

For a single attempt to an unresponsive server, I agree: the handshake timeout is about 5 seconds. But a request waiting for the client mutex has no timeout of its own. In a test through the standard SOCKS5 inbound, both UDP associations were closed at about 1 second, yet the second, already-canceled request started a new QUIC connection attempt at about 5 seconds. Both dials finally exited at about 10 seconds.

With this fix, the canceled request stops waiting and never starts that extra attempt. The benefit is honoring cancellation and avoiding unnecessary connection attempts after the associations close. I’m not suggesting this needs to block the release.

@LjhAUMEM

Copy link
Copy Markdown
Contributor

多个 req.WithContext 和 resp.Body.Close 就行了,fixes #7120,话说 rt Close 是必须的吗,为什么官端没有,还有这 issue 怎么开的时间比这里晚

@LjhAUMEM

Copy link
Copy Markdown
Contributor

我直接来改吧,不用动了

@Fangliding

Copy link
Copy Markdown
Member

多个 req.WithContext 和 resp.Body.Close 就行了,fixes #7120,话说 rt Close 是必须的吗,为什么官端没有,还有这 issue 怎么开的时间比这里晚

有的人会开个pr还开个issue然后说fix xxx 挺诡异的 像是什么agent的standard ops

@Fangliding

Fangliding commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

还有dial底层quic连接期间 其他没拿到锁的小请求会被mutex锁住 不像这个pr里这样或者用 golang.org/x/sync/semaphore 的话 ctx 取消会无法返回
不过理论上很难遇到就是了

@LjhAUMEM

Copy link
Copy Markdown
Contributor

开个 issue 自己解决挺常见的,先 pr 后 issue 第一次见

握手就是要锁住啊,握手结束了后面的 tcp udp 直接走 steam datagram 了跟握手没关系了

@LjhAUMEM

Copy link
Copy Markdown
Contributor

semaphore 容量是 1 的话和 mutex 也没区别吧

@LjhAUMEM

Copy link
Copy Markdown
Contributor

OpenStream 和 udp session 都属于 lazy 不需要对端确认的,当初加 ctx 也是传给 dial 用的,OpenStream 本身也不支持 ctx

@Fangliding

Copy link
Copy Markdown
Member

握手就是要锁住啊,握手结束了后面的 tcp udp 直接走 steam datagram 了跟握手没关系了

假设握手比较极端要卡30s 一个请求来了拿到了dial权限 它的ctx传下去 ok
第二个来了要等 这时候第二个ctx取消了 调用者期望的肯定是第二个立即返回 但是ctx取消没法立刻唤醒在等的第二个

semaphore 容量是 1 的话和 mutex 也没区别吧

它是一个 channel 所以可以用 select 和 ctx.Done 一起等让 ctx 取消可以唤醒它 mutex 没有这种作用

@LjhAUMEM

Copy link
Copy Markdown
Contributor

假设握手比较极端要卡30s 一个请求来了拿到了dial权限 它的ctx传下去 ok
第二个来了要等 这时候第二个ctx取消了 调用者期望的肯定是第二个立即返回 但是ctx取消没法立刻唤醒在等的第二个

那么第一个如果是成功,第二个 stream 直接返回让 ctx 失效是预期结果,这时候 ctx 应该作用在上层的 proxy 上

如果是失败,继续拿 ctx 尝试 dial,ctx 会生效

@LjhAUMEM

Copy link
Copy Markdown
Contributor

才注意到分支名是 codex,看来 codex 也不能胜任 *ray 架构,握手结束后需要 ctx 的地方应该在上层的 proxy,不过命名 client 也确实有点误导 AI,总之先这样吧,rt Close 也懒得确认是不是必须的了,先加上

@svlavr

svlavr commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor Author

ce261f2 Currently, while A is connecting to the Hysteria server, request B waits for the mutex. Once A finishes, B either gets a stream or starts a dial, where its canceled context is then honored.

The remaining case is when B is canceled while A is still connecting. B keeps waiting even though it is no longer needed. This is reproducible through the standard SOCKS5 inbound by closing the second UDP association.

The semaphore with a select on ctx.Done() allowed B to stop waiting without canceling A, while still allowing only one connection attempt at a time. This is about waiting for the mutex before obtaining a stream, not about handling the context after the handshake.

@svlavr

svlavr commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Yes, I use Codex to check my ideas and prepare PRs. I find it convenient.

P.S. English is not my first language, so I apologize in advance for any inaccuracies in translation.

Also, I hadn't seen #7120.

@LjhAUMEM

Copy link
Copy Markdown
Contributor

看明白了,两个不同 ctx,可以在 dial 期间取消另一个,但是没必要啊,等待又不消耗资源,也不是并发 dial,不是并发 dial 为什么要构造两个不同 ctx?

@LjhAUMEM

Copy link
Copy Markdown
Contributor

官端也没有支持全 ctx https://github.com/HyNetworks/hysteria/blob/ca8fbd874fd6ca82413948de6dc5924405e103e1/app/internal/utils/update.go#L57-L58

我们这里能给 req 加上就不错了,全 ctx 需要把上层里的 proxy 握手也算上,我说了这里的 client 确实误导 AI 和官端的 client 是不同的,这里的 client 应该只是内部使用,不是给个 dest ctx 那种的 dial client

@svlavr

svlavr commented Oct 10, 2026

Copy link
Copy Markdown
Contributor Author

I am referring to the wait in client.udp(): first c.Lock(), then c.dial(ctx).

Two ordinary SOCKS5 UDP associations use the same Hysteria outbound. Xray creates a separate context for each association. A acquires the lock and starts connecting; B waits. When B is closed, Xray cancels its context, but c.Lock() keeps waiting until A releases the lock.

I tested this on ce261f2: after closing B, both dials remained pending; after closing A, both exited. I am not claiming a permanent leak or a large resource cost here. The issue is the delayed completion of a canceled request.

The semaphore with a select on ctx.Done() allowed B to stop waiting while A continued connecting. There was still only one handshake at a time.

@LjhAUMEM

Copy link
Copy Markdown
Contributor

你赢了,那就透传 ctx 吧

@svlavr

svlavr commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor Author

I don't see this as a victory ( We clarified a specific behavior.

The tests confirmed delayed completion of a canceled request. I did not establish significant CPU load or a memory leak from that waiting.

The benefit of the change is allowing an already-canceled request to finish while another request continues connecting.

@LjhAUMEM

Copy link
Copy Markdown
Contributor

想了一下以后实现大 Client dial(ctx, addr) 包括握手协议在内的也确实需要透传给底层的 dial read write,但是使用 chan struct{} 是我的底线,不要再进一步封装

I did not establish significant CPU load or a memory leak from that waiting.

你想确认也确认不了,等待也消耗资源就是语言的问题了

@RPRX
RPRX merged commit c1f8702 into XTLS:main Oct 12, 2026
@RPRX RPRX changed the title Hysteria client: Honor cancellation during dial Hysteria client: Honor cancellation during dialing Oct 12, 2026
RPRX pushed a commit that referenced this pull request Oct 12, 2026
Medium1992 pushed a commit to Medium1992/Xray-core-fork that referenced this pull request Oct 13, 2026
Upstream since v26.10.10: TUN inbound on Xray's own TCP/IP stack
instead of gVisor (XTLS#7130) and autoSystemDnsToGateway on FreeBSD (XTLS#7123),
Hysteria dial cancellation (XTLS#7119) and cleaner lock release (XTLS#7122),
golang.org/x/net 0.60.0 (XTLS#7133), inline Lua scripts and the base64
command (XTLS#7132), MASQUE client XMUX and Chrome's User-Agent (XTLS#7121).

Conflicts, resolved as follows:
- app/proxyman/inbound/inbound.go: XHTTP inbounds keep accepting
  Mux.Cool TCP sessions (docs/FORK.md); the XUDP-only rule now applies to
  MASQUE alone, as upstream added it there.
- app/router/router.go: upstream's compile-at-Init script engine, with the
  fork's PickRouteTag fields and needsSniffingAttributes reset kept.
- proxy/masque/client.go: upstream's onClose tunnel callback together with
  the fork's bounded ICMP queue; startTunnel takes the callback.
- transport/internet/hysteria/dialer.go: the fork's versions of XTLS#7119 and
  XTLS#7122 stay (docs/FORK.md), including closing the connection before the
  response body on a rejected authentication.
- go.mod, go.sum: the fork's newer x/net 0.61.0, crypto, sync, sys, text,
  tools.

NewXmuxManager keeps the fork's *XmuxConfig parameter; upstream's new
MASQUE and XMUX call sites pass a pointer.
Medium1992 pushed a commit to Medium1992/Xray-core-fork that referenced this pull request Oct 13, 2026
TaiLerV pushed a commit to TaiLerV/Xray-core-up that referenced this pull request Oct 13, 2026
Port of XTLS#7119 at 61faab4
(still open upstream), which also fixes XTLS#7120. A dial
waiting for a pooled client that another dial held through its QUIC
handshake and authentication ignored its context: a closed SOCKS5 UDP
association left its dial queued on the client lock, and once the lock
was free the dial started its own handshake for nobody. The handshake
and the authentication request ran without the dial's context, so the
holder kept the client until the handshake timed out (5 s) or, on a
server that stalled after the handshake, until the connection idled
out, and the cleaner waited as long.

The client lock is a one-slot channel, so tcp and udp wait for it or
for the dial's context; the cleaner still waits for it unconditionally.
The authentication request carries the dial's context. When RoundTrip
returns on cancellation, rt.Close joins HTTP/3's dial goroutine before
conn is read and the provisional transport and socket are closed. A
rejected authentication closes the response body, whose HTTP/3 request
watcher otherwise never returned: one goroutine leaked per rejected
dial.

Differences from the upstream head, recorded in docs/FORK.md:
- client.dial checks the context after the lock is taken, as svlavr's
  first commit (25699f6) and the upstream PR body describe. A done
  context and a free lock are both ready in the select, so without the
  check an already canceled dial can get a stream.
- A rejected authentication closes the QUIC connection with 0x101
  before the body and the HTTP/3 transport, as the official client
  (v2.13.0) and main do. Upstream's order ends the connection with
  code 0 and can send a stream cancellation before it.
- A comment states why rt.Close runs first on the error path.

Regression tests in dial_cancel_test.go, each failing on main:
- TestCanceledDialStopsWaitingForBusyClient/{tcp,udp}/{cancel,deadline}
- TestCanceledDialGetsNoConnection/{ready,new}_client/{tcp,udp}
- TestCanceledDialAbortsItsHandshake
- TestCanceledDialAbortsItsAuthentication
- TestRejectedAuthenticationLeaksNoGoroutine
- TestCleanerWaitingForCanceledDialFinishes
TestRejectedAuthenticationClosesWithProtocolError passes on main and
fails with upstream's order. The scenarios follow svlavr's tests in
25699f6. The fork's tests that took the client mutex use the channel.

Not ported: XTLS#7122; the fork's cleanOnce already cleans a
snapshot of the pool without the pool lock.

Co-authored-by: svlavr <[email protected]>
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.

4 participants