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
2 changes: 1 addition & 1 deletion specs.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ The maintainer chose embedded `tailscale.com/tsnet` for TCP and UDP; the decisio

- `tailscaleForwardPlan` accepts only the exact `<gameserver>.<namespace>.svc` host and explicitly advertised protocol/port pairs. Inbound bytes never select a backend address. TCP listens on both tailnet families; UDP binds each assigned tailnet IP because tsnet requires an explicit address.
- The ordinary Go network dialer resolves the Service for each new TCP connection or UDP session. Existing streams/sessions can fail during Service/backend replacement; reconnecting clients resolve the current Service. UDP sessions expire after 30 seconds without traffic in either direction; server-only updates keep an established session alive.
- A shared budget covers every port, protocol and address family. The default is 128 sessions and four queued UDP datagrams per peer (65,507 bytes each) plus one response buffer per UDP session. The operator supplies `TAILSCALE_MAX_SESSIONS` and `TAILSCALE_UDP_QUEUE`. Full budgets or queues drop incoming UDP and excess TCP connections close. Dials and UDP writes time out after five seconds. TCP sockets have five-minute activity timeouts. Shutdown closes listeners and sockets, cancels pending dials, then joins workers. See [relay capacity and measurements](https://github.com/GameplanePanel/Gameplane/blob/master/docs/relay-health.md#forwarding-capacity) for configuration bounds, counters and workload methodology.
- A shared budget covers every port, protocol and address family. The default is 128 sessions and four queued UDP datagrams per peer (65,507 bytes each) plus one response buffer per UDP session. The operator supplies `TAILSCALE_MAX_SESSIONS` and `TAILSCALE_UDP_QUEUE`. One tailnet source address may hold at most a quarter of the session budget (at least two; 32 of the default 128) across all ports and protocols, so a single peer cannot lock other players out. Full budgets, per-peer shares or queues drop incoming UDP and excess TCP connections close. Dials and UDP writes time out after five seconds. TCP sockets have five-minute activity timeouts. Shutdown closes listeners and sockets, cancels pending dials, then joins workers. See [relay capacity and measurements](https://github.com/GameplanePanel/Gameplane/blob/master/docs/relay-health.md#forwarding-capacity) for configuration bounds, counters and workload methodology.
- `tsnet.Server` receives the existing hostname, normalized requested tags and mounted auth key. There is no untagged fallback. The fixed state directory `/var/lib/gameplane-tailscale` uses a per-Pod EmptyDir owned through fsGroup 65532. Container restarts reuse identity. Pod replacement loses state and needs a reusable valid auth key; the Deployment uses Recreate. This is not durable identity across Pod replacement. Remove stale devices in the tailnet admin console to free the hostname. A suffixed/conflicting MagicDNS name cannot report the originally advertised name as ready.
- The operator validates tag syntax before creating the Deployment. Invalid tags remove a prior Deployment and report `TunnelReady=False/InvalidTailscaleTags` with correction guidance; fixing the tags resumes reconciliation. Authentication or tag-authorization failures still fail closed inside tsnet, with no registration attempt that omits requested tags.
- `Up` has a two-minute attempt deadline; failed attempts use the existing capped retry delay. After binding every listener, the binary polls local tailnet status every two seconds with a two-second deadline. Loss of online status, tags or hostname clears readiness. Address changes recreate listeners. Failed listeners close all forwarding sockets and retry. Credentials and interactive login URLs are excluded from logs.
Expand Down
104 changes: 87 additions & 17 deletions tailscale_forward.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"net"
"net/netip"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -64,6 +65,9 @@ type forwarder struct {
telemetry *forwardTelemetry
limits forwardLimits
slots chan struct{}
perPeer int
peerMu sync.Mutex
peerFlows map[netip.Addr]int
wg sync.WaitGroup
listeners []io.Closer // registered before Close; no concurrent additions
closeOnce sync.Once
Expand All @@ -73,7 +77,70 @@ type forwarder struct {
func newForwarder(ctx context.Context, telemetry *forwardTelemetry) *forwarder {
ctx, cancel := context.WithCancel(ctx)
limits := telemetry.limits
return &forwarder{telemetry: telemetry, ctx: ctx, cancel: cancel, limits: limits, slots: make(chan struct{}, limits.sessions), failed: make(chan error, 1)}
return &forwarder{telemetry: telemetry, ctx: ctx, cancel: cancel, limits: limits, slots: make(chan struct{}, limits.sessions), perPeer: perPeerFlowLimit(limits.sessions), peerFlows: map[netip.Addr]int{}, failed: make(chan error, 1)}
}

// perPeerFlowLimit is how many of the shared sessions one tailnet source
// address may hold at once: a quarter of the budget, and never fewer than two.
// Without it a single peer the ACL lets in could open every slot and trickle
// bytes to keep them alive, locking every other player out.
func perPeerFlowLimit(sessions int) int {
return max(2, sessions/4)
}

// peerAddr returns the source IP of a tailnet client, or false when the
// address is not an IP:port (never the case for tsnet listeners).
func peerAddr(addr net.Addr) (netip.Addr, bool) {
if addr == nil {
return netip.Addr{}, false
}
ap, err := netip.ParseAddrPort(addr.String())
if err != nil {
return netip.Addr{}, false
}
return ap.Addr().Unmap(), true
}

// acquirePeer takes a shared slot for a flow from peer, refusing it when that
// peer already holds its per-peer share. A flow whose source cannot be parsed
// counts against the shared budget only.
func (f *forwarder) acquirePeer(protocol *flowCounts, peer net.Addr) (netip.Addr, bool) {
ip, ok := peerAddr(peer)
if ok {
f.peerMu.Lock()
if f.peerFlows[ip] >= f.perPeer {
f.peerMu.Unlock()
protocol.rejected.Add(1)
return netip.Addr{}, false
}
f.peerFlows[ip]++
f.peerMu.Unlock()
}
if !f.acquire(protocol) {
if ok {
f.releasePeerAddr(ip)
}
return netip.Addr{}, false
}
return ip, true
}

// releasePeer returns a flow's shared slot and its per-peer share.
func (f *forwarder) releasePeer(protocol *flowCounts, ip netip.Addr) {
f.release(protocol)
if ip.IsValid() {
f.releasePeerAddr(ip)
}
}

func (f *forwarder) releasePeerAddr(ip netip.Addr) {
f.peerMu.Lock()
defer f.peerMu.Unlock()
if f.peerFlows[ip] <= 1 {
delete(f.peerFlows, ip)
return
}
f.peerFlows[ip]--
}

func (f *forwarder) Close() {
Expand Down Expand Up @@ -117,14 +184,15 @@ func (f *forwarder) serveTCP(listener net.Listener, target string) {
f.fail(fmt.Errorf("TCP listener: %w", err))
return
}
if !f.acquire(&f.telemetry.tcp) {
ip, ok := f.acquirePeer(&f.telemetry.tcp, client.RemoteAddr())
if !ok {
_ = client.Close()
continue
}
f.wg.Add(1)
go func() {
defer f.wg.Done()
defer f.release(&f.telemetry.tcp)
defer f.releasePeer(&f.telemetry.tcp, ip)
f.proxyTCP(client, target)
}()
}
Expand Down Expand Up @@ -216,20 +284,22 @@ func (f *forwarder) serveUDP(listener net.PacketConn, target string) {
key := peer.String()
mu.Lock()
session := sessions[key]
if session == nil && f.acquire(&f.telemetry.udp) {
session = &udpForwardSession{packets: make(chan udpPacket, f.limits.udpQueue)}
sessions[key] = session
f.wg.Add(1)
go func(session *udpForwardSession, peer net.Addr, key string) {
defer f.wg.Done()
defer func() {
mu.Lock()
delete(sessions, key)
f.release(&f.telemetry.udp)
mu.Unlock()
}()
f.proxyUDP(listener, peer, session.packets, target)
}(session, peer, key)
if session == nil {
if ip, ok := f.acquirePeer(&f.telemetry.udp, peer); ok {
session = &udpForwardSession{packets: make(chan udpPacket, f.limits.udpQueue)}
sessions[key] = session
f.wg.Add(1)
go func(session *udpForwardSession, peer net.Addr, key string) {
defer f.wg.Done()
defer func() {
mu.Lock()
delete(sessions, key)
f.releasePeer(&f.telemetry.udp, ip)
mu.Unlock()
}()
f.proxyUDP(listener, peer, session.packets, target)
}(session, peer, key)
}
}
if session != nil {
f.enqueue(session, buf[:n], received)
Expand Down
46 changes: 46 additions & 0 deletions tailscale_forward_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"io"
"net"
"net/http/httptest"
"net/netip"
"strconv"
"strings"
"testing"
Expand Down Expand Up @@ -275,3 +276,48 @@ func TestTailscaleUDPServerTrafficKeepsSessionAlive(t *testing.T) {
t.Fatal("silent session did not expire")
}
}

func TestForwarderCapsFlowsPerPeer(t *testing.T) {
f := newForwarder(context.Background(), &forwardTelemetry{limits: defaultForwardLimits})
defer f.Close()
if f.perPeer != 32 {
t.Fatalf("per-peer limit = %d, want 32 for 128 sessions", f.perPeer)
}
peer := &net.TCPAddr{IP: net.ParseIP("100.64.0.1"), Port: 40000}
var held []netip.Addr
for i := range f.perPeer {
ip, ok := f.acquirePeer(&f.telemetry.tcp, peer)
if !ok {
t.Fatalf("flow %d from one peer refused below its share", i)
}
held = append(held, ip)
}
if _, ok := f.acquirePeer(&f.telemetry.udp, &net.UDPAddr{IP: net.ParseIP("100.64.0.1"), Port: 1}); ok {
t.Fatal("peer exceeded its share across protocols")
}
other, ok := f.acquirePeer(&f.telemetry.tcp, &net.TCPAddr{IP: net.ParseIP("100.64.0.2"), Port: 40000})
if !ok {
t.Fatal("another peer was locked out by the first peer's flows")
}
f.releasePeer(&f.telemetry.tcp, other)
f.releasePeer(&f.telemetry.tcp, held[0])
if ip, ok := f.acquirePeer(&f.telemetry.tcp, peer); !ok {
t.Fatal("released share was not returned to the peer")
} else {
f.releasePeer(&f.telemetry.tcp, ip)
}
for _, ip := range held[1:] {
f.releasePeer(&f.telemetry.tcp, ip)
}
if len(f.peerFlows) != 0 || len(f.slots) != 0 {
t.Fatalf("leaked accounting: peers=%v slots=%d", f.peerFlows, len(f.slots))
}
}

func TestPerPeerFlowLimitFloor(t *testing.T) {
for sessions, want := range map[int]int{1: 2, 2: 2, 8: 2, 12: 3, 128: 32, 256: 64} {
if got := perPeerFlowLimit(sessions); got != want {
t.Errorf("perPeerFlowLimit(%d) = %d, want %d", sessions, got, want)
}
}
}