tunnel: add -keepalive-timeout-secs for dead connection detection

Tracks last server receive time (atomic) and runs a watchdog goroutine
that closes the connection if no data arrives within the timeout,
triggering reconnection. Also fixes Close() to guard Conn.Close()
inside sync.Once so concurrent/repeated calls are safe.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Git Sagar 2026-07-11 11:54:12 -03:00
parent c248661eaf
commit 20f41353e7
5 changed files with 57 additions and 18 deletions

View file

@ -37,6 +37,7 @@ func main() {
acceptDNS := flag.Bool("accept-dns", false, "Set /etc/resolv.conf from DHCP-provided DNS servers")
policyRouteTable := flag.Int("policy-route-table", 0, "Policy routing table: route replies from VPN IP back through VPN gateway")
connMark := flag.Bool("connmark", false, "Use CONNMARK to route DNAT reply traffic back through VPN (for port forwards to namespaces/VMs)")
keepaliveTimeout := flag.Int("keepalive-timeout-secs", 0, "Close connection if no data from server within N seconds (0 = disabled)")
flag.Parse()
@ -99,7 +100,7 @@ func main() {
}
for {
err := runSession(cfg, dev, mac, netOpts, sig)
err := runSession(cfg, dev, mac, netOpts, time.Duration(*keepaliveTimeout)*time.Second, sig)
if err == errShutdown {
log.Println("shutting down")
return

View file

@ -15,7 +15,7 @@ import (
var errShutdown = fmt.Errorf("shutdown requested")
func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts netcfg.Options, sig chan os.Signal) error {
func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts netcfg.Options, keepaliveTimeout time.Duration, sig chan os.Signal) error {
log.Printf("connecting to %s:%d hub=%s user=%s", cfg.Host, cfg.Port, cfg.Hub, cfg.Username)
sess, err := client.Connect(cfg)
@ -24,7 +24,7 @@ func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts n
}
log.Printf("connected: session=%s connection=%s", sess.SessionName, sess.ConnectionName)
tunnel := client.NewTunnel(sess)
tunnel := client.NewTunnel(sess, keepaliveTimeout)
tunnel.StartKeepalive()
defer tunnel.Close()