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) + } +}