From ec2ca5964b1693652d1c5bb83b6f3d6173fbd44d Mon Sep 17 00:00:00 2001 From: Prakash Rudraraju <1471544+prakashrj@users.noreply.github.com> Date: Tue, 25 Aug 2026 16:52:47 -0700 Subject: [PATCH] tsnet: don't panic in Close when Start failed before s.sys was set Server.close() dereferenced s.sys.Bus unconditionally. s.sys is only assigned partway through doInit, so it is still nil when Start fails before that point, and Close then panics with a nil pointer dereference. Close is reachable in that state: Start is idempotent via initOnce and returns the stored initErr, so callers that `defer Close()` before checking the error land in close() with s.sys == nil. Every other resource released nearby (s.dialer, s.localAPIListener, s.loopbackListener) is already nil-guarded; this line was the outlier. This is reachable in practice from libtailscale/TailscaleKit, where a failed tsnet start on darwin is followed by a close and surfaces as EXC_BAD_ACCESS rather than the underlying start error. Use GetOK instead of Get as well, so an unset Bus returns ok=false rather than panicking via SubSystem.Get. Adds TestCloseBeforeStart, which panics without this change. Updates #20988 Signed-off-by: Prakash Rudraraju <1471544+prakashrj@users.noreply.github.com> Co-Authored-By: Claude Opus 5 (1M context) --- tsnet/tsnet.go | 11 ++++++++++- tsnet/tsnet_test.go | 11 +++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/tsnet/tsnet.go b/tsnet/tsnet.go index e32c6f6e51..8559f6680e 100644 --- a/tsnet/tsnet.go +++ b/tsnet/tsnet.go @@ -682,7 +682,16 @@ func (s *Server) close() { } wg.Wait() - s.sys.Bus.Get().Close() + // s.sys is only assigned partway through doInit, so it is still nil if + // Start failed before that point. Close is reachable in that state -- + // Start is idempotent via initOnce and returns the stored initErr, so + // callers that `defer Close()` before checking the error land here. + // Use GetOK rather than Get so an unset Bus cannot panic either. + if s.sys != nil { + if bus, ok := s.sys.Bus.GetOK(); ok && bus != nil { + bus.Close() + } + } } func (s *Server) doInit() { diff --git a/tsnet/tsnet_test.go b/tsnet/tsnet_test.go index 6966208147..168384bd84 100644 --- a/tsnet/tsnet_test.go +++ b/tsnet/tsnet_test.go @@ -4035,3 +4035,14 @@ func TestListenMultipleEphemeralPorts(t *testing.T) { testMultipleEphemeral(t, lt) }) } + +// TestCloseBeforeStart verifies that Close on a Server whose Start never ran +// (or failed early) does not panic. s.sys is assigned partway through doInit, +// so it is still nil in that state, and close previously dereferenced +// s.sys.Bus unconditionally. +func TestCloseBeforeStart(t *testing.T) { + s := &Server{} + if err := s.Close(); err != nil { + t.Fatalf("Close: %v", err) + } +}