fix: release pending kcp sessions when the listener is closed (#5575)

KCPListener hands accepted sessions to a consumer through an unbuffered
channel, but its accept goroutine wrote to that channel without watching for
shutdown. A Close racing with a handoff left the goroutine blocked forever,
holding the session it was about to deliver, because closing the underlying
listener does not unblock a send. The close flag it read was also written by
Close without synchronisation.

Watch a done channel in the handoff and close the connection that was never
delivered, so the goroutine can exit and the session is released. Accept now
returns ErrKCPListenerClosed as soon as the listener is closed instead of
blocking on the channel, and the close state is a done channel guarded by
sync.Once.

A ready handoff can still win the race with Close; the session then belongs to
the caller of Accept, matching how WebsocketListener behaves.

Tests cover a pending handoff that is cancelled by Close and a blocked Accept
that is woken by it.
This commit is contained in:
fatedier
2026-10-19 13:20:00 +08:00
committed by GitHub
parent 399bf2ce4c
commit 228d23b3d5
2 changed files with 168 additions and 18 deletions
+37 -18
View File
@@ -15,16 +15,21 @@
package net
import (
"fmt"
"errors"
"net"
"sync"
kcp "github.com/xtaci/kcp-go/v5"
)
var ErrKCPListenerClosed = errors.New("kcp listener closed")
type KCPListener struct {
listener net.Listener
acceptCh chan net.Conn
closeFlag bool
listener net.Listener
acceptCh chan net.Conn
done chan struct{}
closeOnce sync.Once
}
func ListenKcp(address string) (l *KCPListener, err error) {
@@ -36,20 +41,21 @@ func ListenKcp(address string) (l *KCPListener, err error) {
_ = listener.SetWriteBuffer(4194304)
l = &KCPListener{
listener: listener,
acceptCh: make(chan net.Conn),
closeFlag: false,
listener: listener,
acceptCh: make(chan net.Conn),
done: make(chan struct{}),
}
go func() {
for {
conn, err := listener.AcceptKCP()
if err != nil {
if l.closeFlag {
close(l.acceptCh)
select {
case <-l.done:
return
default:
continue
}
continue
}
conn.SetStreamMode(true)
conn.SetWriteDelay(true)
@@ -58,25 +64,38 @@ func ListenKcp(address string) (l *KCPListener, err error) {
conn.SetWindowSize(1024, 1024)
conn.SetACKNoDelay(false)
l.acceptCh <- conn
select {
case <-l.done:
conn.Close()
return
case l.acceptCh <- conn:
// A ready handoff may win when Close races with it. Once delivered,
// the connection is owned by the caller of Accept.
}
}
}()
return l, err
}
func (l *KCPListener) Accept() (net.Conn, error) {
conn, ok := <-l.acceptCh
if !ok {
return conn, fmt.Errorf("channel for kcp listener closed")
select {
case <-l.done:
return nil, ErrKCPListenerClosed
default:
}
select {
case <-l.done:
return nil, ErrKCPListenerClosed
case conn := <-l.acceptCh:
return conn, nil
}
return conn, nil
}
func (l *KCPListener) Close() error {
if !l.closeFlag {
l.closeFlag = true
l.closeOnce.Do(func() {
close(l.done)
l.listener.Close()
}
})
return nil
}