From 1c5a1fbf70f3dcf834f58608d2998b62dce6d053 Mon Sep 17 00:00:00 2001 From: Roy Hill-Percival Date: Thu, 19 Nov 2026 02:57:32 -0500 Subject: [PATCH] TUN inbound: End UDP flows and cancel dispatches when the inbound closes (#7350) https://github.com/XTLS/Xray-core/pull/7350#pullrequestreview-5901009138 --- proxy/tun/handler.go | 10 +++++++++- proxy/tun/handler_test.go | 34 ++++++++++++++++++++++++++++++++ proxy/tun/stack.go | 5 +++++ proxy/tun/udp_fullcone.go | 23 ++++++++++++++++++++++ proxy/tun/udp_fullcone_test.go | 36 ++++++++++++++++++++++++++++++++++ 5 files changed, 107 insertions(+), 1 deletion(-) diff --git a/proxy/tun/handler.go b/proxy/tun/handler.go index 59b643b5d..b281991c7 100644 --- a/proxy/tun/handler.go +++ b/proxy/tun/handler.go @@ -25,7 +25,10 @@ import ( // Handler is managing object that tie together tun interface, ip stack and dispatch connections to the routing type Handler struct { + // ctx is detached from the instance's; cancel ends it, and with it every dispatch started from it, + // when the handler closes, since nothing else would ctx context.Context + cancel context.CancelFunc config *Config stack Stack tun Tun @@ -96,7 +99,7 @@ func (t *Handler) Init(ctx context.Context, pm policy.Manager, dispatcher routin t.sniffingRequest = content.SniffingRequest } - t.ctx = core.ToBackgroundDetachedContext(ctx) + t.ctx, t.cancel = context.WithCancel(core.ToBackgroundDetachedContext(ctx)) t.policyManager = pm t.dispatcher = dispatcher @@ -265,6 +268,11 @@ func (t *Handler) HandleConnection(conn net.Conn, destination net.Destination) { // Close implements common.Closable. func (t *Handler) Close() error { + // cancel first so every dispatch in flight unwinds, then close the stack (resets TCP, ends UDP flows) + // and the tun + if t.cancel != nil { + t.cancel() + } return errors.Combine(common.CloseIfExists(t.stack), common.CloseIfExists(t.tun)) } diff --git a/proxy/tun/handler_test.go b/proxy/tun/handler_test.go index cb7f642d9..9bf04df78 100644 --- a/proxy/tun/handler_test.go +++ b/proxy/tun/handler_test.go @@ -179,3 +179,37 @@ func TestHandlerCountsTunConnectionTraffic(t *testing.T) { t.Fatalf("connection write mismatch: got %q, want %q", got, "downlink") } } + +// a dispatcher that only returns when its context ends +type blockingDispatcher struct { + testDispatcher + entered chan struct{} +} + +func (d *blockingDispatcher) DispatchLink(ctx context.Context, dest xnet.Destination, link *transport.Link) error { + close(d.entered) + <-ctx.Done() + return ctx.Err() +} + +// Closing the handler must end a dispatch that is not reading its connection: the handler's context +// is detached from the instance's, so Close is what cancels it +func TestHandlerCloseCancelsDispatches(t *testing.T) { + dispatcher := &blockingDispatcher{entered: make(chan struct{})} + handler := &Handler{config: &Config{}, dispatcher: dispatcher} + handler.ctx, handler.cancel = context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + handler.HandleConnection(newTestConn(nil), xnet.TCPDestination(xnet.LocalHostIP, 443)) + close(done) + }() + <-dispatcher.entered + if err := handler.Close(); err != nil { + t.Fatal(err) + } + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("dispatch still running after Close") + } +} diff --git a/proxy/tun/stack.go b/proxy/tun/stack.go index 5048ae94c..6c935a55d 100644 --- a/proxy/tun/stack.go +++ b/proxy/tun/stack.go @@ -148,6 +148,11 @@ func (s *stack) Close() error { for _, u := range sockets { u.queue.close() } + // the UDP flows the other side opened are in neither conns nor sockets; end them too, or their + // dispatches and what they hold survive the instance + if s.udp != nil { + s.udp.closeAll() + } return nil } diff --git a/proxy/tun/udp_fullcone.go b/proxy/tun/udp_fullcone.go index 6a71f4b73..11fab6ed7 100644 --- a/proxy/tun/udp_fullcone.go +++ b/proxy/tun/udp_fullcone.go @@ -16,6 +16,8 @@ type udpConnectionHandler struct { sync.RWMutex udpConns map[net.Destination]*udpConn + // closed is set by closeAll; a packet that arrives after it opens no flow + closed bool handleConnection func(conn net.Conn, dest net.Destination) writePacket func(data []byte, src net.Destination, dst net.Destination) error @@ -51,6 +53,10 @@ func (u *udpConnectionHandler) HandlePacket(src net.Destination, dst net.Destina u.Lock() defer u.Unlock() + if u.closed { + data.Release() + return + } conn, found = u.udpConns[src] if !found { conn = &udpConn{handler: u, queue: newPacketQueue(udpQueueLimit), src: src, dst: dst} @@ -66,6 +72,23 @@ func (u *udpConnectionHandler) HandlePacket(src net.Destination, dst net.Destina } } +// closeAll ends every UDP flow and takes no new ones: the readers get EOF, so the dispatch of each flow +// returns and lets go of its outbound. Called when the stack closes; without it an inbound's UDP flows, +// and whatever carries them, outlive the instance. +func (u *udpConnectionHandler) closeAll() { + u.Lock() + u.closed = true + conns := make([]*udpConn, 0, len(u.udpConns)) + for _, c := range u.udpConns { + conns = append(conns, c) + } + u.udpConns = make(map[net.Destination]*udpConn) + u.Unlock() + for _, c := range conns { + c.queue.close() + } +} + func (u *udpConnectionHandler) connectionFinished(conn *udpConn) { u.Lock() // Close runs twice per flow; a newer conn may already own this src. diff --git a/proxy/tun/udp_fullcone_test.go b/proxy/tun/udp_fullcone_test.go index f764830d1..e8139a1b7 100644 --- a/proxy/tun/udp_fullcone_test.go +++ b/proxy/tun/udp_fullcone_test.go @@ -89,3 +89,39 @@ func TestPacketQueueDropsDrainedStorage(t *testing.T) { t.Fatalf("drained queue still holds %d slots", cap(q.items)) } } + +// A closing stack must end its UDP flows: the dispatch reading a flow gets EOF and returns, instead of +// waiting on the queue forever and keeping its outbound alive past the instance; a packet that arrives +// afterwards opens no flow. +func TestUDPHandlerCloseAllEndsFlows(t *testing.T) { + done := make(chan struct{}, 2) + handler := newUdpConnectionHandler(func(conn net.Conn, dest net.Destination) { + b := make([]byte, 2048) + for { + if _, err := conn.Read(b); err != nil { + done <- struct{}{} + return + } + } + }, func(data []byte, src net.Destination, dst net.Destination) error { return nil }) + dst := net.UDPDestination(net.IPAddress([]byte{10, 6, 0, 2}), 53) + for _, port := range []net.Port{40000, 40001} { + src := net.UDPDestination(net.IPAddress([]byte{10, 255, 0, 2}), port) + handler.HandlePacket(src, dst, buf.FromBytes([]byte("query"))) + } + handler.closeAll() + for i := 0; i < 2; i++ { + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatalf("flow %d still running after closeAll", i) + } + } + handler.HandlePacket(net.UDPDestination(net.IPAddress([]byte{10, 255, 0, 2}), 40002), dst, buf.FromBytes([]byte("late"))) + handler.RLock() + n := len(handler.udpConns) + handler.RUnlock() + if n != 0 { + t.Fatalf("%d flows in the table after closeAll", n) + } +}