ping: Fix stale flows kept alive by unrelated ICMP traffic

Unconnected raw ICMP sockets receive every ICMP packet arriving at the
host, so any ICMP traffic refreshed the read deadline of every flow and
stale flows (with their raw sockets and goroutines) were only reclaimed
by LRU eviction while processing all host ICMP traffic in the meantime.

Expire flows based on their own activity only, and on Linux attach a
classic BPF ident filter to each raw socket so other flows' packets are
dropped in the kernel instead of waking every flow.
This commit is contained in:
世界 2026-07-09 22:07:14 +08:00
parent aae2f0750c
commit 30e535973b
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
7 changed files with 233 additions and 17 deletions

View file

@ -11,6 +11,7 @@ import (
"github.com/sagernet/sing-tun"
"github.com/sagernet/sing-tun/internal/gtcpip/header"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/control"
E "github.com/sagernet/sing/common/exceptions"
@ -29,6 +30,7 @@ type Destination struct {
destination netip.Addr
routeContext tun.DirectRouteContext
timeout time.Duration
lastActive common.TypedValue[time.Time]
requestAccess sync.Mutex
requests map[pingRequest]time.Time
}
@ -73,6 +75,7 @@ func ConnectDestination(
timeout: timeout,
requests: make(map[pingRequest]time.Time),
}
d.lastActive.Store(time.Now())
go d.loopRead()
return d, nil
}
@ -80,14 +83,21 @@ func ConnectDestination(
func (d *Destination) loopRead() {
defer d.Close()
for {
buffer := buf.NewSize(maxICMPPacketSize)
err := d.conn.SetReadDeadline(time.Now().Add(d.timeout))
deadline := d.lastActive.Load().Add(d.timeout)
if !time.Now().Before(deadline) {
return
}
err := d.conn.SetReadDeadline(deadline)
if err != nil {
d.logger.ErrorContext(d.ctx, E.Cause(err, "set read deadline for ICMP conn"))
}
buffer := buf.NewSize(maxICMPPacketSize)
err = d.conn.ReadIP(buffer)
if err != nil {
buffer.Release()
if E.IsTimeout(err) {
continue
}
if !E.IsClosed(err) {
d.logger.ErrorContext(d.ctx, E.Cause(err, "receive ICMP echo reply"))
}
@ -158,6 +168,7 @@ func (d *Destination) loopRead() {
}
d.logger.TraceContext(d.ctx, "read ICMPv6 echo reply from ", ipHdr.SourceAddr(), " to ", ipHdr.DestinationAddr(), " id ", icmpHdr.Ident(), " seq ", icmpHdr.Sequence())
}
d.lastActive.Store(time.Now())
err = d.routeContext.WritePacket(buffer.Bytes())
if err != nil {
d.logger.ErrorContext(d.ctx, E.Cause(err, "write ICMP echo reply"))
@ -167,6 +178,7 @@ func (d *Destination) loopRead() {
}
func (d *Destination) WritePacket(packet *buf.Buffer) error {
d.lastActive.Store(time.Now())
if !d.destination.Is6() {
ipHdr := header.IPv4(packet.Bytes())
if !ipHdr.IsValid(packet.Len()) {