From 76e2ce011d94b6f553ee925be51756a84f6de631 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=96=E7=95=8C?= Date: Mon, 8 Apr 2024 17:26:08 +0800 Subject: [PATCH] Add control.SetKeepAlivePeriod --- common/control/tcp_keep_alive_linux.go | 29 ++++++++++++++++++++++++++ common/control/tcp_keep_alive_stub.go | 11 ++++++++++ 2 files changed, 40 insertions(+) create mode 100644 common/control/tcp_keep_alive_linux.go create mode 100644 common/control/tcp_keep_alive_stub.go diff --git a/common/control/tcp_keep_alive_linux.go b/common/control/tcp_keep_alive_linux.go new file mode 100644 index 00000000..7c84a67c --- /dev/null +++ b/common/control/tcp_keep_alive_linux.go @@ -0,0 +1,29 @@ +package control + +import ( + "syscall" + "time" + _ "unsafe" + + E "github.com/sagernet/sing/common/exceptions" + N "github.com/sagernet/sing/common/network" + + "golang.org/x/sys/unix" +) + +func SetKeepAlivePeriod(idle time.Duration, interval time.Duration) Func { + return func(network, address string, conn syscall.RawConn) error { + if N.NetworkName(network) != N.NetworkTCP { + return nil + } + return Raw(conn, func(fd uintptr) error { + return E.Errors( + unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_KEEPIDLE, int(roundDurationUp(idle, time.Second))), + unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_KEEPINTVL, int(roundDurationUp(interval, time.Second))), + ) + }) + } +} + +//go:linkname roundDurationUp net.roundDurationUp +func roundDurationUp(d time.Duration, to time.Duration) time.Duration diff --git a/common/control/tcp_keep_alive_stub.go b/common/control/tcp_keep_alive_stub.go new file mode 100644 index 00000000..180d8d3f --- /dev/null +++ b/common/control/tcp_keep_alive_stub.go @@ -0,0 +1,11 @@ +//go:build !linux + +package control + +import ( + "time" +) + +func SetKeepAlivePeriod(idle time.Duration, interval time.Duration) Func { + return nil +}