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 <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
Prakash RudrarajuandClaude Opus 5 authored and Brad Fitzpatrick committed 2026-08-26 13:47:29 -07:00
1 parent d7253cb40e
commit ec2ca5964b
2 files changed
+21 -1

No files matched your search

+10 -1
View File
@@ -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() {
+11
View File
@@ -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)
}
}