From 07b6ffd55c006706c06e8bb16eecb169730786fb Mon Sep 17 00:00:00 2001
From: Brad Fitzpatrick <bradfitz@tailscale.com>
Date: Mon, 2 Nov 2020 21:11:20 -0800
Subject: [PATCH] ipn: only use Prefs, not computed stateKey, to determine
 server mode

When the service was running without a client (e.g. after a reboot)
and then the owner logs in and the GUI attaches, the computed state
key changed to "" (driven by frontend prefs), and then it was falling
out of server mode, despite the GUI-provided prefs still saying it
wanted server mode.

Also add some logging. And remove a scary "Access denied" from a
user-visible error, making the two possible already-in-use error
messages consistent with each other.
---
 ipn/ipnserver/server.go | 2 +-
 ipn/local.go            | 3 ++-
 2 files changed, 3 insertions(+), 2 deletions(-)

diff --git a/ipn/ipnserver/server.go b/ipn/ipnserver/server.go
index 43acd9ef1..6df546bae 100644
--- a/ipn/ipnserver/server.go
+++ b/ipn/ipnserver/server.go
@@ -314,7 +314,7 @@ func (s *server) checkConnIdentityLocked(ci connIdentity) error {
 	}
 	if su := s.serverModeUser; su != nil && ci.UserID != su.Uid {
 		//lint:ignore ST1005 we want to capitalize Tailscale here
-		return inUseOtherUserError{fmt.Errorf("Tailscale running as %s. Access denied.", su.Username)}
+		return inUseOtherUserError{fmt.Errorf("Tailscale already in use by %s", su.Username)}
 	}
 	return nil
 }
diff --git a/ipn/local.go b/ipn/local.go
index 8dabe1b79..0b5d1cf82 100644
--- a/ipn/local.go
+++ b/ipn/local.go
@@ -415,10 +415,11 @@ func (b *LocalBackend) Start(opts Options) error {
 		return fmt.Errorf("loading requested state: %v", err)
 	}
 
-	b.inServerMode = b.stateKey != ""
+	b.inServerMode = b.prefs.ForceDaemon
 	b.serverURL = b.prefs.ControlURL
 	hostinfo.RoutableIPs = append(hostinfo.RoutableIPs, b.prefs.AdvertiseRoutes...)
 	hostinfo.RequestTags = append(hostinfo.RequestTags, b.prefs.AdvertiseTags...)
+	b.logf("Start: serverMode=%v; stateKey=%q; tags=%q; routes=%v; url=%v", b.inServerMode, b.stateKey, b.prefs.AdvertiseTags, b.prefs.AdvertiseRoutes, b.prefs.ControlURL)
 	applyPrefsToHostinfo(hostinfo, b.prefs)
 
 	b.notify = opts.Notify