Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions network/v2/sockopts.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ func setCommonSocketOptions(conn *net.TCPConn, keepAliveConfig net.KeepAliveConf
}

setCongestionControl(rawConn)
setTCPUserTimeout(rawConn, keepAliveConfig)

return nil
}
39 changes: 39 additions & 0 deletions network/v2/sockopts_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,50 @@
package network

import (
"net"
"syscall"
"time"

"golang.org/x/sys/unix"
)

// Go runtime defaults for KeepAliveConfig when fields are zero.
const (
goDefaultKeepAliveIdle = 15 * time.Second
goDefaultKeepAliveInterval = 15 * time.Second
goDefaultKeepAliveCount = 9
)

// setTCPUserTimeout sets TCP_USER_TIMEOUT on a socket. If transmitted
// data remains unacknowledged for this long, the kernel closes the
// connection. As recommended by Cloudflare
// (https://blog.cloudflare.com/when-tcp-sockets-refuse-to-die/),
// the value is computed as: keepidle + keepintvl * keepcnt. This
// ensures TCP_USER_TIMEOUT and keepalives agree on when to give up.
// Best-effort: silently ignored if unsupported.
func setTCPUserTimeout(conn syscall.RawConn, cfg net.KeepAliveConfig) {
idle := cfg.Idle
if idle == 0 {
idle = goDefaultKeepAliveIdle
}

interval := cfg.Interval
if interval == 0 {
interval = goDefaultKeepAliveInterval
}

count := cfg.Count
if count == 0 {
count = goDefaultKeepAliveCount
}

timeout := idle + interval*time.Duration(count)

conn.Control(func(fd uintptr) { //nolint: errcheck
unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_USER_TIMEOUT, int(timeout.Milliseconds())) //nolint: errcheck
})
}

func setCongestionControl(conn syscall.RawConn) {
conn.Control(func(fd uintptr) { //nolint: errcheck
// BBR provides better throughput over lossy and high-latency links compared
Expand Down
8 changes: 6 additions & 2 deletions network/v2/sockopts_nolinux.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

package network

import "syscall"
import (
"net"
"syscall"
)

func setCongestionControl(conn syscall.RawConn) {}
func setCongestionControl(conn syscall.RawConn) {}
func setTCPUserTimeout(conn syscall.RawConn, cfg net.KeepAliveConfig) {}
Loading