Skip to content

Fix net.Conn memory leak in case of Handshake error - #6087

Closed
excel23 wants to merge 1 commit into
XTLS:mainfrom
excel23:main
Closed

excel23 wants to merge 1 commit into
XTLS:mainfrom
excel23:main

Conversation

@excel23

@excel23 excel23 commented May 7, 2026

Copy link
Copy Markdown

On error, Handshake returns (nil, err) → conn becomes nil.
defer conn.Close() (declared above) attempts to close nil → panic.
The original connection (raw net.Conn) is lost but not closed → descriptor and memory leak.

What modification does:
The original conn is preserved before calling Handshake.
On error, the original connection is explicitly closed → no leak.
defer conn.Close() (the outer one) will no longer panic because conn did not become nil (the error returns before reassignment).

@excel23 excel23 changed the title Fix net.Conn memeory leak in case of Handshake error Fix net.Conn memory leak in case of Handshake error May 7, 2026
@Fangliding

Copy link
Copy Markdown
Member

这个pattern在core中被大量使用 不会有问题的 defer 要执行的函数从执行到那一行起就固定了

@Fangliding Fangliding closed this May 7, 2026
@excel23

excel23 commented May 7, 2026

Copy link
Copy Markdown
Author

After this modification, the memory leak that I analysed with pprof wasn't repeated. That was the error, I believe.
Could you look up these heap dumps?
xray_mem.zip

@Fangliding

Copy link
Copy Markdown
Member

提供一下goroutine的 pprof

@excel23

excel23 commented May 8, 2026 •

Copy link
Copy Markdown
Author

After the error repeated, I can say that the problem occurs when the system is configured to use VLESS Reality with mlkem768 encryption. If the connection is stable, everything works fine. But as soon as you turn off the connection, the memory leak appears. Here are the heap and goroutine dumps.
xray_base.zip
After modification leak is reduced, but not gone:
xray_mod.zip

@Fangliding

Fangliding commented May 8, 2026 •

Copy link
Copy Markdown
Member

try 1bae46b

@excel23

excel23 commented May 8, 2026

Copy link
Copy Markdown
Author

Yes, it fixes the heap and goroutine leak, even without my modifications.
I still think there is a minor bug in Handshake error handling in outbound.go, but at least it doesn't cause an uncontrollable leak.

@RPRX

RPRX commented May 9, 2026

Copy link
Copy Markdown
Member

I still think there is a minor bug in Handshake error handling in outbound.go, but at least it doesn't cause an uncontrollable leak.

你试下使用其它传输层(比如 WS)时有没有问题

BobJustFry pushed a commit to BobJustFry/xray-core that referenced this pull request Jun 7, 2026
wyusgw pushed a commit to wyusgw/Xray-core that referenced this pull request Sep 15, 2026
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.

3 participants