Skip to content
Open
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
3 changes: 3 additions & 0 deletions cmd/tailcat/forward.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"strings"
"sync"
"syscall"
"time"

"github.com/peterbourgon/ff/v4"
"github.com/tailscale/tailcat"
Expand Down Expand Up @@ -77,6 +78,8 @@ func runForward(ctx context.Context, logf logger.Logf, bind string, args []strin
}

cl := newClient(logf, tailcatAddrArg(args[0]), clientKey())
// Re-register after server restarts even when forward is idle.
cl.ReannounceInterval = 30 * time.Second
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer stop()

Expand Down
3 changes: 3 additions & 0 deletions cmd/tailcat/tailcat.go
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,9 @@ func clientKey() key.NodePrivate {

// newClient returns a [tailcat.Client] configured with the global
// --derpmap-url flag and the disk DERP map cache.
//
// Opt in to re-announcing at the call site. SOCKS clients share a node
// key, so an idle client's meow could steal DERP replies from an active one.
func newClient(logf logger.Logf, addr tailcat.Addr, priv key.NodePrivate) *tailcat.Client {
return &tailcat.Client{
Server: addr,
Expand Down
176 changes: 157 additions & 19 deletions tailcat.go
Original file line number Diff line number Diff line change
Expand Up @@ -1830,10 +1830,15 @@ func (lb *locoBackend) Start() error {
// server then stops trusting the old process's direct path (see
// resetClientPathLocked).
func (b *locoBackend) onMeow(src key.NodePublic, discoPub key.DiscoPublic, inst meowInstanceID) bool {
b.logf("got meow from %v", src.String())
b.mu.Lock()
defer b.mu.Unlock()
if _, ok := b.clients[src]; ok {
_, known := b.clients[src]
defer func() {
b.mu.Unlock()
if !known {
b.logf("got meow from %v", src.String())
}
}()
if known {
if b.clientInstance[src] != inst {
b.logf("client %v restarted; resetting its path", src.ShortString())
b.clientInstance[src] = inst
Expand Down Expand Up @@ -2115,9 +2120,19 @@ type Client struct {
// before the client's first use.
DERPMapCache DERPMapCache

lb *locoBackend
ci ConnInfo // of server
meowWait chan struct{} // closed on first meowed message from server
// ReannounceInterval controls background registration with the server.
// A non-positive value disables it. Failures retry with backoff.
// Set this before first use.
ReannounceInterval time.Duration

lb *locoBackend
ci ConnInfo // of server
meowMu sync.Mutex
meowed chan struct{} // closed, then replaced, on each meowed ack from the server

reannounceStop func() // stops the re-announce loop, if one is running (guarded by startMu)
dialTimeout time.Duration // per-attempt dial bound; zero means defaultDialAttemptTimeout (tests shrink it)
closed atomic.Bool

serverAddr netip.Addr

Expand Down Expand Up @@ -2190,19 +2205,28 @@ func (c *Client) initLocked() error {
var store ipn.StateStore = new(mem.Store)
sys.Set(store)

meowWait := make(chan struct{})
onMeowed := sync.OnceFunc(func() {
close(meowWait)
// The server just learned who we are; tell it our UDP
// endpoints so both sides can attempt a direct path.
lb.advertiseEndpoints()
})
c.meowed = make(chan struct{})
lb.onDERPRecv = func(regionID tailcfg.DERPRegionID, src key.NodePublic, pkt []byte) bool {
if !IsMeowPacket(pkt) {
return false
}
if src != ci.ServerPublic.NodePublic {
return true
}
if IsMeowedPacket(pkt) {
go onMeowed()
// A restarted server may have lost the WireGuard session.
// Schedule a handshake before waking callers that can send.
lb.sys.Engine.Get().MarkDevicePeerForHandshake(ci.ServerPublic.NodePublic)
c.meowMu.Lock()
select {
case <-c.meowed:
default:
close(c.meowed)
}
c.meowed = make(chan struct{})
c.meowMu.Unlock()
// Re-advertise endpoints without blocking DERP receive on lb.mu.
go lb.advertiseEndpoints()
return true
}
return true // client ignores MeowPing
Expand Down Expand Up @@ -2252,7 +2276,6 @@ func (c *Client) initLocked() error {
c.ci = ci
c.lb = lb
c.serverAddr = tcAddrForKey(ci.ServerPublic.NodePublic)
c.meowWait = meowWait
return nil
}

Expand All @@ -2277,13 +2300,20 @@ func (c *Client) DERPRegion() *tailcfg.DERPRegion {
return c.ci.Region[0]
}

var errClientClosed = errors.New("tailcat: client is closed")

// Close shuts down the client, closing the WireGuard engine and DERP connections.
func (c *Client) Close() error {
// Don't hold startMu while closing the backend, so a slow
// netstack shutdown can't block other uses of c. The backend's
// Close is idempotent and safe to call concurrently.
c.startMu.Lock()
lb := c.lb
if c.reannounceStop != nil {
c.reannounceStop()
}
// Serialize closing with lazy startup in ensureStarted.
c.closed.Store(true)
c.startMu.Unlock()
if lb == nil {
return nil // never used
Expand All @@ -2310,6 +2340,9 @@ func (c *Client) ensureStarted(ctx context.Context) error {
if c.started {
return nil
}
if c.closed.Load() {
return errClientClosed
}
if err := c.initLocked(); err != nil {
return err
}
Expand All @@ -2333,6 +2366,11 @@ func (c *Client) ensureStarted(ctx context.Context) error {
return err
}
c.started = true
if c.ReannounceInterval > 0 && c.reannounceStop == nil {
ctx, cancel := context.WithCancel(context.Background())
c.reannounceStop = cancel
go c.reannounceLoop(ctx)
}
return nil
}

Expand All @@ -2342,13 +2380,96 @@ func (c *Client) ensureStarted(ctx context.Context) error {
// setup calls. A concurrent first use may ping twice; the handshake
// is idempotent.
func (c *Client) up(ctx context.Context) error {
if c.closed.Load() {
return errClientClosed
}
if c.upDone.Load() {
return nil
}
_, err := c.Ping(ctx)
return err
}

const reannounceMaxBackoff = time.Minute

func (c *Client) reannounceLoop(ctx context.Context) {
interval := c.ReannounceInterval
var fails int
delay := interval
for {
t := time.NewTimer(delay)
select {
case <-ctx.Done():
t.Stop()
return
case <-t.C:
}
if _, err := c.Ping(ctx); err != nil {
if ctx.Err() == nil {
c.lb.logf("re-announce failed (attempt %d): %v", fails+1, err)
}
fails++
shift := fails
if shift > 16 { // the cap below dominates long before this matters
shift = 16
}
// Clamp before multiplying to avoid duration overflow.
base := min(max(time.Second, interval/8), reannounceMaxBackoff)
delay = min(base*time.Duration(1<<shift), max(interval, reannounceMaxBackoff))
} else {
fails = 0
delay = interval
}
}
}

const defaultDialAttemptTimeout = 10 * time.Second

const dialRecoveryAttempts = 3

// dialRecovered re-registers and retries when a dial attempt times out.
// The default budget is about 53s: 3 dials, 2 pings, and 3s of backoff.
func (c *Client) dialRecovered(ctx context.Context, dial func(context.Context) (net.Conn, error)) (net.Conn, error) {
backoff := time.Second
for attempt := 1; ; attempt++ {
if c.closed.Load() {
return nil, errClientClosed
}
conn, timedOut, err := c.dialAttempt(ctx, dial)
if err == nil || ctx.Err() != nil || !timedOut {
return conn, err
}
if attempt >= dialRecoveryAttempts {
return nil, fmt.Errorf("dial timed out after %d attempts; the server may be unreachable or have restarted: %w", attempt, err)
}
c.lb.logf("dial attempt %d timed out; re-registering with the server and retrying", attempt)
// The tunnel may still work if the DERP ping fails.
c.Ping(ctx)
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(backoff):
}
backoff *= 2
}
}

func (c *Client) dialAttempt(ctx context.Context, dial func(context.Context) (net.Conn, error)) (conn net.Conn, timedOut bool, err error) {
timeout := c.dialTimeout
if timeout <= 0 {
timeout = defaultDialAttemptTimeout
}
attemptCtx := ctx
if d, ok := ctx.Deadline(); !ok || time.Until(d) > timeout {
var cancel context.CancelFunc
attemptCtx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
}
conn, err = dial(attemptCtx)
timedOut = ctx.Err() == nil && errors.Is(attemptCtx.Err(), context.DeadlineExceeded)
return conn, timedOut, err
}

// Ping starts the client if needed (see [Client.Dial] for the lazy
// startup behavior), sends a meow ping to the server via DERP
// (resending periodically in case of packet loss), and waits for the
Expand All @@ -2359,6 +2480,9 @@ func (c *Client) up(ctx context.Context) error {
// regardless of ctx.
func (c *Client) Ping(ctx context.Context) (PingResult, error) {
var zero PingResult
if c.closed.Load() {
return zero, errClientClosed
}
if err := c.ensureStarted(ctx); err != nil {
return zero, err
}
Expand All @@ -2376,9 +2500,17 @@ func (c *Client) ping(ctx context.Context) (PingResult, error) {
defer cancel()

var zero PingResult
if ctx.Err() != nil {
return zero, ctx.Err()
}
t0 := time.Now()
mc := c.lb.sys.MagicSock.Get()

// Subscribe before sending. Concurrent pings can share an ACK.
c.meowMu.Lock()
meowed := c.meowed
c.meowMu.Unlock()

dstNode := c.ci.ServerPublic.NodePublic
derpRegion := c.lb.derpRegionID()
pkt := appendMeowInstance(EncodeMeowPing(c.lb.pub, mc.DiscoPublicKey()), c.lb.meowInstance)
Expand Down Expand Up @@ -2406,7 +2538,7 @@ func (c *Client) ping(ctx context.Context) (PingResult, error) {
defer resend.Stop()
for {
select {
case <-c.meowWait:
case <-meowed:
return PingResult{time.Since(t0)}, nil
case <-ctx.Done():
if lastSendErr != nil {
Expand Down Expand Up @@ -2479,7 +2611,9 @@ func (c *Client) Dial(ctx context.Context, network, addr string) (net.Conn, erro
if err := c.up(ctx); err != nil {
return nil, err
}
return c.lb.sys.Dialer.Get().UserDial(ctx, network, addr)
return c.dialRecovered(ctx, func(ctx context.Context) (net.Conn, error) {
return c.lb.sys.Dialer.Get().UserDial(ctx, network, addr)
})
}

// DialTCPPort opens a TCP connection to the given port on the server.
Expand All @@ -2488,7 +2622,9 @@ func (c *Client) DialTCPPort(ctx context.Context, port uint16) (net.Conn, error)
if err := c.up(ctx); err != nil {
return nil, err
}
return c.lb.sys.Dialer.Get().UserDial(ctx, "tcp", net.JoinHostPort(c.serverAddr.String(), fmt.Sprint(port)))
return c.dialRecovered(ctx, func(ctx context.Context) (net.Conn, error) {
return c.lb.sys.Dialer.Get().UserDial(ctx, "tcp", net.JoinHostPort(c.serverAddr.String(), fmt.Sprint(port)))
})
}

var (
Expand All @@ -2511,7 +2647,9 @@ func (c *Client) DialTCP(ctx context.Context, ap netip.AddrPort) (net.Conn, erro
copy(a[12:], a4[:])
ap = netip.AddrPortFrom(netip.AddrFrom16(a), ap.Port())
}
return c.lb.ns.DialContextTCP(ctx, ap)
return c.dialRecovered(ctx, func(ctx context.Context) (net.Conn, error) {
return c.lb.ns.DialContextTCP(ctx, ap)
})
}

// DialUDPPort opens a connected UDP packet connection to the given port on the
Expand Down
Loading