auto.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package controlclient
  4. import (
  5. "context"
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. "tailscale.com/health"
  13. "tailscale.com/logtail/backoff"
  14. "tailscale.com/net/sockstats"
  15. "tailscale.com/tailcfg"
  16. "tailscale.com/tstime"
  17. "tailscale.com/types/key"
  18. "tailscale.com/types/logger"
  19. "tailscale.com/types/netmap"
  20. "tailscale.com/types/persist"
  21. "tailscale.com/types/structs"
  22. "tailscale.com/util/clientmetric"
  23. "tailscale.com/util/execqueue"
  24. )
  25. type LoginGoal struct {
  26. _ structs.Incomparable
  27. flags LoginFlags // flags to use when logging in
  28. url string // auth url that needs to be visited
  29. }
  30. var _ Client = (*Auto)(nil)
  31. // waitUnpause waits until either the client is unpaused or the Auto client is
  32. // shut down. It reports whether the client should keep running (i.e. it's not
  33. // closed).
  34. func (c *Auto) waitUnpause(routineLogName string) (keepRunning bool) {
  35. c.mu.Lock()
  36. if !c.paused || c.closed {
  37. defer c.mu.Unlock()
  38. return !c.closed
  39. }
  40. unpaused := c.unpausedChanLocked()
  41. c.mu.Unlock()
  42. c.logf("%s: awaiting unpause", routineLogName)
  43. return <-unpaused
  44. }
  45. // updateRoutine is responsible for informing the server of worthy changes to
  46. // our local state. It runs in its own goroutine.
  47. func (c *Auto) updateRoutine() {
  48. defer close(c.updateDone)
  49. bo := backoff.NewBackoff("updateRoutine", c.logf, 30*time.Second)
  50. // lastUpdateGenInformed is the value of lastUpdateAt that we've successfully
  51. // informed the server of.
  52. var lastUpdateGenInformed updateGen
  53. for {
  54. if !c.waitUnpause("updateRoutine") {
  55. c.logf("updateRoutine: exiting")
  56. return
  57. }
  58. c.mu.Lock()
  59. gen := c.lastUpdateGen
  60. ctx := c.mapCtx
  61. needUpdate := gen > 0 && gen != lastUpdateGenInformed && c.loggedIn
  62. c.mu.Unlock()
  63. if !needUpdate {
  64. // Nothing to do, wait for a signal.
  65. select {
  66. case <-ctx.Done():
  67. continue
  68. case <-c.updateCh:
  69. continue
  70. }
  71. }
  72. t0 := c.clock.Now()
  73. err := c.direct.SendUpdate(ctx)
  74. d := time.Since(t0).Round(time.Millisecond)
  75. if err != nil {
  76. if ctx.Err() == nil {
  77. c.direct.logf("lite map update error after %v: %v", d, err)
  78. }
  79. bo.BackOff(ctx, err)
  80. continue
  81. }
  82. bo.BackOff(ctx, nil)
  83. c.direct.logf("[v1] successful lite map update in %v", d)
  84. lastUpdateGenInformed = gen
  85. }
  86. }
  87. // atomicGen is an atomic int64 generator. It is used to generate monotonically
  88. // increasing numbers for updateGen.
  89. var atomicGen atomic.Int64
  90. func nextUpdateGen() updateGen {
  91. return updateGen(atomicGen.Add(1))
  92. }
  93. // updateGen is a monotonically increasing number that represents a particular
  94. // update to the local state.
  95. type updateGen int64
  96. // Auto connects to a tailcontrol server for a node.
  97. // It's a concrete implementation of the Client interface.
  98. type Auto struct {
  99. direct *Direct // our interface to the server APIs
  100. clock tstime.Clock
  101. logf logger.Logf
  102. closed bool
  103. updateCh chan struct{} // readable when we should inform the server of a change
  104. observer Observer // called to update Client status; always non-nil
  105. observerQueue execqueue.ExecQueue
  106. shutdownFn func() // to be called prior to shutdown or nil
  107. unregisterHealthWatch func()
  108. mu sync.Mutex // mutex guards the following fields
  109. wantLoggedIn bool // whether the user wants to be logged in per last method call
  110. urlToVisit string // the last url we were told to visit
  111. expiry time.Time
  112. // lastUpdateGen is the gen of last update we had an update worth sending to
  113. // the server.
  114. lastUpdateGen updateGen
  115. lastStatus atomic.Pointer[Status]
  116. paused bool // whether we should stop making HTTP requests
  117. unpauseWaiters []chan bool // chans that gets sent true (once) on wake, or false on Shutdown
  118. loggedIn bool // true if currently logged in
  119. loginGoal *LoginGoal // non-nil if some login activity is desired
  120. inMapPoll bool // true once we get the first MapResponse in a stream; false when HTTP response ends
  121. state State // TODO(bradfitz): delete this, make it computed by method from other state
  122. authCtx context.Context // context used for auth requests
  123. mapCtx context.Context // context used for netmap and update requests
  124. authCancel func() // cancel authCtx
  125. mapCancel func() // cancel mapCtx
  126. authDone chan struct{} // when closed, authRoutine is done
  127. mapDone chan struct{} // when closed, mapRoutine is done
  128. updateDone chan struct{} // when closed, updateRoutine is done
  129. }
  130. // New creates and starts a new Auto.
  131. func New(opts Options) (*Auto, error) {
  132. c, err := NewNoStart(opts)
  133. if c != nil {
  134. c.Start()
  135. }
  136. return c, err
  137. }
  138. // NewNoStart creates a new Auto, but without calling Start on it.
  139. func NewNoStart(opts Options) (_ *Auto, err error) {
  140. direct, err := NewDirect(opts)
  141. if err != nil {
  142. return nil, err
  143. }
  144. defer func() {
  145. if err != nil {
  146. direct.Close()
  147. }
  148. }()
  149. if opts.Observer == nil {
  150. return nil, errors.New("missing required Options.Observer")
  151. }
  152. if opts.Logf == nil {
  153. opts.Logf = func(fmt string, args ...any) {}
  154. }
  155. if opts.Clock == nil {
  156. opts.Clock = tstime.StdClock{}
  157. }
  158. c := &Auto{
  159. direct: direct,
  160. clock: opts.Clock,
  161. logf: opts.Logf,
  162. updateCh: make(chan struct{}, 1),
  163. authDone: make(chan struct{}),
  164. mapDone: make(chan struct{}),
  165. updateDone: make(chan struct{}),
  166. observer: opts.Observer,
  167. shutdownFn: opts.Shutdown,
  168. }
  169. c.authCtx, c.authCancel = context.WithCancel(context.Background())
  170. c.authCtx = sockstats.WithSockStats(c.authCtx, sockstats.LabelControlClientAuto, opts.Logf)
  171. c.mapCtx, c.mapCancel = context.WithCancel(context.Background())
  172. c.mapCtx = sockstats.WithSockStats(c.mapCtx, sockstats.LabelControlClientAuto, opts.Logf)
  173. c.unregisterHealthWatch = opts.HealthTracker.RegisterWatcher(func(c health.Change) {
  174. if c.WarnableChanged {
  175. direct.ReportWarnableChange(c.Warnable, c.UnhealthyState)
  176. }
  177. })
  178. return c, nil
  179. }
  180. // SetPaused controls whether HTTP activity should be paused.
  181. //
  182. // The client can be paused and unpaused repeatedly, unlike Start and Shutdown, which can only be used once.
  183. func (c *Auto) SetPaused(paused bool) {
  184. c.mu.Lock()
  185. defer c.mu.Unlock()
  186. if paused == c.paused || c.closed {
  187. return
  188. }
  189. c.logf("setPaused(%v)", paused)
  190. c.paused = paused
  191. if paused {
  192. c.cancelMapCtxLocked()
  193. c.cancelAuthCtxLocked()
  194. return
  195. }
  196. for _, ch := range c.unpauseWaiters {
  197. ch <- true
  198. }
  199. c.unpauseWaiters = nil
  200. }
  201. // Start starts the client's goroutines.
  202. //
  203. // It should only be called for clients created by NewNoStart.
  204. func (c *Auto) Start() {
  205. go c.authRoutine()
  206. go c.mapRoutine()
  207. go c.updateRoutine()
  208. }
  209. // updateControl sends a new OmitPeers, non-streaming map request (to just send
  210. // Hostinfo/Netinfo/Endpoints info, while keeping an existing streaming response
  211. // open).
  212. //
  213. // It should be called whenever there's something new to tell the server.
  214. func (c *Auto) updateControl() {
  215. gen := nextUpdateGen()
  216. c.mu.Lock()
  217. if gen < c.lastUpdateGen {
  218. // This update is out of date.
  219. c.mu.Unlock()
  220. return
  221. }
  222. c.lastUpdateGen = gen
  223. c.mu.Unlock()
  224. select {
  225. case c.updateCh <- struct{}{}:
  226. default:
  227. }
  228. }
  229. // cancelAuthCtxLocked is like cancelAuthCtx, but assumes the caller holds c.mu.
  230. func (c *Auto) cancelAuthCtxLocked() {
  231. if c.authCancel != nil {
  232. c.authCancel()
  233. }
  234. if !c.closed {
  235. c.authCtx, c.authCancel = context.WithCancel(context.Background())
  236. c.authCtx = sockstats.WithSockStats(c.authCtx, sockstats.LabelControlClientAuto, c.logf)
  237. }
  238. }
  239. // cancelMapCtxLocked is like cancelMapCtx, but assumes the caller holds c.mu.
  240. func (c *Auto) cancelMapCtxLocked() {
  241. if c.mapCancel != nil {
  242. c.mapCancel()
  243. }
  244. if !c.closed {
  245. c.mapCtx, c.mapCancel = context.WithCancel(context.Background())
  246. c.mapCtx = sockstats.WithSockStats(c.mapCtx, sockstats.LabelControlClientAuto, c.logf)
  247. }
  248. }
  249. // restartMap cancels the existing mapPoll and liteUpdates, and then starts a
  250. // new one.
  251. func (c *Auto) restartMap() {
  252. c.mu.Lock()
  253. c.cancelMapCtxLocked()
  254. synced := c.inMapPoll
  255. c.mu.Unlock()
  256. c.logf("[v1] restartMap: synced=%v", synced)
  257. c.updateControl()
  258. }
  259. func (c *Auto) authRoutine() {
  260. defer close(c.authDone)
  261. bo := backoff.NewBackoff("authRoutine", c.logf, 30*time.Second)
  262. for {
  263. if !c.waitUnpause("authRoutine") {
  264. c.logf("authRoutine: exiting")
  265. return
  266. }
  267. c.mu.Lock()
  268. goal := c.loginGoal
  269. ctx := c.authCtx
  270. if goal != nil {
  271. c.logf("[v1] authRoutine: %s; wantLoggedIn=%v", c.state, true)
  272. } else {
  273. c.logf("[v1] authRoutine: %s; goal=nil paused=%v", c.state, c.paused)
  274. }
  275. c.mu.Unlock()
  276. report := func(err error, msg string) {
  277. c.logf("[v1] %s: %v", msg, err)
  278. // don't send status updates for context errors,
  279. // since context cancelation is always on purpose.
  280. if ctx.Err() == nil {
  281. c.sendStatus("authRoutine-report", err, "", nil)
  282. }
  283. }
  284. if goal == nil {
  285. c.direct.health.SetAuthRoutineInError(nil)
  286. // Wait for user to Login or Logout.
  287. <-ctx.Done()
  288. c.logf("[v1] authRoutine: context done.")
  289. continue
  290. }
  291. c.mu.Lock()
  292. c.urlToVisit = goal.url
  293. if goal.url != "" {
  294. c.state = StateURLVisitRequired
  295. } else {
  296. c.state = StateAuthenticating
  297. }
  298. c.mu.Unlock()
  299. var url string
  300. var err error
  301. var f string
  302. if goal.url != "" {
  303. url, err = c.direct.WaitLoginURL(ctx, goal.url)
  304. f = "WaitLoginURL"
  305. } else {
  306. url, err = c.direct.TryLogin(ctx, goal.flags)
  307. f = "TryLogin"
  308. }
  309. if err != nil {
  310. c.direct.health.SetAuthRoutineInError(err)
  311. report(err, f)
  312. bo.BackOff(ctx, err)
  313. continue
  314. }
  315. if url != "" {
  316. // goal.url ought to be empty here. However, not all control servers
  317. // get this right, and logging about it here just generates noise.
  318. //
  319. // TODO(bradfitz): I don't follow that comment. Our own testcontrol
  320. // used by tstest/integration hits this path, in fact.
  321. if c.direct.panicOnUse {
  322. panic("tainted client")
  323. }
  324. c.mu.Lock()
  325. c.urlToVisit = url
  326. c.loginGoal = &LoginGoal{
  327. flags: LoginDefault,
  328. url: url,
  329. }
  330. c.state = StateURLVisitRequired
  331. c.mu.Unlock()
  332. c.sendStatus("authRoutine-url", err, url, nil)
  333. if goal.url == url {
  334. // The server sent us the same URL we already tried,
  335. // backoff to avoid a busy loop.
  336. bo.BackOff(ctx, errors.New("login URL not changing"))
  337. } else {
  338. bo.BackOff(ctx, nil)
  339. }
  340. continue
  341. }
  342. // success
  343. c.direct.health.SetAuthRoutineInError(nil)
  344. c.mu.Lock()
  345. c.urlToVisit = ""
  346. c.loggedIn = true
  347. c.loginGoal = nil
  348. c.state = StateAuthenticated
  349. c.mu.Unlock()
  350. c.sendStatus("authRoutine-success", nil, "", nil)
  351. c.restartMap()
  352. bo.BackOff(ctx, nil)
  353. }
  354. }
  355. // ExpiryForTests returns the credential expiration time, or the zero value if
  356. // the expiration time isn't known. It's used in tests only.
  357. func (c *Auto) ExpiryForTests() time.Time {
  358. c.mu.Lock()
  359. defer c.mu.Unlock()
  360. return c.expiry
  361. }
  362. // DirectForTest returns the underlying direct client object.
  363. // It's used in tests only.
  364. func (c *Auto) DirectForTest() *Direct {
  365. return c.direct
  366. }
  367. // unpausedChanLocked returns a new channel that gets sent
  368. // either a true when unpaused or false on Auto.Shutdown.
  369. //
  370. // c.mu must be held
  371. func (c *Auto) unpausedChanLocked() <-chan bool {
  372. unpaused := make(chan bool, 1)
  373. c.unpauseWaiters = append(c.unpauseWaiters, unpaused)
  374. return unpaused
  375. }
  376. // mapRoutineState is the state of Auto.mapRoutine while it's running.
  377. type mapRoutineState struct {
  378. c *Auto
  379. bo *backoff.Backoff
  380. }
  381. var _ NetmapDeltaUpdater = mapRoutineState{}
  382. func (mrs mapRoutineState) UpdateFullNetmap(nm *netmap.NetworkMap) {
  383. c := mrs.c
  384. c.mu.Lock()
  385. ctx := c.mapCtx
  386. c.inMapPoll = true
  387. if c.loggedIn {
  388. c.state = StateSynchronized
  389. }
  390. c.expiry = nm.Expiry
  391. stillAuthed := c.loggedIn
  392. c.logf("[v1] mapRoutine: netmap received: %s", c.state)
  393. c.mu.Unlock()
  394. if stillAuthed {
  395. c.sendStatus("mapRoutine-got-netmap", nil, "", nm)
  396. }
  397. // Reset the backoff timer if we got a netmap.
  398. mrs.bo.BackOff(ctx, nil)
  399. }
  400. func (mrs mapRoutineState) UpdateNetmapDelta(muts []netmap.NodeMutation) bool {
  401. c := mrs.c
  402. c.mu.Lock()
  403. goodState := c.loggedIn && c.inMapPoll
  404. ndu, canDelta := c.observer.(NetmapDeltaUpdater)
  405. c.mu.Unlock()
  406. if !goodState || !canDelta {
  407. return false
  408. }
  409. ctx, cancel := context.WithTimeout(c.mapCtx, 2*time.Second)
  410. defer cancel()
  411. var ok bool
  412. err := c.observerQueue.RunSync(ctx, func() {
  413. ok = ndu.UpdateNetmapDelta(muts)
  414. })
  415. return err == nil && ok
  416. }
  417. // mapRoutine is responsible for keeping a read-only streaming connection to the
  418. // control server, and keeping the netmap up to date.
  419. func (c *Auto) mapRoutine() {
  420. defer close(c.mapDone)
  421. mrs := mapRoutineState{
  422. c: c,
  423. bo: backoff.NewBackoff("mapRoutine", c.logf, 30*time.Second),
  424. }
  425. for {
  426. if !c.waitUnpause("mapRoutine") {
  427. c.logf("mapRoutine: exiting")
  428. return
  429. }
  430. c.mu.Lock()
  431. c.logf("[v1] mapRoutine: %s", c.state)
  432. loggedIn := c.loggedIn
  433. ctx := c.mapCtx
  434. c.mu.Unlock()
  435. report := func(err error, msg string) {
  436. c.logf("[v1] %s: %v", msg, err)
  437. err = fmt.Errorf("%s: %w", msg, err)
  438. // don't send status updates for context errors,
  439. // since context cancelation is always on purpose.
  440. if ctx.Err() == nil {
  441. c.sendStatus("mapRoutine1", err, "", nil)
  442. }
  443. }
  444. if !loggedIn {
  445. // Wait for something interesting to happen
  446. c.mu.Lock()
  447. c.inMapPoll = false
  448. c.mu.Unlock()
  449. <-ctx.Done()
  450. c.logf("[v1] mapRoutine: context done.")
  451. continue
  452. }
  453. c.direct.health.SetOutOfPollNetMap()
  454. err := c.direct.PollNetMap(ctx, mrs)
  455. c.direct.health.SetOutOfPollNetMap()
  456. c.mu.Lock()
  457. c.inMapPoll = false
  458. if c.state == StateSynchronized {
  459. c.state = StateAuthenticated
  460. }
  461. paused := c.paused
  462. c.mu.Unlock()
  463. if paused {
  464. mrs.bo.BackOff(ctx, nil)
  465. c.logf("mapRoutine: paused")
  466. } else {
  467. mrs.bo.BackOff(ctx, err)
  468. report(err, "PollNetMap")
  469. }
  470. }
  471. }
  472. func (c *Auto) AuthCantContinue() bool {
  473. if c == nil {
  474. return true
  475. }
  476. c.mu.Lock()
  477. defer c.mu.Unlock()
  478. return !c.loggedIn && (c.loginGoal == nil || c.loginGoal.url != "")
  479. }
  480. func (c *Auto) SetHostinfo(hi *tailcfg.Hostinfo) {
  481. if hi == nil {
  482. panic("nil Hostinfo")
  483. }
  484. if !c.direct.SetHostinfo(hi) {
  485. // No changes. Don't log.
  486. return
  487. }
  488. // Send new Hostinfo to server
  489. c.updateControl()
  490. }
  491. func (c *Auto) SetNetInfo(ni *tailcfg.NetInfo) {
  492. if ni == nil {
  493. panic("nil NetInfo")
  494. }
  495. if !c.direct.SetNetInfo(ni) {
  496. return
  497. }
  498. // Send new NetInfo to server
  499. c.updateControl()
  500. }
  501. // SetTKAHead updates the TKA head hash that map-request infrastructure sends.
  502. func (c *Auto) SetTKAHead(headHash string) {
  503. if !c.direct.SetTKAHead(headHash) {
  504. return
  505. }
  506. // Send new TKAHead to server
  507. c.updateControl()
  508. }
  509. // sendStatus can not be called with the c.mu held.
  510. func (c *Auto) sendStatus(who string, err error, url string, nm *netmap.NetworkMap) {
  511. c.mu.Lock()
  512. if c.closed {
  513. c.mu.Unlock()
  514. return
  515. }
  516. state := c.state
  517. loggedIn := c.loggedIn
  518. inMapPoll := c.inMapPoll
  519. c.mu.Unlock()
  520. c.logf("[v1] sendStatus: %s: %v", who, state)
  521. var p persist.PersistView
  522. if nm != nil && loggedIn && inMapPoll {
  523. p = c.direct.GetPersist()
  524. } else {
  525. // don't send netmap status, as it's misleading when we're
  526. // not logged in.
  527. nm = nil
  528. }
  529. newSt := &Status{
  530. URL: url,
  531. Persist: p,
  532. NetMap: nm,
  533. Err: err,
  534. state: state,
  535. }
  536. c.lastStatus.Store(newSt)
  537. // Launch a new goroutine to avoid blocking the caller while the observer
  538. // does its thing, which may result in a call back into the client.
  539. metricQueued.Add(1)
  540. c.observerQueue.Add(func() {
  541. if canSkipStatus(newSt, c.lastStatus.Load()) {
  542. metricSkippable.Add(1)
  543. if !c.direct.controlKnobs.DisableSkipStatusQueue.Load() {
  544. metricSkipped.Add(1)
  545. return
  546. }
  547. }
  548. c.observer.SetControlClientStatus(c, *newSt)
  549. // Best effort stop retaining the memory now that we've sent it to the
  550. // observer (LocalBackend). We CAS here because the caller goroutine is
  551. // doing a Store which we want to win a race. This is only a memory
  552. // optimization and is not for correctness.
  553. //
  554. // If the CAS fails, that means somebody else's Store replaced our
  555. // pointer (so mission accomplished: our netmap is no longer retained in
  556. // any case) and that Store caller will be responsible for removing
  557. // their own netmap (or losing their race too, down the chain).
  558. // Eventually the last caller will win this CAS and zero lastStatus.
  559. c.lastStatus.CompareAndSwap(newSt, nil)
  560. })
  561. }
  562. var (
  563. metricQueued = clientmetric.NewCounter("controlclient_auto_status_queued")
  564. metricSkippable = clientmetric.NewCounter("controlclient_auto_status_queue_skippable")
  565. metricSkipped = clientmetric.NewCounter("controlclient_auto_status_queue_skipped")
  566. )
  567. // canSkipStatus reports whether we can skip sending s1, knowing
  568. // that s2 is enqueued sometime in the future after s1.
  569. //
  570. // s1 must be non-nil. s2 may be nil.
  571. func canSkipStatus(s1, s2 *Status) bool {
  572. if s2 == nil {
  573. // Nothing in the future.
  574. return false
  575. }
  576. if s1 == s2 {
  577. // If the last item in the queue is the same as s1,
  578. // we can't skip it.
  579. return false
  580. }
  581. if s1.Err != nil || s1.URL != "" {
  582. // If s1 has an error or a URL, we shouldn't skip it, lest the error go
  583. // away in s2 or in-between. We want to make sure all the subsystems see
  584. // it. Plus there aren't many of these, so not worth skipping.
  585. return false
  586. }
  587. if !s1.Persist.Equals(s2.Persist) || s1.state != s2.state {
  588. // If s1 has a different Persist or state than s2,
  589. // don't skip it. We only care about skipping the typical
  590. // entries where the only difference is the NetMap.
  591. return false
  592. }
  593. // If nothing above precludes it, and both s1 and s2 have NetMaps, then
  594. // we can skip it, because s2's NetMap is a newer version and we can
  595. // jump straight from whatever state we had before to s2's state,
  596. // without passing through s1's state first. A NetMap is regrettably a
  597. // full snapshot of the state, not an incremental delta. We're slowly
  598. // moving towards passing around only deltas around internally at all
  599. // layers, but this is explicitly the case where we didn't have a delta
  600. // path for the message we received over the wire and had to resort
  601. // to the legacy full NetMap path. And then we can get behind processing
  602. // these full NetMap snapshots in LocalBackend/wgengine/magicsock/netstack
  603. // and this path (when it returns true) lets us skip over useless work
  604. // and not get behind in the queue. This matters in particular for tailnets
  605. // that are both very large + very churny.
  606. return s1.NetMap != nil && s2.NetMap != nil
  607. }
  608. func (c *Auto) Login(flags LoginFlags) {
  609. c.logf("client.Login(%v)", flags)
  610. c.mu.Lock()
  611. defer c.mu.Unlock()
  612. if c.closed {
  613. return
  614. }
  615. if c.direct != nil && c.direct.panicOnUse {
  616. panic("tainted client")
  617. }
  618. c.wantLoggedIn = true
  619. c.loginGoal = &LoginGoal{
  620. flags: flags,
  621. }
  622. c.cancelMapCtxLocked()
  623. c.cancelAuthCtxLocked()
  624. }
  625. var ErrClientClosed = errors.New("client closed")
  626. func (c *Auto) Logout(ctx context.Context) error {
  627. c.logf("client.Logout()")
  628. c.mu.Lock()
  629. c.wantLoggedIn = false
  630. c.loginGoal = nil
  631. closed := c.closed
  632. if c.direct != nil && c.direct.panicOnUse {
  633. panic("tainted client")
  634. }
  635. c.mu.Unlock()
  636. if closed {
  637. return ErrClientClosed
  638. }
  639. if err := c.direct.TryLogout(ctx); err != nil {
  640. return err
  641. }
  642. c.mu.Lock()
  643. c.loggedIn = false
  644. c.state = StateNotAuthenticated
  645. c.cancelAuthCtxLocked()
  646. c.cancelMapCtxLocked()
  647. c.mu.Unlock()
  648. c.sendStatus("authRoutine-wantout", nil, "", nil)
  649. return nil
  650. }
  651. func (c *Auto) SetExpirySooner(ctx context.Context, expiry time.Time) error {
  652. return c.direct.SetExpirySooner(ctx, expiry)
  653. }
  654. // UpdateEndpoints sets the client's discovered endpoints and sends
  655. // them to the control server if they've changed.
  656. //
  657. // It does not retain the provided slice.
  658. func (c *Auto) UpdateEndpoints(endpoints []tailcfg.Endpoint) {
  659. changed := c.direct.SetEndpoints(endpoints)
  660. if changed {
  661. c.updateControl()
  662. }
  663. }
  664. func (c *Auto) Shutdown() {
  665. c.mu.Lock()
  666. if c.closed {
  667. c.mu.Unlock()
  668. return
  669. }
  670. c.logf("client.Shutdown ...")
  671. shutdownFn := c.shutdownFn
  672. direct := c.direct
  673. c.closed = true
  674. c.observerQueue.Shutdown()
  675. c.cancelAuthCtxLocked()
  676. c.cancelMapCtxLocked()
  677. for _, w := range c.unpauseWaiters {
  678. w <- false
  679. }
  680. c.unpauseWaiters = nil
  681. c.mu.Unlock()
  682. if shutdownFn != nil {
  683. shutdownFn()
  684. }
  685. c.unregisterHealthWatch()
  686. <-c.authDone
  687. <-c.mapDone
  688. <-c.updateDone
  689. if direct != nil {
  690. direct.Close()
  691. }
  692. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  693. defer cancel()
  694. c.observerQueue.Wait(ctx)
  695. c.logf("Client.Shutdown done.")
  696. }
  697. // NodePublicKey returns the node public key currently in use. This is
  698. // used exclusively in tests.
  699. func (c *Auto) TestOnlyNodePublicKey() key.NodePublic {
  700. priv := c.direct.GetPersist()
  701. return priv.PrivateNodeKey().Public()
  702. }
  703. func (c *Auto) TestOnlySetAuthKey(authkey string) {
  704. c.direct.mu.Lock()
  705. defer c.direct.mu.Unlock()
  706. c.direct.authKey = authkey
  707. }
  708. func (c *Auto) TestOnlyTimeNow() time.Time {
  709. return c.clock.Now()
  710. }
  711. // SetDNS sends the SetDNSRequest request to the control plane server,
  712. // requesting a DNS record be created or updated.
  713. func (c *Auto) SetDNS(ctx context.Context, req *tailcfg.SetDNSRequest) error {
  714. return c.direct.SetDNS(ctx, req)
  715. }
  716. func (c *Auto) DoNoiseRequest(req *http.Request) (*http.Response, error) {
  717. return c.direct.DoNoiseRequest(req)
  718. }
  719. // GetSingleUseNoiseRoundTripper returns a RoundTripper that can be only be used
  720. // once (and must be used once) to make a single HTTP request over the noise
  721. // channel to the coordination server.
  722. //
  723. // In addition to the RoundTripper, it returns the HTTP/2 channel's early noise
  724. // payload, if any.
  725. func (c *Auto) GetSingleUseNoiseRoundTripper(ctx context.Context) (http.RoundTripper, *tailcfg.EarlyNoise, error) {
  726. return c.direct.GetSingleUseNoiseRoundTripper(ctx)
  727. }