Skip to content

udpnat2: Fix losing the first packet of a new flow - #120

Open
janeblower wants to merge 2 commits into
SagerNet:devfrom
janeblower:udpnat2-first-packet
Open

janeblower wants to merge 2 commits into
SagerNet:devfrom
janeblower:udpnat2-first-packet

Conversation

@janeblower

Copy link
Copy Markdown

Service.NewPacket reads conn.handler under handlerAccess.RLock() but releases the lock before it queues the packet (service.go#L69-L72, service.go#L91-L96). The connection handler goroutine started for a new flow calls SetHandler as soon as copying starts. If that happens between the read and the send, SetHandler drains a still-empty packetChan, and the packet is then queued into a channel nobody reads any more, because the connection is in push mode now. The first packet of the flow is lost.

In sing-box v1.14.6 a single-datagram exchange through tproxy (one DNS query, one UDP ping) sometimes gets no answer because of this. I hit it in about 1 of 10 runs of my end-to-end suite on shared CI runners.

The fix keeps the read lock until the packet is queued, so SetHandler runs either before the read (the packet goes straight to the handler) or after the send (its drain picks the packet up). The handler itself is still called without the lock.

The new test causes evictions, and with them the race detector reported a second, older race: Close read c.handler without the lock while SetHandler wrote it. The first commit fixes that, so the package is clean under -race.

TestServiceDeliversFirstPacket opens 100000 flows with one packet each, with a handler that calls SetHandler right away:

go test go test -race
main fails, 53–70 lost fails: data race in Close
main + first commit fails, 44–57 lost fails, 1759–1920 lost
this branch passes passes

go vet ./common/udpnat2/ is clean.

NewPacket released handlerAccess before queueing the packet, so a
SetHandler in between drained an empty queue and the packet was left
in a channel nobody reads.
@nekohasekai
nekohasekai force-pushed the dev branch 2 times, most recently from 355b3af to 35ad80e Compare December 3, 2026 12:21
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.

1 participant