net/netutil: add reusable TCP proxying functionality

We keep running into problems with improperly handling proxying TCP
connections when one side half-closes their write end
(see #20880, #20883, #21522, tailscale/corp#29837, etc).

net/netutil now provides PumpTCP, a function that can be used to
implement TCP proxying while correctly handling that footgun.

Updates #20880.

Signed-off-by: Naman Sood <[email protected]>
Co-authored-by: Brendan Creane <[email protected]>
This commit is contained in:
Naman SoodandBrendan Creane committed 2026-11-23 14:35:10 -05:00
1 parent b837008974
commit 56303bee5c
9 files changed
+323 -109

No files matched your search

+1
View File
@@ -143,6 +143,7 @@ tailscale.com/cmd/derper dependencies: (generated by github.com/tailscale/depawa
tailscale.com/types/lazy from tailscale.com/version+
tailscale.com/types/logger from tailscale.com/cmd/derper+
tailscale.com/types/netmap from tailscale.com/net/routecheck
tailscale.com/types/nettype from tailscale.com/net/netutil
tailscale.com/types/opt from tailscale.com/envknob+
tailscale.com/types/persist from tailscale.com/ipn+
tailscale.com/types/preftype from tailscale.com/ipn
+2 -1
View File
@@ -45,6 +45,7 @@ import (
"tailscale.com/tailcfg/peercap"
"tailscale.com/types/lazy"
"tailscale.com/types/logger"
"tailscale.com/types/nettype"
"tailscale.com/types/views"
"tailscale.com/util/backoff"
"tailscale.com/util/clientmetric"
@@ -586,7 +587,7 @@ func (c *serviceMeteredConn) Write(p []byte) (int, error) {
// and drain gracefully when a connection won't be reused, avoiding a truncating
// RST on the final response.
func (c *serviceMeteredConn) CloseWrite() error {
if cw, ok := c.Conn.(interface{ CloseWrite() error }); ok {
if cw, ok := c.Conn.(nettype.TCPWriteCloser); ok {
return cw.CloseWrite()
}
return nil
+85
View File
@@ -0,0 +1,85 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package netutil
import (
"errors"
"fmt"
"io"
"net"
"tailscale.com/types/nettype"
)
// PumpTCP copies from src to dst until src returns EOF or either side fails.
//
// On EOF or read error, it half-closes dst, if dst supports it, so dst's peer
// sees EOF while the other direction of the proxied connection keeps flowing
// (or in an error case, so that the dst's peer knows that src is dead and
// doesn't block on further reads).
// It does not half-close src's read side: that has no effect on the wire,
// and after src has returned EOF, both macOS and Linux may reject the shutdown
// with ENOTCONN.
//
// direction is a string used in the error text, used to denote the direction
// of a [PumpTCP]. This is because in a forwarding scenario, two [PumpTCP]s are
// started, to copy data from each direction to the other.
//
// Errors from writing to or half-closing dst are returned wrapped in a
// [dstError]. Errors from reading src are not.
//
// When you call PumpTCP, you must ensure that the destination Conn can be
// half-closed (ie. implements CloseWrite()).
func PumpTCP(dst, src net.Conn, direction string) error {
var err error
if _, err = io.Copy(dstWriter{dst}, src); err != nil {
err = fmt.Errorf("%s: %w", direction, err)
}
// If writing to the destination failed, the destination socket is already
// dead so we can return without trying to half-close the socket.
if IsDstError(err) {
return err
}
// Otherwise, try to half-close the dst socket to let it know to stop
// expecting more data after anything already buffered runs out.
if hc, ok := dst.(nettype.TCPWriteCloser); ok {
if err := hc.CloseWrite(); err != nil {
return fmt.Errorf("%s: close write: %w", direction, dstError{err})
}
}
return nil
}
// dstError wraps an error from [PumpTCP]'s destination, as opposed to one
// from reading its source.
type dstError struct{ error }
func (e dstError) Unwrap() error { return e.error }
// IsDstError reports whether an error is from the destination of a [PumpTCP],
// rather than one from reading from its source.
func IsDstError(err error) bool {
_, ok := errors.AsType[dstError](err)
return ok
}
// dstWriter wraps [PumpTCP]'s destination so that its write errors are
// reported as a [dstError].
//
// Wrapping the destination hides its ReadFrom method from [io.Copy] and hides
// its type from the source's WriteTo, so when both ends are bare TCP
// connections the kernel splice fast path is not used. That costs about a
// third of the relay throughput on Linux loopback, but knowing which side
// failed is what lets us avoid truncating a reply after the backend
// resets, and in the common userspace-networking and proxymux configurations
// the connections are wrapped types with no fast path anyway.
type dstWriter struct{ io.Writer }
func (w dstWriter) Write(p []byte) (int, error) {
n, err := w.Writer.Write(p)
if err != nil {
err = dstError{err}
}
return n, err
}
+201
View File
@@ -0,0 +1,201 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package netutil
import (
"bytes"
"fmt"
"io"
"net"
"testing"
"time"
"tailscale.com/types/nettype"
"tailscale.com/util/must"
)
// halfCloseCheckingTCPConn is a TCPConn that keeps track of if its write end
// was closed.
type halfCloseCheckingTCPConn struct {
*net.TCPConn
halfClosed bool
}
func (c *halfCloseCheckingTCPConn) CloseWrite() error {
c.halfClosed = true
return c.TCPConn.CloseWrite()
}
// peerSimulator is a function that runs in its own goroutine to pretend to be
// a computer on the other side of a connection. It sends exactly one value over
// errc (either an error if one occurred, or nil otherwise), and plays its part
// in a conversation between a client that sends `request`, and closes its
// write end, and a backend that responds with `response`.
type peerSimulator func(conn net.Conn, errc chan<- error, request, response []byte)
func goodClient(client net.Conn, errc chan<- error, request, response []byte) {
defer func() { errc <- client.Close() }()
if _, err := client.Write(request); err != nil {
errc <- fmt.Errorf("client write: %v", err)
return
}
if err := client.(nettype.TCPWriteCloser).CloseWrite(); err != nil {
errc <- fmt.Errorf("client closewrite: %v", err)
return
}
got, err := io.ReadAll(client)
if err != nil {
errc <- fmt.Errorf("client read: %v", err)
return
}
if !bytes.Equal(got, response) {
errc <- fmt.Errorf("client read: expected response length %v, got %v", len(response), len(got))
return
}
}
func goodBackend(backend net.Conn, errc chan<- error, request, response []byte) {
defer func() { errc <- backend.Close() }()
got, err := io.ReadAll(backend)
if err != nil {
errc <- fmt.Errorf("backend read: %v", err)
return
}
if !bytes.Equal(got, request) {
errc <- fmt.Errorf("backend read: expected request length %v, got %v", len(request), len(got))
return
}
if _, err = backend.Write(response); err != nil {
errc <- fmt.Errorf("backend write: %v", err)
return
}
}
func TestPumpTCP(t *testing.T) {
tests := []struct {
name string
client peerSimulator
backend peerSimulator
connToBackendShouldHalfClose bool
wantError bool
}{
{
name: "success",
client: goodClient,
backend: goodBackend,
},
{
name: "error-writing-to-backend",
client: goodClient,
backend: func(conn net.Conn, errc chan<- error, request, response []byte) {
// Close the connection without finishing the transaction to
// induce a dstError in PumpTCP writing the rest of the
// response to us.
defer func() { errc <- conn.Close() }()
// But first, partially read from the connection to ensure that
// the connection doesn't die before the client has a chance
// to write anything at all.
var buf [10]byte
if _, err := conn.Read(buf[:]); err != nil {
errc <- fmt.Errorf("backend read: %v", err)
}
},
wantError: true,
},
{
name: "error-reading-from-client",
client: func(conn net.Conn, errc chan<- error, request, response []byte) {
// Close with SO_LINGER zero so the kernel sends a RST rather
// than a FIN, and reading from the client gives a non-EOF
// error to PumpTCP.
conn.(*net.TCPConn).SetLinger(0)
errc <- conn.Close()
},
backend: goodBackend,
wantError: true,
connToBackendShouldHalfClose: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// makePeer makes a "peer", ie. an approximation of a computer that we are
// talking to over a TCP connection.
// peer is the end that we use to pretend to be the other computer.
// proxy is the end that we use to talk to the other computer.
makePeer := func() (peer, proxy net.Conn, cleanup func()) {
t.Helper()
ln := must.Get(net.Listen("tcp", "127.0.0.1:0"))
peerCh := make(chan net.Conn, 1)
go func() {
peerCh <- must.Get(ln.Accept())
}()
proxy = must.Get(net.Dial("tcp", ln.Addr().String()))
peer = <-peerCh
return peer, proxy, func() {
ln.Close()
peer.Close()
proxy.Close()
}
}
// Two errors come in from the peer puppeting goroutines, and two come in
// from the calls to PumpTCP in their own goroutines.
errc := make(chan error, 4)
// Create a "backend" server to forward connections to.
backend, toBackend, cleanupBackend := makePeer()
defer cleanupBackend()
if tt.connToBackendShouldHalfClose {
toBackendTCPConn := toBackend.(*net.TCPConn)
// Fail instantly with a non-EOF error trying to read from the
// client to exercise half-closing code path.
toBackendTCPConn.SetReadDeadline(time.Now())
toBackend = &halfCloseCheckingTCPConn{toBackendTCPConn, false}
}
// Requests and responses are sufficiently long to notice an
// incomplete read.
request := bytes.Repeat([]byte("q"), 1<<20)
response := bytes.Repeat([]byte("r"), 1<<20)
go tt.backend(backend, errc, request, response)
// Create a "client" to receive a connection from.
client, toClient, cleanupClient := makePeer()
defer cleanupClient()
go tt.client(client, errc, request, response)
// Test the actual pumping functionality, by connecting
// the two proxies together.
go func() { errc <- PumpTCP(toBackend, toClient, "backend <- client") }()
go func() { errc <- PumpTCP(toClient, toBackend, "client <- backend") }()
// It might be okay for us to be getting errors in cases where we
// induce one. For example, in the case that tests half-closing,
// the backend will send us errors.
gotError := false
for range 4 {
err := <-errc
if err != nil {
t.Logf("got error: %v", err)
gotError = true
}
}
if gotError != tt.wantError {
t.Errorf("wanted gotError = %v, got %v", tt.wantError, gotError)
}
if tt.connToBackendShouldHalfClose {
// This conversion should always succeed because we wrap
// `toBackend` in this struct when `tt.backendShouldHalfClose`.
if !toBackend.(*halfCloseCheckingTCPConn).halfClosed {
t.Errorf("wanted connection to be half-closed, but it wasn't")
}
}
})
}
}
+2 -12
View File
@@ -149,20 +149,10 @@ func (c *connWithOneByte) Read(bs []byte) (int, error) {
return 1, nil
}
// CloseRead implements [nettype.HalfCloser], allowing the underlying Conn
// to be half-closed if possible. Otherwise, this is a no-op.
func (c *connWithOneByte) CloseRead() error {
if hc, ok := c.Conn.(nettype.HalfCloser); ok {
c.readClosed = true
return hc.CloseRead()
}
return nil
}
// CloseWrite implements [nettype.HalfCloser], allowing the underlying Conn
// CloseWrite implements [nettype.TCPWriteCloser], allowing the underlying Conn
// to be half-closed if possible. Otherwise, this is a no-op.
func (c *connWithOneByte) CloseWrite() error {
if hc, ok := c.Conn.(nettype.HalfCloser); ok {
if hc, ok := c.Conn.(nettype.TCPWriteCloser); ok {
return hc.CloseWrite()
}
return nil
+11 -58
View File
@@ -26,9 +26,9 @@ import (
"strconv"
"time"
"tailscale.com/net/netutil"
"tailscale.com/syncs"
"tailscale.com/types/logger"
"tailscale.com/types/nettype"
)
// Authentication METHODs described in RFC 1928, section 3.
@@ -262,8 +262,15 @@ func (c *Conn) handleTCP() error {
c.clientConn.Write(buf)
errc := make(chan error, 2)
go func() { errc <- pump(c.clientConn, srv, "from backend to client") }()
go func() { errc <- pump(srv, c.clientConn, "from client to backend") }()
// [netutil.PumpTCP] requires that the destination in both of these calls
// supports closing the write half of its connection. As of 2026-09-16,
// both ends of a proxied connection support half-closing:
// [Server.dial] returns a [*net.TCPConn], possibly wrapped by a
// tsdial.sysConn, and the client connection comes from a TCP listener,
// possibly wrapped by proxymux.SplitSOCKSAndHTTP. Both wrappers pass
// half-closes through to the underlying connection.
go func() { errc <- netutil.PumpTCP(c.clientConn, srv, "from backend to client") }()
go func() { errc <- netutil.PumpTCP(srv, c.clientConn, "from client to backend") }()
err = <-errc
if err == nil {
return <-errc
@@ -281,7 +288,7 @@ func (c *Conn) handleTCP() error {
// unblock it. Nothing deliverable is lost: the dead socket has already
// returned everything it received, and anything from the live peer
// could not be delivered to it anyway.
if _, isDstErr := errors.AsType[dstError](err); !isDstErr {
if !netutil.IsDstError(err) {
srv.Close()
c.clientConn.Close()
}
@@ -289,60 +296,6 @@ func (c *Conn) handleTCP() error {
return err
}
// pump copies from src to dst until src returns EOF or either side fails.
//
// On EOF it half-closes dst, if dst supports it, so dst's peer sees EOF while
// the other direction of the proxied connection keeps flowing. It does not
// half-close src's read side: that has no effect on the wire, and after src
// has returned EOF, both macOS and Linux may reject the shutdown with
// ENOTCONN.
//
// Errors from writing to or half-closing dst are returned wrapped in a
// [dstError]. Errors from reading src are not.
//
// As of 2026-09-16, both ends of a proxied connection support half-closing:
// [Server.dial] returns a [*net.TCPConn], possibly wrapped by a
// tsdial.sysConn, and the client connection comes from a TCP listener,
// possibly wrapped by proxymux.SplitSOCKSAndHTTP. Both wrappers pass
// half-closes through to the underlying connection.
func pump(dst, src net.Conn, dir string) error {
if _, err := io.Copy(dstWriter{dst}, src); err != nil {
return fmt.Errorf("%s: %w", dir, err)
}
if hc, ok := dst.(nettype.HalfCloser); ok {
if err := hc.CloseWrite(); err != nil {
return fmt.Errorf("%s: close write: %w", dir, dstError{err})
}
}
return nil
}
// dstError wraps an error from a [pump]'s destination, as opposed to one
// from reading its source.
type dstError struct{ error }
func (e dstError) Unwrap() error { return e.error }
// dstWriter wraps a [pump]'s destination so that its write errors are
// reported as a [dstError].
//
// Wrapping the destination hides its ReadFrom method from [io.Copy] and hides
// its type from the source's WriteTo, so when both ends are bare TCP
// connections the kernel splice fast path is not used. That costs about a
// third of the relay throughput on Linux loopback, but knowing which side
// failed is what lets handleTCP avoid truncating a reply after the backend
// resets, and in the common userspace-networking and proxymux configurations
// the connections are wrapped types with no fast path anyway.
type dstWriter struct{ io.Writer }
func (w dstWriter) Write(p []byte) (int, error) {
n, err := w.Writer.Write(p)
if err != nil {
err = dstError{err}
}
return n, err
}
func (c *Conn) handleUDP() error {
// The DST.ADDR and DST.PORT fields contain the address and port that
// the client expects to use to send UDP datagrams on for the
+2 -11
View File
@@ -130,19 +130,10 @@ func (c sysConn) Close() error {
return nil
}
// CloseRead implements [nettype.HalfCloser], allowing the underlying Conn
// to be half-closed if possible. Otherwise, this is a no-op.
func (c sysConn) CloseRead() error {
if hc, ok := c.Conn.(nettype.HalfCloser); ok {
return hc.CloseRead()
}
return nil
}
// CloseWrite implements [nettype.HalfCloser], allowing the underlying Conn
// CloseWrite implements [nettype.TCPWriteCloser], allowing the underlying Conn
// to be half-closed if possible. Otherwise, this is a no-op.
func (c sysConn) CloseWrite() error {
if hc, ok := c.Conn.(nettype.HalfCloser); ok {
if hc, ok := c.Conn.(nettype.TCPWriteCloser); ok {
return hc.CloseWrite()
}
return nil
+8 -5
View File
@@ -64,13 +64,16 @@ type ConnPacketConn interface {
net.PacketConn
}
// HalfCloser is an interface to abstract around various Conn types that
// allow closing of the read and write streams independently of each other.
// WriteCloser is an interface to abstract around various TCP conn types that
// allow closing of the write stream independently of the overall connection.
// It is normally used as a typecast for a `net.Conn` to get access to these
// functions. If you use it for this purpose, you should either be absolutely
// certain that the `net.Conn` you have represents a half-closable connection
// (eg. TCP or unix socket), or check for and handle a failure to cast.
type HalfCloser interface {
CloseRead() error
// (eg. TCP), or check for and handle a failure to cast.
// This interface intentionally does not implement CloseRead(), since that is
// usually a no-op, and CloseRead()ing a dead connection may cause errors.
// See #21522 for context.
type TCPWriteCloser interface {
CloseWrite() error
}
+11 -22
View File
@@ -10,7 +10,6 @@ import (
"errors"
"expvar"
"fmt"
"io"
"math"
"net"
"net/netip"
@@ -40,6 +39,7 @@ import (
"tailscale.com/net/dns"
"tailscale.com/net/ipset"
"tailscale.com/net/netaddr"
"tailscale.com/net/netutil"
"tailscale.com/net/netx"
"tailscale.com/net/packet"
"tailscale.com/net/tsaddr"
@@ -1891,11 +1891,6 @@ func (ns *Impl) forwardTCP(getClient func(...tcpip.SettableSocketOption) *gonet.
}
defer client.Close()
// As of 2025-07-03, backend is always either a net.TCPConn
// from stdDialer.DialContext (which has the requisite functions),
// or nil from hangDialer in tests (in which case we would have
// errored out by now), so this conversion should always succeed.
backendHalfCloser, backendIsHalfCloser := backend.(nettype.HalfCloser)
connClosed := make(chan error, 2)
// Each direction half-closes its destination once the source is done,
// so the destination's peer sees EOF while the other direction keeps
@@ -1903,27 +1898,21 @@ func (ns *Impl) forwardTCP(getClient func(...tcpip.SettableSocketOption) *gonet.
// has no effect on the wire, and once the source has returned EOF,
// macOS (and Linux, if the socket is fully closed by then) rejects the
// shutdown with ENOTCONN, which used to be logged for every connection.
//
// [netutil.PumpTCP] requires its destination to support TCP half-closing.
// As of 2025-07-03, backend is always either a net.TCPConn
// from stdDialer.DialContext (which has the requisite functions),
// or nil from hangDialer in tests (in which case we would have
// errored out by now), so if we get here, backend should support
// half-closing.
// client is a [*gonet.TCPConn], which supports half-closing.
go func() {
_, err := io.Copy(backend, client)
if err != nil {
err = fmt.Errorf("client -> backend: %w", err)
}
err := netutil.PumpTCP(backend, client, "client -> backend")
connClosed <- err
if backendIsHalfCloser {
if err := backendHalfCloser.CloseWrite(); err != nil {
ns.logf("client -> backend close connection: %v", err)
}
}
}()
go func() {
_, err := io.Copy(client, backend)
if err != nil {
err = fmt.Errorf("backend -> client: %w", err)
}
err := netutil.PumpTCP(client, backend, "backend -> client")
connClosed <- err
if err := client.CloseWrite(); err != nil {
ns.logf("backend -> client close connection: %v", err)
}
}()
// Wait for both ends of the connection to close.
for range 2 {