diff --git a/engine/engine.go b/engine/engine.go index 2284d67..6f7b743 100644 --- a/engine/engine.go +++ b/engine/engine.go @@ -123,6 +123,10 @@ func general(k *Key) error { log.Infof("[DIALER] set fwmark: %#x", k.Mark) } + if k.TCPWaitTimeout > 0 { + tunnel.SetTCPWaitTimeout(k.TCPWaitTimeout) + } + if k.UDPTimeout > 0 { if k.UDPTimeout < time.Second { return errors.New("invalid udp timeout value") diff --git a/engine/key.go b/engine/key.go index fcbfcd7..bc77500 100644 --- a/engine/key.go +++ b/engine/key.go @@ -13,6 +13,7 @@ type Key struct { TCPModerateReceiveBuffer bool `yaml:"tcp-moderate-receive-buffer"` TCPSendBufferSize string `yaml:"tcp-send-buffer-size"` TCPReceiveBufferSize string `yaml:"tcp-receive-buffer-size"` + TCPWaitTimeout time.Duration `yaml:"tcp-wait-timeout"` UDPRelayBufferSize string `yaml:"udp-relay-buffer-size"` UDPTimeout time.Duration `yaml:"udp-timeout"` TUNPreUp string `yaml:"tun-pre-up"` diff --git a/main.go b/main.go index e7aa992..8573c72 100644 --- a/main.go +++ b/main.go @@ -37,6 +37,7 @@ func init() { flag.StringVar(&key.TCPReceiveBufferSize, "tcp-rcvbuf", "", "Set TCP receive buffer size for netstack") flag.StringVar(&key.UDPRelayBufferSize, "udp-rlybuf", "", "Set UDP relay buffer size for tunnel") flag.BoolVar(&key.TCPModerateReceiveBuffer, "tcp-auto-tuning", false, "Enable TCP receive buffer auto-tuning") + flag.DurationVar(&key.TCPWaitTimeout, "tcp-wait-timeout", 0, "Set timeout before closing each TCP connection") flag.StringVar(&key.TUNPreUp, "tun-pre-up", "", "Execute a command before TUN device setup") flag.StringVar(&key.TUNPostUp, "tun-post-up", "", "Execute a command after TUN device setup") flag.BoolVar(&versionFlag, "version", false, "Show version and then quit") diff --git a/tunnel/tcp.go b/tunnel/tcp.go index e540cb1..32b7fbb 100644 --- a/tunnel/tcp.go +++ b/tunnel/tcp.go @@ -16,9 +16,11 @@ import ( "github.com/xjasonlyu/tun2socks/v2/tunnel/statistic" ) -const ( - tcpWaitTimeout = 5 * time.Second -) +var _tcpWaitTimeout = 5 * time.Second + +func SetTCPWaitTimeout(t time.Duration) { + _tcpWaitTimeout = t +} func handleTCPConn(localConn adapter.TCPConn) { defer localConn.Close() @@ -60,7 +62,7 @@ func relay(left, right net.Conn) error { if err := copyBuffer(right, left); err != nil { leftErr = errors.Join(leftErr, err) } - right.SetReadDeadline(time.Now().Add(tcpWaitTimeout)) + right.SetReadDeadline(time.Now().Add(_tcpWaitTimeout)) }() go func() { @@ -68,7 +70,7 @@ func relay(left, right net.Conn) error { if err := copyBuffer(left, right); err != nil { rightErr = errors.Join(rightErr, err) } - left.SetReadDeadline(time.Now().Add(tcpWaitTimeout)) + left.SetReadDeadline(time.Now().Add(_tcpWaitTimeout)) }() wg.Wait()