util/pipetcp: 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).

util/pipetcp now provides Pipe, a function that can be used to
implement TCP proxying while correctly handling that footgun.

Updates #20880

Signed-off-by: Naman Sood <mail@nsood.in>
Co-authored-by: Brendan Creane <bcreane@tailscale.com>
This commit is contained in:
Naman SoodandBrendan Creane committed 2026-11-24 15:08:07 -05:00
1 parent 67e092fe7d
commit aa0d479294
12 files changed
+411 -154

No files matched your search

+1
View File
@@ -916,6 +916,7 @@ tailscale.com/cmd/k8s-operator dependencies: (generated by github.com/tailscale/
💣 tailscale.com/util/osdiag from tailscale.com/ipn/localapi
W 💣 tailscale.com/util/osdiag/internal/wsc from tailscale.com/util/osdiag
tailscale.com/util/osuser from tailscale.com/ipn/ipnlocal
tailscale.com/util/pipetcp from tailscale.com/net/socks5+
tailscale.com/util/race from tailscale.com/net/dns/resolver
tailscale.com/util/racebuild from tailscale.com/logpolicy
tailscale.com/util/rands from tailscale.com/ipn/ipnlocal+
+1
View File
@@ -502,6 +502,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de
W 💣 tailscale.com/util/osdiag/internal/wsc from tailscale.com/util/osdiag
tailscale.com/util/osshare from tailscale.com/cmd/tailscaled+
tailscale.com/util/osuser from tailscale.com/ipn/ipnlocal+
tailscale.com/util/pipetcp from tailscale.com/net/socks5+
tailscale.com/util/progresstracking from tailscale.com/feature/taildrop+
tailscale.com/util/race from tailscale.com/net/dns/resolver
tailscale.com/util/racebuild from tailscale.com/logpolicy
+1
View File
@@ -300,6 +300,7 @@ tailscale.com/cmd/tsidp dependencies: (generated by github.com/tailscale/depawar
💣 tailscale.com/util/osdiag from tailscale.com/ipn/localapi
W 💣 tailscale.com/util/osdiag/internal/wsc from tailscale.com/util/osdiag
tailscale.com/util/osuser from tailscale.com/ipn/ipnlocal
tailscale.com/util/pipetcp from tailscale.com/net/socks5+
tailscale.com/util/race from tailscale.com/net/dns/resolver
tailscale.com/util/racebuild from tailscale.com/logpolicy
tailscale.com/util/rands from tailscale.com/cmd/tsidp+
+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
+4 -18
View File
@@ -129,15 +129,11 @@ func (ln *listener) Addr() net.Addr {
type connWithOneByte struct {
net.Conn
b byte
bRead bool
readClosed bool
b byte
bRead bool
}
func (c *connWithOneByte) Read(bs []byte) (int, error) {
if c.readClosed {
return 0, net.ErrClosed
}
if c.bRead {
return c.Conn.Read(bs)
}
@@ -149,20 +145,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
+9 -81
View File
@@ -28,7 +28,7 @@ import (
"tailscale.com/syncs"
"tailscale.com/types/logger"
"tailscale.com/types/nettype"
"tailscale.com/util/pipetcp"
)
// Authentication METHODs described in RFC 1928, section 3.
@@ -261,86 +261,14 @@ 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") }()
err = <-errc
if err == nil {
return <-errc
}
// One direction failed, which means one of the two sockets is dead.
//
// If it failed writing to (or half-closing) its destination, the other
// direction is reading from that dead socket. Its reads return whatever
// arrived before the failure and then an error, so leave it alone to
// deliver that data rather than truncating it.
//
// If it failed reading from its source, the other direction is writing
// into that dead socket and may be blocked reading from the live peer,
// which has no reason to send anything. Close both connections to
// 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 {
srv.Close()
c.clientConn.Close()
}
<-errc
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
// [pipetcp.Pipe] 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.
return pipetcp.Pipe(srv, c.clientConn)
}
func (c *Conn) handleUDP() error {
+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
+1
View File
@@ -295,6 +295,7 @@ tailscale.com/tsnet dependencies: (generated by github.com/tailscale/depaware)
💣 tailscale.com/util/osdiag from tailscale.com/ipn/localapi
W 💣 tailscale.com/util/osdiag/internal/wsc from tailscale.com/util/osdiag
tailscale.com/util/osuser from tailscale.com/ipn/ipnlocal
tailscale.com/util/pipetcp from tailscale.com/net/socks5+
tailscale.com/util/race from tailscale.com/net/dns/resolver
tailscale.com/util/racebuild from tailscale.com/logpolicy
tailscale.com/util/rands from tailscale.com/ipn/ipnlocal+
+7 -5
View File
@@ -64,13 +64,15 @@ 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.
// TCPWriteCloser 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
}
+125
View File
@@ -0,0 +1,125 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
// Package pipetcp provides functionality to proxy connections between two TCP
// connections.
package pipetcp
import (
"errors"
"fmt"
"io"
"net"
"tailscale.com/types/nettype"
)
// 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.
//
// direction is a string used in the error text, used to denote the direction
// of a [pump]. This is because in a forwarding scenario, two [pump]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.
func pump(dst, src net.Conn, direction string) error {
if _, err := io.Copy(dstWriter{dst}, src); err != nil {
return fmt.Errorf("%s: %w", direction, err)
}
// If the Copy finished without error, inform the other side that no more
// data will be sent.
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
}
// Pipe bidirectionally connects `left` and `right`, two TCP streams (not
// necessarily [*net.TCPConn], but something that represents a TCP connection
// and is `CloseWrite()`-able), and closes the two connections when finished.
// It gracefully handles half-closed TCP connections on either side.
//
// When you call Pipe, you must ensure that both the Conns can be half-closed
// (ie. implement CloseWrite()). Otherwise, `Pipe` may block forever, or at
// least until both sides tear down their connections on their own.
func Pipe(left, right net.Conn) error {
defer left.Close()
defer right.Close()
errc := make(chan error, 2)
retErrs := make([]error, 2)
go func() { errc <- pump(left, right, "right to left") }()
go func() { errc <- pump(right, left, "left to right") }()
closed := false
for i := range 2 {
err := <-errc
// We ignore `net.ErrClosed` after we close the sockets, because we
// know we did that.
if !closed || !errors.Is(err, net.ErrClosed) {
retErrs[i] = err
}
// One direction failed, which means one of the two sockets is dead.
//
// If it failed writing to (or half-closing) its destination, the other
// direction is reading from that dead socket. Its reads return whatever
// arrived before the failure and then an error, so leave it alone to
// deliver that data rather than truncating it.
//
// If it failed reading from its source, the other direction is writing
// into that dead socket and may be blocked reading from the live peer,
// which has no reason to send anything. Close both connections to
// 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 err != nil && !isDstError(err) {
left.Close()
right.Close()
closed = true
}
}
return errors.Join(retErrs...)
}
// dstError wraps an error from [pump]'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 [pump],
// rather than one from reading from its source.
func isDstError(err error) bool {
_, ok := errors.AsType[dstError](err)
return ok
}
// dstWriter wraps [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 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
}
+250
View File
@@ -0,0 +1,250 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package pipetcp
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.Conn
halfClosed bool
}
func (c *halfCloseCheckingTCPConn) CloseWrite() error {
c.halfClosed = true
return c.Conn.(nettype.TCPWriteCloser).CloseWrite()
}
// brokenReadConn is a Conn that returns an error on Read.
type brokenReadConn struct {
net.Conn
}
func (c *brokenReadConn) Read(_ []byte) (int, error) {
return 0, io.ErrClosedPipe
}
func (c *brokenReadConn) WriteTo(_ io.Writer) (int64, error) {
return 0, io.ErrClosedPipe
}
// brokenWriteConn is a Conn that returns an error on Write.
type brokenWriteConn struct {
net.Conn
}
func (c *brokenWriteConn) Write(_ []byte) (int, error) {
// CloseWrite so that the backing connection knows we won't write anything.
c.CloseWrite()
return 0, io.ErrClosedPipe
}
func (c *brokenWriteConn) ReadFrom(_ io.Reader) (int64, error) {
// CloseWrite so that the backing connection knows we won't write anything.
c.CloseWrite()
return 0, io.ErrClosedPipe
}
func (c *brokenWriteConn) CloseWrite() error {
return c.Conn.(nettype.TCPWriteCloser).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)
// connModifier wraps a [*net.TCPConn] in modifiers to mock functionality.
type connModifier func(*net.TCPConn) net.Conn
func goodClient(client net.Conn, errc chan<- error, request, response []byte) {
defer func() { 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
}
errc <- nil
}
func goodBackend(backend net.Conn, errc chan<- error, request, response []byte) {
defer func() { 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
}
errc <- nil
}
func TestPipe(t *testing.T) {
tests := []struct {
name string
client peerSimulator
backend peerSimulator
toClientModifier connModifier
toBackendModifier connModifier
wantPipeError bool
wantHalfClosed bool
wantClientError bool
wantBackendError bool
}{
{
name: "success",
client: goodClient,
backend: goodBackend,
wantPipeError: false,
wantClientError: false,
wantBackendError: false,
wantHalfClosed: true,
},
{
name: "error-writing-to-backend",
client: goodClient,
backend: goodBackend,
toBackendModifier: func(c *net.TCPConn) net.Conn {
return &brokenWriteConn{c}
},
wantPipeError: true,
wantClientError: true,
wantBackendError: true,
wantHalfClosed: false,
},
{
name: "error-reading-from-client",
client: func(conn net.Conn, errc chan<- error, request, response []byte) {
// We will never successfully read from this client, so might
// as well close it immediately.
errc <- conn.Close()
},
backend: goodBackend,
toClientModifier: func(c *net.TCPConn) net.Conn {
return &brokenReadConn{c}
},
wantPipeError: true,
wantClientError: false, // the client we wrote above never has a chance to error
wantBackendError: true,
wantHalfClosed: false,
},
}
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()
}
}
// Create a "backend" server to forward connections to.
backend, toBackend, cleanupBackend := makePeer()
defer cleanupBackend()
if tt.toBackendModifier != nil {
toBackend = tt.toBackendModifier(toBackend.(*net.TCPConn))
}
toBackend = &halfCloseCheckingTCPConn{toBackend, 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)
errOnBackend := make(chan error, 1)
go tt.backend(backend, errOnBackend, request, response)
// Create a "client" to receive a connection from.
client, toClient, cleanupClient := makePeer()
defer cleanupClient()
if tt.toClientModifier != nil {
toClient = tt.toClientModifier(toClient.(*net.TCPConn))
}
errOnClient := make(chan error, 1)
go tt.client(client, errOnClient, request, response)
err := Pipe(toBackend, toClient)
gotError := err != nil
if gotError {
t.Logf("PipeTCP: %v", err)
}
if gotError != tt.wantPipeError {
t.Errorf("PipeTCP: wanted error=%v, got=%v", tt.wantPipeError, gotError)
}
for range 2 {
select {
case err := <-errOnClient:
gotError := err != nil
if gotError {
t.Logf("client: %v", err)
}
if gotError != tt.wantClientError {
t.Errorf("client: wanted error=%v, got %v", tt.wantClientError, gotError)
}
case err := <-errOnBackend:
gotError := err != nil
if gotError {
t.Logf("backend: %v", err)
}
if gotError != tt.wantBackendError {
t.Errorf("client: wanted error=%v, got %v", tt.wantBackendError, gotError)
}
case <-time.After(5 * time.Second):
t.Errorf("timed out waiting for peers to finish")
}
}
if hc, ok := toBackend.(*halfCloseCheckingTCPConn); ok {
if hc.halfClosed != tt.wantHalfClosed {
t.Errorf("conn to backend: want halfClosed %v, got %v", tt.wantHalfClosed, hc.halfClosed)
}
}
})
}
}
+8 -38
View File
@@ -10,7 +10,6 @@ import (
"errors"
"expvar"
"fmt"
"io"
"math"
"net"
"net/netip"
@@ -54,6 +53,7 @@ import (
"tailscale.com/types/nettype"
"tailscale.com/types/views"
"tailscale.com/util/clientmetric"
"tailscale.com/util/pipetcp"
"tailscale.com/util/set"
"tailscale.com/util/usermetric"
"tailscale.com/version"
@@ -1891,46 +1891,16 @@ func (ns *Impl) forwardTCP(getClient func(...tcpip.SettableSocketOption) *gonet.
}
defer client.Close()
// [pipetcp.Pipe] 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 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
// flowing. Neither direction shuts down its source's read side: that
// 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.
go func() {
_, err := io.Copy(backend, client)
if err != nil {
err = fmt.Errorf("client -> backend: %w", err)
}
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)
}
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 {
err = <-connClosed
if err != nil {
ns.logf("proxy connection closed with error: %v", err)
}
// errored out by now), so if we get here, backend should support
// half-closing.
// client is a [*gonet.TCPConn], which supports half-closing.
err = pipetcp.Pipe(backend, client)
if err != nil {
ns.logf("proxy connection closed with error: %v", err)
}
ns.logf("[v2] netstack: forwarder connection to %s closed", dialAddrStr)
return