Add configurable TCP keepalives to TCP listener and dialer
Exposes TCP keepalive configuration via listener and dialer metadata: keepalive: true keepalive.idle: 30s keepalive.interval: 10s keepalive.count: 6 When enabled, the OS sends keepalive probes after the idle period and tears down the socket if the remote does not respond. This causes any blocked Read() on a dead connection to return promptly, releasing goroutines and memory — covering both legs of a CONNECT tunnel (the inbound client connection via the listener, and the outbound upstream connection via the dialer). This is the correct alternative to a hard application-level read deadline (SetReadDeadline) for detecting dead connections, as it distinguishes truly dead connections from legitimately idle ones. Relates to: https://github.com/go-gost/x/issues/91
This commit is contained in:
@@ -47,6 +47,18 @@ func (d *tcpDialer) Dial(ctx context.Context, addr string, opts ...dialer.DialOp
|
||||
conn, err := options.Dialer.Dial(ctx, "tcp", addr)
|
||||
if err != nil {
|
||||
d.logger.Error(err)
|
||||
return conn, err
|
||||
}
|
||||
|
||||
if d.md.keepalive {
|
||||
if tc, ok := conn.(*net.TCPConn); ok {
|
||||
tc.SetKeepAliveConfig(net.KeepAliveConfig{
|
||||
Enable: true,
|
||||
Idle: d.md.keepaliveIdle,
|
||||
Interval: d.md.keepaliveInterval,
|
||||
Count: d.md.keepaliveCount,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
conn = proxyproto.WrapClientConn(
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"time"
|
||||
|
||||
md "github.com/go-gost/core/metadata"
|
||||
mdutil "github.com/go-gost/x/metadata/util"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -16,8 +17,17 @@ const (
|
||||
|
||||
type metadata struct {
|
||||
dialTimeout time.Duration
|
||||
|
||||
keepalive bool
|
||||
keepaliveIdle time.Duration
|
||||
keepaliveInterval time.Duration
|
||||
keepaliveCount int
|
||||
}
|
||||
|
||||
func (d *tcpDialer) parseMetadata(md md.Metadata) (err error) {
|
||||
d.md.keepalive = mdutil.GetBool(md, "keepalive")
|
||||
d.md.keepaliveIdle = mdutil.GetDuration(md, "keepalive.idle")
|
||||
d.md.keepaliveInterval = mdutil.GetDuration(md, "keepalive.interval")
|
||||
d.md.keepaliveCount = mdutil.GetInt(md, "keepalive.count")
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user