diff --git a/feature/captiveportal/captiveportal.go b/feature/captiveportal/captiveportal.go index 115552509..9253b3d8a 100644 --- a/feature/captiveportal/captiveportal.go +++ b/feature/captiveportal/captiveportal.go @@ -16,10 +16,10 @@ import ( "tailscale.com/ipn" "tailscale.com/ipn/ipnext" "tailscale.com/net/captivedetection" - "tailscale.com/syncs" "tailscale.com/tailcfg" "tailscale.com/types/logger" "tailscale.com/util/clientmetric" + "tailscale.com/util/coalescedop" "tailscale.com/util/eventbus" ) @@ -34,9 +34,9 @@ func init() { var metricCaptivePortalDetected = clientmetric.NewCounter("captiveportal_detected") -// captivePortalDetectionInterval is the duration to wait in an unhealthy state with connectivity broken +// captivePortalDetectionDelay is the duration to wait in an unhealthy state with connectivity broken // before running captive portal detection. -const captivePortalDetectionInterval = 2 * time.Second +const captivePortalDetectionDelay = 2 * time.Second // captivePortalWarnable is a Warnable which is set to an unhealthy state when a captive portal is detected. var captivePortalWarnable = health.Register(&health.Warnable{ @@ -57,216 +57,120 @@ type Extension struct { health *health.Tracker ec *eventbus.Client - mu syncs.Mutex - // captiveCtx and captiveCancel are used to control captive portal - // detection. They are protected by 'mu' and can be changed during the - // lifetime of the extension. - // - // captiveCtx will always be non-nil, though it might be a canceled - // context. captiveCancel is non-nil if checkCaptivePortalLoop is - // running, and is set to nil after being canceled. - captiveCtx context.Context - captiveCancel context.CancelFunc + // ctx is canceled by cancel on Shutdown. + ctx context.Context + cancel context.CancelFunc - // needsCaptiveDetection is a channel that is used to signal either - // that captive portal detection is required (sending true) or that the - // backend is healthy and captive portal detection is not required - // (sending false). - needsCaptiveDetection chan bool + // maybeDetectOp serializes and coalesces calls + // to [Extension.maybeDetectCaptivePortal]. + maybeDetectOp *coalescedop.CoalescedOp } func newExtension(logf logger.Logf, sb ipnext.SafeBackend) (ipnext.Extension, error) { - // Initialize the context used to control the captive portal detection - // goroutine in a canceled state, so that it is always non-nil and safe - // to wait on even before the loop has ever started. ctx, cancel := context.WithCancel(context.Background()) - cancel() - return &Extension{ - logf: logf, - sb: sb, - health: sb.Sys().HealthTracker.Get(), - captiveCtx: ctx, - needsCaptiveDetection: make(chan bool), - }, nil + e := &Extension{ + logf: logf, + sb: sb, + health: sb.Sys().HealthTracker.Get(), + ctx: ctx, + cancel: cancel, + } + e.maybeDetectOp = coalescedop.New(e.maybeDetectCaptivePortal) + return e, nil } func (e *Extension) Name() string { return featureName } func (e *Extension) Init(h ipnext.Host) error { e.host = h - h.Hooks().BackendStateChange.Add(e.onBackendStateChange) + h.Hooks().ProfileStateChange.Add(e.onProfileStateChange) e.ec = e.sb.Sys().Bus.Get().Client("captiveportal") eventbus.SubscribeFunc(e.ec, e.onHealthChange) + e.maybeDetectOp.Do() // non-blocking return nil } func (e *Extension) Shutdown() error { - e.mu.Lock() - if e.captiveCancel != nil { - e.captiveCancel() - e.captiveCancel = nil - } - e.mu.Unlock() + e.cancel() if e.ec != nil { e.ec.Close() } return nil } -// onBackendStateChange starts or stops the captive portal detection loop as -// the backend enters or leaves the Running state. It is called with -// LocalBackend's mutex held, so it must not call back into LocalBackend. -func (e *Extension) onBackendStateChange(st ipn.State) { - e.mu.Lock() - defer e.mu.Unlock() - if st == ipn.Running { - // Start a captive portal detection loop if none has been - // started. - if e.captiveCancel == nil { - e.captiveCtx, e.captiveCancel = context.WithCancel(context.Background()) - go e.checkCaptivePortalLoop(e.captiveCtx) - } - } else if e.captiveCancel != nil { - // Transitioning away from Running; stop any existing captive - // portal detection loop. - e.captiveCancel() - e.captiveCancel = nil - - // NOTE: don't set captiveCtx to nil here, to ensure that we - // always have a (canceled) context to wait on in - // onHealthChange. - } +// onProfileStateChange is called when the current profile or its prefs, +// including WantRunning, change. It is called with LocalBackend's mutex held, +// so it must not call back into LocalBackend. +func (e *Extension) onProfileStateChange(ipn.LoginProfileView, ipn.PrefsView, bool) { + e.maybeDetectOp.Do() // non-blocking; coalesced } // onHealthChange is called (via the eventbus) whenever the node's health -// state changes. If connectivity appears to be impacted, it signals the -// detection loop to check for a captive portal. -func (e *Extension) onHealthChange(health.Change) { - state := e.health.CurrentState() - isConnectivityImpacted := false +// state changes. It ignores changes to the [captivePortalWarnable], which are +// made by check itself. +func (e *Extension) onHealthChange(c health.Change) { + if c.Warnable != captivePortalWarnable { + e.maybeDetectOp.Do() // non-blocking; coalesced + } +} + +// isConnectivityImpacted reports whether state has a warning, +// other than the [captivePortalWarnable], that impacts connectivity. +func isConnectivityImpacted(state *health.State) bool { for _, w := range state.Warnings { - // Ignore the captive portal warnable itself. if w.ImpactsConnectivity && w.WarnableCode != captivePortalWarnable.Code { - isConnectivityImpacted = true - break + return true } } + return false +} - // captiveCtx can be changed, and is protected with 'mu'; grab that - // before we start our select, below. - // - // It is guaranteed to be non-nil. - e.mu.Lock() - ctx := e.captiveCtx - e.mu.Unlock() +// wantCaptiveDetection reports whether captive portal detection +// is enabled and connectivity appears to be impacted. +func (e *Extension) wantCaptiveDetection() bool { + return e.captiveDetectionEnabled() && isConnectivityImpacted(e.health.CurrentState()) +} - // If the context is canceled, we don't need to do anything. - if ctx.Err() != nil { +// maybeDetectCaptivePortal runs captive portal detection +// if connectivity has been impacted for [captivePortalDetectionDelay], +// and updates the [captivePortalWarnable] accordingly. +func (e *Extension) maybeDetectCaptivePortal() { + if e.wantCaptiveDetection() { + select { + case <-e.ctx.Done(): + return + case <-time.After(captivePortalDetectionDelay): + } + } + if !e.wantCaptiveDetection() { + // If connectivity is not impacted, we know for sure + // we're not behind a captive portal. + e.health.SetHealthy(captivePortalWarnable) return } - if isConnectivityImpacted { - e.logf("health: connectivity impacted; triggering captive portal detection") - - // Ensure that we select on captiveCtx so that we can time out - // triggering captive portal detection if the loop is shut down. - select { - case e.needsCaptiveDetection <- true: - case <-ctx.Done(): + e.logf("health: connectivity impacted; running captive portal detection") + if e.detectCaptivePortal(e.ctx) { + if !e.health.IsUnhealthy(captivePortalWarnable) { + metricCaptivePortalDetected.Add(1) } + e.health.SetUnhealthy(captivePortalWarnable, health.Args{}) } else { - // If connectivity is not impacted, we know for sure we're not behind a captive portal, - // so drop any warning, and signal that we don't need captive portal detection. e.health.SetHealthy(captivePortalWarnable) - select { - case e.needsCaptiveDetection <- false: - case <-ctx.Done(): - } } } -func (e *Extension) checkCaptivePortalLoop(ctx context.Context) { - var tmr *time.Timer - - maybeStartTimer := func() { - // If there's an existing timer, nothing to do; just continue - // waiting for it to expire. Otherwise, create a new timer. - if tmr == nil { - tmr = time.NewTimer(captivePortalDetectionInterval) - } - } - maybeStopTimer := func() { - if tmr == nil { - return - } - if !tmr.Stop() { - <-tmr.C - } - tmr = nil - } - - for { - if ctx.Err() != nil { - maybeStopTimer() - return - } - - // First, see if we have a signal on our "healthy" channel, which - // takes priority over an existing timer. Because a select is - // nondeterministic, we explicitly check this channel before - // entering the main select below, so that we're guaranteed to - // stop the timer before starting captive portal detection. - select { - case needsCaptiveDetection := <-e.needsCaptiveDetection: - if needsCaptiveDetection { - maybeStartTimer() - } else { - maybeStopTimer() - } - default: - } - - var timerChan <-chan time.Time - if tmr != nil { - timerChan = tmr.C - } - select { - case <-ctx.Done(): - // All done; stop the timer and then exit. - maybeStopTimer() - return - case <-timerChan: - // Kick off captive portal check - e.performCaptiveDetection(ctx) - // nil out the timer and its channel to force recreation - tmr, timerChan = nil, nil - case needsCaptiveDetection := <-e.needsCaptiveDetection: - if needsCaptiveDetection { - maybeStartTimer() - } else { - // Healthy; cancel any existing timer - maybeStopTimer() - } - } - } -} - -// shouldRunCaptivePortalDetection reports whether captive portal detection -// should be run. It is enabled by default, but can be disabled via a control -// knob. It is also only run when the user explicitly wants the backend to be +// captiveDetectionEnabled reports whether captive portal detection is +// enabled. It is enabled by default, but can be disabled via a control knob. +// It is also only enabled when the user explicitly wants the backend to be // running. -func (e *Extension) shouldRunCaptivePortalDetection() bool { +func (e *Extension) captiveDetectionEnabled() bool { return !e.sb.Sys().ControlKnobs().DisableCaptivePortalDetection.Load() && e.host.Profiles().CurrentPrefs().WantRunning() } -// performCaptiveDetection checks if captive portal detection is enabled via controlknob. If so, it runs -// the detection and updates the Warnable accordingly. -func (e *Extension) performCaptiveDetection(ctx context.Context) { - if !e.shouldRunCaptivePortalDetection() { - return - } - +// detectCaptivePortal reports whether a captive portal is detected. +func (e *Extension) detectCaptivePortal(ctx context.Context) (found bool) { d := captivedetection.NewDetector(e.logf) dm := e.host.NodeBackend().DERPMap() var preferredDERP tailcfg.DERPRegionID @@ -276,13 +180,5 @@ func (e *Extension) performCaptiveDetection(ctx context.Context) { } } netMon := e.sb.Sys().NetMon.Get() - found := d.Detect(ctx, netMon, dm, preferredDERP) - if found { - if !e.health.IsUnhealthy(captivePortalWarnable) { - metricCaptivePortalDetected.Add(1) - } - e.health.SetUnhealthy(captivePortalWarnable, health.Args{}) - } else { - e.health.SetHealthy(captivePortalWarnable) - } + return d.Detect(ctx, netMon, dm, preferredDERP) } diff --git a/feature/captiveportal/captiveportal_test.go b/feature/captiveportal/captiveportal_test.go new file mode 100644 index 000000000..4d1d68c4b --- /dev/null +++ b/feature/captiveportal/captiveportal_test.go @@ -0,0 +1,94 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package captiveportal + +import ( + "testing" + "testing/synctest" + "time" + + "tailscale.com/health" + "tailscale.com/ipn" + "tailscale.com/ipn/ipnext" + "tailscale.com/tsd" + "tailscale.com/util/eventbus/eventbustest" +) + +type fakeBackend struct { + ipnext.SafeBackend + sys *tsd.System +} + +func (b fakeBackend) Sys() *tsd.System { return b.sys } + +// fakeHost is an [ipnext.Host] that only provides hooks and the current prefs. +type fakeHost struct { + ipnext.Host + ipnext.ProfileServices + hooks ipnext.Hooks + prefs ipn.Prefs +} + +func (h *fakeHost) Hooks() *ipnext.Hooks { return &h.hooks } +func (h *fakeHost) Profiles() ipnext.ProfileServices { return h } +func (h *fakeHost) CurrentPrefs() ipn.PrefsView { return h.prefs.View() } + +func (h *fakeHost) setWantRunning(e *Extension, wantRunning bool) { + h.prefs.WantRunning = wantRunning + e.onProfileStateChange(ipn.LoginProfileView{}, h.prefs.View(), true) +} + +func TestMaybeDetectCaptivePortal(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + sys := tsd.NewSystemWithBus(eventbustest.NewBus(t)) + ht := sys.HealthTracker.Get() + ht.SetIPNState("Running", true) + ext, err := newExtension(t.Logf, fakeBackend{sys: sys}) + if err != nil { + t.Fatal(err) + } + e := ext.(*Extension) + defer e.Shutdown() + wait := func() { + synctest.Wait() // for the health.Change subscriber + e.maybeDetectOp.Wait() + } + + // Init runs a check, which drops a warning that shouldn't be there. + ht.SetUnhealthy(captivePortalWarnable, nil) + h := &fakeHost{prefs: ipn.Prefs{WantRunning: true}} + if err := e.Init(h); err != nil { + t.Fatal(err) + } + wait() + if ht.IsUnhealthy(captivePortalWarnable) { + t.Error("warning remained after Init") + } + + // Connectivity recovers while check waits to run detection, + // so it doesn't run it. It would panic without a NodeBackend. + ht.SetAnyInterfaceUp(false) + time.Sleep(health.NetworkStatusWarnable.TimeToVisible + captivePortalDetectionDelay/2) + ht.SetAnyInterfaceUp(true) + wait() + + // A change to control health has no Warnable. + e.onHealthChange(health.Change{ControlHealthChanged: true}) + wait() + + // A change to the warning itself doesn't cause a check. + ht.SetUnhealthy(captivePortalWarnable, nil) + wait() + if !ht.IsUnhealthy(captivePortalWarnable) { + t.Error("warning dropped by its own change") + } + + // Clearing WantRunning drops the warning. + h.setWantRunning(e, false) + wait() + if ht.IsUnhealthy(captivePortalWarnable) { + t.Error("warning remained after clearing WantRunning") + } + }) +}