From 353511df7fc345661635d7d40ae5f62c305fb12e Mon Sep 17 00:00:00 2001 From: James Tucker Date: Tue, 10 Nov 2026 22:20:42 +0000 Subject: [PATCH] net/{ktimeout,sockopts}: add explicit TCP settings application Provide a shared TCP configuration helper for future DERP, control, and log-upload socket policy. Apply optional keepalive and user-timeout settings before protocol wrapping, and report each result independently so callers can choose whether to fall back or reject a connection. Add a checked user-timeout setter that validates duration bounds and reports unsupported platforms or sockets instead of silently succeeding. Preserve the existing best-effort APIs and all service defaults. Reuse net.TCPConn keepalive configuration; do not introduce RTO tuning or infer hardware offload support. Test actual Linux socket settings on dialed and accepted connections, zero-config behavior, invalid values, partial failures, and timeout reset. Updates tailscale/corp#50948 Change-Id: I8151ab81b8630610ba3ef2e2ec54b62caebadf65 Signed-off-by: James Tucker --- cmd/k8s-operator/depaware.txt | 1 + cmd/tailscaled/depaware-min.txt | 1 + cmd/tailscaled/depaware-minbox.txt | 1 + cmd/tailscaled/depaware.txt | 1 + cmd/tsidp/depaware.txt | 1 + net/ktimeout/checked.go | 25 +++++++ net/ktimeout/checked_test.go | 45 ++++++++++++ net/ktimeout/ktimeout_default.go | 5 ++ net/ktimeout/ktimeout_linux.go | 10 +++ net/sockopts/tcp.go | 69 ++++++++++++++++++ net/sockopts/tcp_linux_test.go | 111 +++++++++++++++++++++++++++++ net/sockopts/tcp_test.go | 34 +++++++++ tsnet/depaware.txt | 1 + 13 files changed, 305 insertions(+) create mode 100644 net/ktimeout/checked.go create mode 100644 net/ktimeout/checked_test.go create mode 100644 net/sockopts/tcp.go create mode 100644 net/sockopts/tcp_linux_test.go create mode 100644 net/sockopts/tcp_test.go diff --git a/cmd/k8s-operator/depaware.txt b/cmd/k8s-operator/depaware.txt index 3a3c960d3..eb5bf96c6 100644 --- a/cmd/k8s-operator/depaware.txt +++ b/cmd/k8s-operator/depaware.txt @@ -807,6 +807,7 @@ tailscale.com/cmd/k8s-operator dependencies: (generated by github.com/tailscale/ tailscale.com/net/dnsfallback from tailscale.com/control/controlclient+ tailscale.com/net/flowtrack from tailscale.com/wgengine+ tailscale.com/net/ipset from tailscale.com/ipn/ipnlocal+ + tailscale.com/net/ktimeout from tailscale.com/net/sockopts tailscale.com/net/memnet from tailscale.com/tsnet tailscale.com/net/netaddr from tailscale.com/ipn+ tailscale.com/net/netcheck from tailscale.com/ipn/ipnlocal+ diff --git a/cmd/tailscaled/depaware-min.txt b/cmd/tailscaled/depaware-min.txt index 65d235fca..b9641ad06 100644 --- a/cmd/tailscaled/depaware-min.txt +++ b/cmd/tailscaled/depaware-min.txt @@ -92,6 +92,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de tailscale.com/net/dnsfallback from tailscale.com/cmd/tailscaled+ tailscale.com/net/flowtrack from tailscale.com/wgengine/filter tailscale.com/net/ipset from tailscale.com/ipn/ipnlocal+ + tailscale.com/net/ktimeout from tailscale.com/net/sockopts tailscale.com/net/netaddr from tailscale.com/ipn+ tailscale.com/net/netcheck from tailscale.com/wgengine/magicsock+ tailscale.com/net/neterror from tailscale.com/net/batching+ diff --git a/cmd/tailscaled/depaware-minbox.txt b/cmd/tailscaled/depaware-minbox.txt index 495291937..c56821361 100644 --- a/cmd/tailscaled/depaware-minbox.txt +++ b/cmd/tailscaled/depaware-minbox.txt @@ -109,6 +109,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de tailscale.com/net/dnsfallback from tailscale.com/cmd/tailscaled+ tailscale.com/net/flowtrack from tailscale.com/wgengine/filter tailscale.com/net/ipset from tailscale.com/ipn/ipnlocal+ + tailscale.com/net/ktimeout from tailscale.com/net/sockopts tailscale.com/net/netaddr from tailscale.com/ipn+ tailscale.com/net/netcheck from tailscale.com/cmd/tailscale/cli+ tailscale.com/net/neterror from tailscale.com/net/batching+ diff --git a/cmd/tailscaled/depaware.txt b/cmd/tailscaled/depaware.txt index f371b8753..e92a27e65 100644 --- a/cmd/tailscaled/depaware.txt +++ b/cmd/tailscaled/depaware.txt @@ -386,6 +386,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de tailscale.com/net/dnsfallback from tailscale.com/cmd/tailscaled+ tailscale.com/net/flowtrack from tailscale.com/wgengine+ tailscale.com/net/ipset from tailscale.com/ipn/ipnlocal+ + tailscale.com/net/ktimeout from tailscale.com/net/sockopts tailscale.com/net/netaddr from tailscale.com/ipn+ tailscale.com/net/netcheck from tailscale.com/wgengine/magicsock+ tailscale.com/net/neterror from tailscale.com/net/dns/resolver+ diff --git a/cmd/tsidp/depaware.txt b/cmd/tsidp/depaware.txt index 1f2ed7a46..731b4a735 100644 --- a/cmd/tsidp/depaware.txt +++ b/cmd/tsidp/depaware.txt @@ -192,6 +192,7 @@ tailscale.com/cmd/tsidp dependencies: (generated by github.com/tailscale/depawar tailscale.com/net/dnsfallback from tailscale.com/control/controlclient+ tailscale.com/net/flowtrack from tailscale.com/wgengine+ tailscale.com/net/ipset from tailscale.com/ipn/ipnlocal+ + tailscale.com/net/ktimeout from tailscale.com/net/sockopts tailscale.com/net/memnet from tailscale.com/tsnet tailscale.com/net/netaddr from tailscale.com/ipn+ tailscale.com/net/netcheck from tailscale.com/wgengine/magicsock+ diff --git a/net/ktimeout/checked.go b/net/ktimeout/checked.go new file mode 100644 index 000000000..3269c4c11 --- /dev/null +++ b/net/ktimeout/checked.go @@ -0,0 +1,25 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package ktimeout + +import ( + "fmt" + "math" + "time" +) + +// SetUserTimeoutChecked sets the TCP user timeout on fd, or returns an error +// wrapping errors.ErrUnsupported if this platform or socket does not support it. +// Unlike SetUserTimeout, it does not silently succeed on unsupported platforms. +// Success does not imply keepalive offload or any application-health guarantee. +// +// timeout must be a nonnegative whole number of milliseconds no greater than +// math.MaxInt32 milliseconds. Zero restores the kernel's default behavior. +// Invalid values are rejected before touching the socket. +func SetUserTimeoutChecked(fd uintptr, timeout time.Duration) error { + if timeout < 0 || timeout%time.Millisecond != 0 || timeout/time.Millisecond > math.MaxInt32 { + return fmt.Errorf("invalid TCP user timeout %v: want whole milliseconds in [0, %d]", timeout, math.MaxInt32) + } + return setUserTimeoutChecked(fd, timeout) +} diff --git a/net/ktimeout/checked_test.go b/net/ktimeout/checked_test.go new file mode 100644 index 000000000..ec6521a2b --- /dev/null +++ b/net/ktimeout/checked_test.go @@ -0,0 +1,45 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package ktimeout + +import ( + "errors" + "math" + "runtime" + "strings" + "testing" + "time" +) + +func TestSetUserTimeoutCheckedInvalid(t *testing.T) { + for _, timeout := range []time.Duration{ + -time.Millisecond, + time.Nanosecond, + time.Millisecond + time.Nanosecond, + (math.MaxInt32 + 1) * time.Millisecond, + time.Duration(math.MaxInt64), + } { + t.Run(timeout.String(), func(t *testing.T) { + // No valid fd is needed: validation must precede socket access. + err := SetUserTimeoutChecked(^uintptr(0), timeout) + if err == nil || !strings.HasPrefix(err.Error(), "invalid TCP user timeout ") { + t.Fatalf("invalid timeout error = %v; want validation error", err) + } + }) + } +} + +func TestSetUserTimeoutCheckedUnsupported(t *testing.T) { + if runtime.GOOS == "linux" || runtime.GOOS == "android" { + t.Skip("platform has a TCP_USER_TIMEOUT implementation") + } + for _, timeout := range []time.Duration{0, time.Second, math.MaxInt32 * time.Millisecond} { + if err := SetUserTimeoutChecked(^uintptr(0), timeout); !errors.Is(err, errors.ErrUnsupported) { + t.Errorf("checked timeout %v: error = %v; want unsupported", timeout, err) + } + if err := SetUserTimeout(^uintptr(0), timeout); err != nil { + t.Errorf("legacy timeout %v: error = %v; want no-op success", timeout, err) + } + } +} diff --git a/net/ktimeout/ktimeout_default.go b/net/ktimeout/ktimeout_default.go index 2304245b3..aace93f29 100644 --- a/net/ktimeout/ktimeout_default.go +++ b/net/ktimeout/ktimeout_default.go @@ -6,6 +6,7 @@ package ktimeout import ( + "errors" "time" ) @@ -13,3 +14,7 @@ import ( func SetUserTimeout(fd uintptr, timeout time.Duration) error { return nil } + +func setUserTimeoutChecked(fd uintptr, timeout time.Duration) error { + return errors.ErrUnsupported +} diff --git a/net/ktimeout/ktimeout_linux.go b/net/ktimeout/ktimeout_linux.go index 634c32119..fb7678ad7 100644 --- a/net/ktimeout/ktimeout_linux.go +++ b/net/ktimeout/ktimeout_linux.go @@ -4,6 +4,8 @@ package ktimeout import ( + "errors" + "fmt" "time" "golang.org/x/sys/unix" @@ -13,3 +15,11 @@ import ( func SetUserTimeout(fd uintptr, timeout time.Duration) error { return unix.SetsockoptInt(int(fd), unix.SOL_TCP, unix.TCP_USER_TIMEOUT, int(timeout/time.Millisecond)) } + +func setUserTimeoutChecked(fd uintptr, timeout time.Duration) error { + err := SetUserTimeout(fd, timeout) + if errors.Is(err, unix.ENOPROTOOPT) || errors.Is(err, unix.EOPNOTSUPP) { + return fmt.Errorf("%w: %w", errors.ErrUnsupported, err) + } + return err +} diff --git a/net/sockopts/tcp.go b/net/sockopts/tcp.go new file mode 100644 index 000000000..a56d32a38 --- /dev/null +++ b/net/sockopts/tcp.go @@ -0,0 +1,69 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package sockopts + +import ( + "net" + "time" + + "tailscale.com/net/ktimeout" +) + +// TCPConfig specifies transport settings for a TCP socket. The zero value +// leaves all settings unchanged. It does not select service-specific defaults. +// +// Apply these settings to the actual TCP connection before TLS/Noise wrapping, +// either after dialing or after accepting a connection. For a TCP-terminating +// proxy, they govern the connection to the proxy, not the end-to-end service. +type TCPConfig struct { + // KeepAlive, if non-nil, enables or disables TCP keepalive. When enabled, + // timing fields have the semantics of net.KeepAliveConfig. When disabled, + // timing fields are ignored. Success does not imply hardware offload. + KeepAlive *net.KeepAliveConfig + + // UserTimeout, if non-nil, sets the maximum age of outstanding data via + // ktimeout.SetUserTimeoutChecked. A pointer to zero restores the kernel's + // default behavior; nil leaves it unchanged. This is not an RTO setting. + UserTimeout *time.Duration +} + +// TCPConfigResult reports each requested setting independently. For a requested +// setting, nil means its application succeeded. Unrequested settings have nil +// results as well. KeepAlive retains the errors from net.TCPConn's setters; +// UserTimeout reports errors.ErrUnsupported for an unsupported platform or +// socket. Other errors, such as invalid values or a closed socket, are failures +// to apply the setting. +// +// There is no rollback: a setting may partially apply before returning an error. +// Callers must not infer that the requested policy is active when an error is +// returned, and decide whether to close the connection or use a fallback. +type TCPConfigResult struct { + KeepAlive error + UserTimeout error +} + +// Apply attempts all requested settings, even if one fails, and reports their +// results. It does not log, select fallbacks, or close c. The caller must apply +// configuration before handing the connection to other goroutines. +func (cfg TCPConfig) Apply(c *net.TCPConn) (result TCPConfigResult) { + if ka := cfg.KeepAlive; ka != nil { + if ka.Enable { + result.KeepAlive = c.SetKeepAliveConfig(*ka) + } else { + result.KeepAlive = c.SetKeepAlive(false) + } + } + if timeout := cfg.UserTimeout; timeout != nil { + rc, err := c.SyscallConn() + if err == nil { + err = rc.Control(func(fd uintptr) { + result.UserTimeout = ktimeout.SetUserTimeoutChecked(fd, *timeout) + }) + } + if err != nil { + result.UserTimeout = err + } + } + return result +} diff --git a/net/sockopts/tcp_linux_test.go b/net/sockopts/tcp_linux_test.go new file mode 100644 index 000000000..a33edeb39 --- /dev/null +++ b/net/sockopts/tcp_linux_test.go @@ -0,0 +1,111 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux + +package sockopts + +import ( + "net" + "testing" + "time" + + "golang.org/x/sys/unix" +) + +func TestTCPConfigApply(t *testing.T) { + ln, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}) + if err != nil { + t.Fatal(err) + } + defer ln.Close() + d := new(net.Dialer) + d.SetMultipathTCP(false) + outgoing, err := d.DialContext(t.Context(), "tcp4", ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer outgoing.Close() + incoming, err := ln.AcceptTCP() + if err != nil { + t.Fatal(err) + } + defer incoming.Close() + + for name, c := range map[string]*net.TCPConn{"dialed": outgoing.(*net.TCPConn), "accepted": incoming} { + t.Run(name, func(t *testing.T) { + rc, err := c.SyscallConn() + if err != nil { + t.Fatal(err) + } + get := func(level, opt int) int { + t.Helper() + var value int + var sockErr error + if err := rc.Control(func(fd uintptr) { + value, sockErr = unix.GetsockoptInt(int(fd), level, opt) + }); err != nil { + t.Fatal(err) + } + if sockErr != nil { + t.Fatal(sockErr) + } + return value + } + check := func(level, opt, want int) { + t.Helper() + if got := get(level, opt); got != want { + t.Errorf("socket option (%d, %d) = %d; want %d", level, opt, got, want) + } + } + timeout := 45 * time.Second + cfg := TCPConfig{ + KeepAlive: &net.KeepAliveConfig{ + Enable: true, Idle: 60 * time.Second, Interval: 10 * time.Second, Count: 3, + }, + UserTimeout: &timeout, + } + for _, config := range []TCPConfig{cfg, {}} { + result := config.Apply(c) + if result.KeepAlive != nil || result.UserTimeout != nil { + t.Fatalf("Apply: %+v", result) + } + check(unix.SOL_SOCKET, unix.SO_KEEPALIVE, 1) + check(unix.SOL_TCP, unix.TCP_KEEPIDLE, 60) + check(unix.SOL_TCP, unix.TCP_KEEPINTVL, 10) + check(unix.SOL_TCP, unix.TCP_KEEPCNT, 3) + check(unix.SOL_TCP, unix.TCP_USER_TIMEOUT, 45000) + } + + // A rejected user timeout must not prevent an independent + // keepalive change, or overwrite the previous timeout. + invalid := -time.Second + result := (TCPConfig{ + KeepAlive: &net.KeepAliveConfig{Enable: false}, UserTimeout: &invalid, + }).Apply(c) + if result.KeepAlive != nil || result.UserTimeout == nil { + t.Fatalf("invalid timeout: %+v", result) + } + check(unix.SOL_SOCKET, unix.SO_KEEPALIVE, 0) + check(unix.SOL_TCP, unix.TCP_USER_TIMEOUT, 45000) + + // A failed keepalive setting must not prevent the timeout from + // being applied. Linux rejects probe counts above 127. + timeout = 30 * time.Second + result = (TCPConfig{ + KeepAlive: &net.KeepAliveConfig{Enable: true, Count: 128}, UserTimeout: &timeout, + }).Apply(c) + if result.KeepAlive == nil || result.UserTimeout != nil { + t.Fatalf("invalid keepalive count: %+v", result) + } + check(unix.SOL_TCP, unix.TCP_USER_TIMEOUT, 30000) + + zero := time.Duration(0) + result = (TCPConfig{UserTimeout: &zero}).Apply(c) + if result.UserTimeout != nil { + t.Fatal(result.UserTimeout) + } + check(unix.SOL_TCP, unix.TCP_USER_TIMEOUT, 0) + }) + } +} diff --git a/net/sockopts/tcp_test.go b/net/sockopts/tcp_test.go new file mode 100644 index 000000000..63a4b25b8 --- /dev/null +++ b/net/sockopts/tcp_test.go @@ -0,0 +1,34 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package sockopts + +import ( + "net" + "testing" + "time" +) + +func TestTCPConfigNoop(t *testing.T) { + // A zero configuration must not even access the socket. + result := (TCPConfig{}).Apply(new(net.TCPConn)) + if result.KeepAlive != nil || result.UserTimeout != nil { + t.Fatalf("zero config: %+v", result) + } +} + +func TestTCPConfigErrors(t *testing.T) { + timeout := time.Second + for _, enable := range []bool{false, true} { + cfg := TCPConfig{ + KeepAlive: &net.KeepAliveConfig{Enable: enable}, + UserTimeout: &timeout, + } + // Both operations fail on an uninitialized connection. The second + // must still be attempted when the first fails. + result := cfg.Apply(new(net.TCPConn)) + if result.KeepAlive == nil || result.UserTimeout == nil { + t.Errorf("enable=%v: %+v; want both errors", enable, result) + } + } +} diff --git a/tsnet/depaware.txt b/tsnet/depaware.txt index 0dcb10650..41b529456 100644 --- a/tsnet/depaware.txt +++ b/tsnet/depaware.txt @@ -188,6 +188,7 @@ tailscale.com/tsnet dependencies: (generated by github.com/tailscale/depaware) tailscale.com/net/dnsfallback from tailscale.com/control/controlclient+ tailscale.com/net/flowtrack from tailscale.com/wgengine+ tailscale.com/net/ipset from tailscale.com/ipn/ipnlocal+ + tailscale.com/net/ktimeout from tailscale.com/net/sockopts tailscale.com/net/memnet from tailscale.com/tsnet tailscale.com/net/netaddr from tailscale.com/ipn+ tailscale.com/net/netcheck from tailscale.com/wgengine/magicsock+