map.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package controlclient
  4. import (
  5. "cmp"
  6. "context"
  7. "crypto/sha256"
  8. "encoding/hex"
  9. "encoding/json"
  10. "io"
  11. "maps"
  12. "net"
  13. "reflect"
  14. "runtime"
  15. "runtime/debug"
  16. "slices"
  17. "strconv"
  18. "sync"
  19. "time"
  20. "tailscale.com/control/controlknobs"
  21. "tailscale.com/envknob"
  22. "tailscale.com/hostinfo"
  23. "tailscale.com/tailcfg"
  24. "tailscale.com/tstime"
  25. "tailscale.com/types/key"
  26. "tailscale.com/types/logger"
  27. "tailscale.com/types/netmap"
  28. "tailscale.com/types/ptr"
  29. "tailscale.com/types/views"
  30. "tailscale.com/util/clientmetric"
  31. "tailscale.com/util/mak"
  32. "tailscale.com/util/set"
  33. "tailscale.com/util/slicesx"
  34. "tailscale.com/wgengine/filter"
  35. )
  36. // mapSession holds the state over a long-polled "map" request to the
  37. // control plane.
  38. //
  39. // It accepts incremental tailcfg.MapResponse values to
  40. // netMapForResponse and returns fully inflated NetworkMaps, filling
  41. // in the omitted data implicit from prior MapResponse values from
  42. // within the same session (the same long-poll HTTP response to the
  43. // one MapRequest).
  44. type mapSession struct {
  45. // Immutable fields.
  46. netmapUpdater NetmapUpdater // called on changes (in addition to the optional hooks below)
  47. controlKnobs *controlknobs.Knobs // or nil
  48. privateNodeKey key.NodePrivate
  49. publicNodeKey key.NodePublic
  50. logf logger.Logf
  51. vlogf logger.Logf
  52. machinePubKey key.MachinePublic
  53. altClock tstime.Clock // if nil, regular time is used
  54. cancel context.CancelFunc // always non-nil, shuts down caller's base long poll context
  55. // sessionAliveCtx is a Background-based context that's alive for the
  56. // duration of the mapSession that we own the lifetime of. It's closed by
  57. // sessionAliveCtxClose.
  58. sessionAliveCtx context.Context
  59. sessionAliveCtxClose context.CancelFunc // closes sessionAliveCtx
  60. // Optional hooks, guaranteed non-nil (set to no-op funcs) by the
  61. // newMapSession constructor. They must be overridden if desired
  62. // before the mapSession is used.
  63. // onDebug specifies what to do with a *tailcfg.Debug message.
  64. onDebug func(context.Context, *tailcfg.Debug) error
  65. // onSelfNodeChanged is called before the NetmapUpdater if the self node was
  66. // changed.
  67. onSelfNodeChanged func(*netmap.NetworkMap)
  68. // Fields storing state over the course of multiple MapResponses.
  69. lastPrintMap time.Time
  70. lastNode tailcfg.NodeView
  71. lastCapSet set.Set[tailcfg.NodeCapability]
  72. peers map[tailcfg.NodeID]tailcfg.NodeView
  73. lastDNSConfig *tailcfg.DNSConfig
  74. lastDERPMap *tailcfg.DERPMap
  75. lastUserProfile map[tailcfg.UserID]tailcfg.UserProfileView
  76. lastPacketFilterRules views.Slice[tailcfg.FilterRule] // concatenation of all namedPacketFilters
  77. namedPacketFilters map[string]views.Slice[tailcfg.FilterRule]
  78. lastParsedPacketFilter []filter.Match
  79. lastSSHPolicy *tailcfg.SSHPolicy
  80. collectServices bool
  81. lastDomain string
  82. lastDomainAuditLogID string
  83. lastHealth []string
  84. lastDisplayMessages map[tailcfg.DisplayMessageID]tailcfg.DisplayMessage
  85. lastPopBrowserURL string
  86. lastTKAInfo *tailcfg.TKAInfo
  87. lastNetmapSummary string // from NetworkMap.VeryConcise
  88. }
  89. // newMapSession returns a mostly unconfigured new mapSession.
  90. //
  91. // Modify its optional fields on the returned value before use.
  92. //
  93. // It must have its Close method called to release resources.
  94. func newMapSession(privateNodeKey key.NodePrivate, nu NetmapUpdater, controlKnobs *controlknobs.Knobs) *mapSession {
  95. ms := &mapSession{
  96. netmapUpdater: nu,
  97. controlKnobs: controlKnobs,
  98. privateNodeKey: privateNodeKey,
  99. publicNodeKey: privateNodeKey.Public(),
  100. lastDNSConfig: new(tailcfg.DNSConfig),
  101. lastUserProfile: map[tailcfg.UserID]tailcfg.UserProfileView{},
  102. // Non-nil no-op defaults, to be optionally overridden by the caller.
  103. logf: logger.Discard,
  104. vlogf: logger.Discard,
  105. cancel: func() {},
  106. onDebug: func(context.Context, *tailcfg.Debug) error { return nil },
  107. onSelfNodeChanged: func(*netmap.NetworkMap) {},
  108. }
  109. ms.sessionAliveCtx, ms.sessionAliveCtxClose = context.WithCancel(context.Background())
  110. return ms
  111. }
  112. // occasionallyPrintSummary logs summary at most once very 5 minutes. The
  113. // summary is the Netmap.VeryConcise result from the last received map response.
  114. func (ms *mapSession) occasionallyPrintSummary(summary string) {
  115. // Occasionally print the netmap header.
  116. // This is handy for debugging, and our logs processing
  117. // pipeline depends on it. (TODO: Remove this dependency.)
  118. now := ms.clock().Now()
  119. if now.Sub(ms.lastPrintMap) < 5*time.Minute {
  120. return
  121. }
  122. ms.lastPrintMap = now
  123. ms.logf("[v1] new network map (periodic):\n%s", summary)
  124. }
  125. func (ms *mapSession) clock() tstime.Clock {
  126. return cmp.Or[tstime.Clock](ms.altClock, tstime.StdClock{})
  127. }
  128. func (ms *mapSession) Close() {
  129. ms.sessionAliveCtxClose()
  130. }
  131. // HandleNonKeepAliveMapResponse handles a non-KeepAlive MapResponse (full or
  132. // incremental).
  133. //
  134. // All fields that are valid on a KeepAlive MapResponse have already been
  135. // handled.
  136. //
  137. // TODO(bradfitz): make this handle all fields later. For now (2023-08-20) this
  138. // is [re]factoring progress enough.
  139. func (ms *mapSession) HandleNonKeepAliveMapResponse(ctx context.Context, resp *tailcfg.MapResponse) error {
  140. if debug := resp.Debug; debug != nil {
  141. if err := ms.onDebug(ctx, debug); err != nil {
  142. return err
  143. }
  144. }
  145. if DevKnob.StripEndpoints() {
  146. for _, p := range resp.Peers {
  147. p.Endpoints = nil
  148. }
  149. for _, p := range resp.PeersChanged {
  150. p.Endpoints = nil
  151. }
  152. }
  153. // For responses that mutate the self node, check for updated nodeAttrs.
  154. if resp.Node != nil {
  155. upgradeNode(resp.Node)
  156. if DevKnob.StripCaps() {
  157. resp.Node.Capabilities = nil
  158. resp.Node.CapMap = nil
  159. }
  160. // If the server is old and is still sending us Capabilities instead of
  161. // CapMap, convert it to CapMap early so the rest of the client code can
  162. // work only in terms of CapMap.
  163. for _, c := range resp.Node.Capabilities {
  164. if _, ok := resp.Node.CapMap[c]; !ok {
  165. mak.Set(&resp.Node.CapMap, c, nil)
  166. }
  167. }
  168. ms.controlKnobs.UpdateFromNodeAttributes(resp.Node.CapMap)
  169. }
  170. for _, p := range resp.Peers {
  171. upgradeNode(p)
  172. }
  173. for _, p := range resp.PeersChanged {
  174. upgradeNode(p)
  175. }
  176. // Call Node.InitDisplayNames on any changed nodes.
  177. initDisplayNames(cmp.Or(resp.Node.View(), ms.lastNode), resp)
  178. ms.patchifyPeersChanged(resp)
  179. ms.updateStateFromResponse(resp)
  180. if ms.tryHandleIncrementally(resp) {
  181. ms.occasionallyPrintSummary(ms.lastNetmapSummary)
  182. return nil
  183. }
  184. // We have to rebuild the whole netmap (lots of garbage & work downstream of
  185. // our UpdateFullNetmap call). This is the part we tried to avoid but
  186. // some field mutations (especially rare ones) aren't yet handled.
  187. if runtime.GOOS == "ios" {
  188. // Memory is tight on iOS. Free what we can while we
  189. // can before this potential burst of in-use memory.
  190. debug.FreeOSMemory()
  191. }
  192. nm := ms.netmap()
  193. ms.lastNetmapSummary = nm.VeryConcise()
  194. ms.occasionallyPrintSummary(ms.lastNetmapSummary)
  195. // If the self node changed, we might need to update persist.
  196. if resp.Node != nil {
  197. ms.onSelfNodeChanged(nm)
  198. }
  199. ms.netmapUpdater.UpdateFullNetmap(nm)
  200. return nil
  201. }
  202. // upgradeNode upgrades Node fields from the server into the modern forms
  203. // not using deprecated fields.
  204. func upgradeNode(n *tailcfg.Node) {
  205. if n == nil {
  206. return
  207. }
  208. if n.LegacyDERPString != "" {
  209. if n.HomeDERP == 0 {
  210. ip, portStr, err := net.SplitHostPort(n.LegacyDERPString)
  211. if ip == tailcfg.DerpMagicIP && err == nil {
  212. port, err := strconv.Atoi(portStr)
  213. if err == nil {
  214. n.HomeDERP = port
  215. }
  216. }
  217. }
  218. n.LegacyDERPString = ""
  219. }
  220. if DevKnob.StripHomeDERP() {
  221. n.HomeDERP = 0
  222. }
  223. if n.AllowedIPs == nil {
  224. n.AllowedIPs = slices.Clone(n.Addresses)
  225. }
  226. }
  227. func (ms *mapSession) tryHandleIncrementally(res *tailcfg.MapResponse) bool {
  228. if ms.controlKnobs != nil && ms.controlKnobs.DisableDeltaUpdates.Load() {
  229. return false
  230. }
  231. nud, ok := ms.netmapUpdater.(NetmapDeltaUpdater)
  232. if !ok {
  233. return false
  234. }
  235. mutations, ok := netmap.MutationsFromMapResponse(res, time.Now())
  236. if ok && len(mutations) > 0 {
  237. return nud.UpdateNetmapDelta(mutations)
  238. }
  239. return ok
  240. }
  241. // updateStats are some stats from updateStateFromResponse, primarily for
  242. // testing. It's meant to be cheap enough to always compute, though. It doesn't
  243. // allocate.
  244. type updateStats struct {
  245. allNew bool
  246. added int
  247. removed int
  248. changed int
  249. }
  250. // updateStateFromResponse updates ms from res. It takes ownership of res.
  251. func (ms *mapSession) updateStateFromResponse(resp *tailcfg.MapResponse) {
  252. ms.updatePeersStateFromResponse(resp)
  253. if resp.Node != nil {
  254. ms.lastNode = resp.Node.View()
  255. capSet := set.Set[tailcfg.NodeCapability]{}
  256. for _, c := range resp.Node.Capabilities {
  257. capSet.Add(c)
  258. }
  259. for c := range resp.Node.CapMap {
  260. capSet.Add(c)
  261. }
  262. ms.lastCapSet = capSet
  263. }
  264. for _, up := range resp.UserProfiles {
  265. ms.lastUserProfile[up.ID] = up.View()
  266. }
  267. // TODO(bradfitz): clean up old user profiles? maybe not worth it.
  268. if dm := resp.DERPMap; dm != nil {
  269. ms.vlogf("netmap: new map contains DERP map")
  270. // Guard against the control server accidentally sending
  271. // a nil region definition, which at least Headscale was
  272. // observed to send.
  273. for rid, r := range dm.Regions {
  274. if r == nil {
  275. delete(dm.Regions, rid)
  276. }
  277. }
  278. // In the copy/v86 wasm environment with limited networking, if the
  279. // control plane didn't pick our DERP home for us, do it ourselves and
  280. // mark all but the lowest region as NoMeasureNoHome. For prod, this
  281. // will be Region 1, NYC, a compromise between the US and Europe. But
  282. // really the control plane should pick this. This is only a fallback.
  283. if hostinfo.IsInVM86() {
  284. numCanMeasure := 0
  285. lowest := 0
  286. for rid, r := range dm.Regions {
  287. if !r.NoMeasureNoHome {
  288. numCanMeasure++
  289. if lowest == 0 || rid < lowest {
  290. lowest = rid
  291. }
  292. }
  293. }
  294. if numCanMeasure > 1 {
  295. for rid, r := range dm.Regions {
  296. if rid != lowest {
  297. r.NoMeasureNoHome = true
  298. }
  299. }
  300. }
  301. }
  302. // Zero-valued fields in a DERPMap mean that we're not changing
  303. // anything and are using the previous value(s).
  304. if ldm := ms.lastDERPMap; ldm != nil {
  305. if dm.Regions == nil {
  306. dm.Regions = ldm.Regions
  307. dm.OmitDefaultRegions = ldm.OmitDefaultRegions
  308. }
  309. if dm.HomeParams == nil {
  310. dm.HomeParams = ldm.HomeParams
  311. } else if oldhh := ldm.HomeParams; oldhh != nil {
  312. // Propagate sub-fields of HomeParams
  313. hh := dm.HomeParams
  314. if hh.RegionScore == nil {
  315. hh.RegionScore = oldhh.RegionScore
  316. }
  317. }
  318. }
  319. ms.lastDERPMap = dm
  320. }
  321. var packetFilterChanged bool
  322. // Older way, one big blob:
  323. if pf := resp.PacketFilter; pf != nil {
  324. packetFilterChanged = true
  325. mak.Set(&ms.namedPacketFilters, "base", views.SliceOf(pf))
  326. }
  327. // Newer way, named chunks:
  328. if m := resp.PacketFilters; m != nil {
  329. packetFilterChanged = true
  330. if v, ok := m["*"]; ok && v == nil {
  331. ms.namedPacketFilters = nil
  332. }
  333. for k, v := range m {
  334. if k == "*" {
  335. continue
  336. }
  337. if v != nil {
  338. mak.Set(&ms.namedPacketFilters, k, views.SliceOf(v))
  339. } else {
  340. delete(ms.namedPacketFilters, k)
  341. }
  342. }
  343. }
  344. if packetFilterChanged {
  345. var concat []tailcfg.FilterRule
  346. for _, v := range slices.Sorted(maps.Keys(ms.namedPacketFilters)) {
  347. concat = ms.namedPacketFilters[v].AppendTo(concat)
  348. }
  349. ms.lastPacketFilterRules = views.SliceOf(concat)
  350. var err error
  351. ms.lastParsedPacketFilter, err = filter.MatchesFromFilterRules(concat)
  352. if err != nil {
  353. ms.logf("parsePacketFilter: %v", err)
  354. }
  355. }
  356. if c := resp.DNSConfig; c != nil {
  357. ms.lastDNSConfig = c
  358. }
  359. if p := resp.SSHPolicy; p != nil {
  360. ms.lastSSHPolicy = p
  361. }
  362. if v, ok := resp.CollectServices.Get(); ok {
  363. ms.collectServices = v
  364. }
  365. if resp.Domain != "" {
  366. ms.lastDomain = resp.Domain
  367. }
  368. if resp.DomainDataPlaneAuditLogID != "" {
  369. ms.lastDomainAuditLogID = resp.DomainDataPlaneAuditLogID
  370. }
  371. if resp.Health != nil {
  372. ms.lastHealth = resp.Health
  373. }
  374. if resp.DisplayMessages != nil {
  375. if v, ok := resp.DisplayMessages["*"]; ok && v == nil {
  376. ms.lastDisplayMessages = nil
  377. }
  378. for k, v := range resp.DisplayMessages {
  379. if k == "*" {
  380. continue
  381. }
  382. if v != nil {
  383. mak.Set(&ms.lastDisplayMessages, k, *v)
  384. } else {
  385. delete(ms.lastDisplayMessages, k)
  386. }
  387. }
  388. }
  389. if resp.TKAInfo != nil {
  390. ms.lastTKAInfo = resp.TKAInfo
  391. }
  392. }
  393. var (
  394. patchDERPRegion = clientmetric.NewCounter("controlclient_patch_derp")
  395. patchEndpoints = clientmetric.NewCounter("controlclient_patch_endpoints")
  396. patchCap = clientmetric.NewCounter("controlclient_patch_capver")
  397. patchKey = clientmetric.NewCounter("controlclient_patch_key")
  398. patchDiscoKey = clientmetric.NewCounter("controlclient_patch_discokey")
  399. patchOnline = clientmetric.NewCounter("controlclient_patch_online")
  400. patchLastSeen = clientmetric.NewCounter("controlclient_patch_lastseen")
  401. patchKeyExpiry = clientmetric.NewCounter("controlclient_patch_keyexpiry")
  402. patchCapMap = clientmetric.NewCounter("controlclient_patch_capmap")
  403. patchKeySignature = clientmetric.NewCounter("controlclient_patch_keysig")
  404. patchifiedPeer = clientmetric.NewCounter("controlclient_patchified_peer")
  405. patchifiedPeerEqual = clientmetric.NewCounter("controlclient_patchified_peer_equal")
  406. )
  407. // updatePeersStateFromResponseres updates ms.peers from resp.
  408. // It takes ownership of resp.
  409. func (ms *mapSession) updatePeersStateFromResponse(resp *tailcfg.MapResponse) (stats updateStats) {
  410. if ms.peers == nil {
  411. ms.peers = make(map[tailcfg.NodeID]tailcfg.NodeView)
  412. }
  413. if len(resp.Peers) > 0 {
  414. // Not delta encoded.
  415. stats.allNew = true
  416. keep := make(map[tailcfg.NodeID]bool, len(resp.Peers))
  417. for _, n := range resp.Peers {
  418. keep[n.ID] = true
  419. lenBefore := len(ms.peers)
  420. ms.peers[n.ID] = n.View()
  421. if len(ms.peers) == lenBefore {
  422. stats.changed++
  423. } else {
  424. stats.added++
  425. }
  426. }
  427. for id := range ms.peers {
  428. if !keep[id] {
  429. stats.removed++
  430. delete(ms.peers, id)
  431. }
  432. }
  433. // Peers precludes all other delta operations so just return.
  434. return
  435. }
  436. for _, id := range resp.PeersRemoved {
  437. if _, ok := ms.peers[id]; ok {
  438. delete(ms.peers, id)
  439. stats.removed++
  440. }
  441. }
  442. for _, n := range resp.PeersChanged {
  443. lenBefore := len(ms.peers)
  444. ms.peers[n.ID] = n.View()
  445. if len(ms.peers) == lenBefore {
  446. stats.changed++
  447. } else {
  448. stats.added++
  449. }
  450. }
  451. for nodeID, seen := range resp.PeerSeenChange {
  452. if vp, ok := ms.peers[nodeID]; ok {
  453. mut := vp.AsStruct()
  454. if seen {
  455. mut.LastSeen = ptr.To(clock.Now())
  456. } else {
  457. mut.LastSeen = nil
  458. }
  459. ms.peers[nodeID] = mut.View()
  460. stats.changed++
  461. }
  462. }
  463. for nodeID, online := range resp.OnlineChange {
  464. if vp, ok := ms.peers[nodeID]; ok {
  465. mut := vp.AsStruct()
  466. mut.Online = ptr.To(online)
  467. ms.peers[nodeID] = mut.View()
  468. stats.changed++
  469. }
  470. }
  471. for _, pc := range resp.PeersChangedPatch {
  472. vp, ok := ms.peers[pc.NodeID]
  473. if !ok {
  474. continue
  475. }
  476. stats.changed++
  477. mut := vp.AsStruct()
  478. if pc.DERPRegion != 0 {
  479. mut.HomeDERP = pc.DERPRegion
  480. patchDERPRegion.Add(1)
  481. }
  482. if pc.Cap != 0 {
  483. mut.Cap = pc.Cap
  484. patchCap.Add(1)
  485. }
  486. if pc.Endpoints != nil {
  487. mut.Endpoints = pc.Endpoints
  488. patchEndpoints.Add(1)
  489. }
  490. if pc.Key != nil {
  491. mut.Key = *pc.Key
  492. patchKey.Add(1)
  493. }
  494. if pc.DiscoKey != nil {
  495. mut.DiscoKey = *pc.DiscoKey
  496. patchDiscoKey.Add(1)
  497. }
  498. if v := pc.Online; v != nil {
  499. mut.Online = ptr.To(*v)
  500. patchOnline.Add(1)
  501. }
  502. if v := pc.LastSeen; v != nil {
  503. mut.LastSeen = ptr.To(*v)
  504. patchLastSeen.Add(1)
  505. }
  506. if v := pc.KeyExpiry; v != nil {
  507. mut.KeyExpiry = *v
  508. patchKeyExpiry.Add(1)
  509. }
  510. if v := pc.KeySignature; v != nil {
  511. mut.KeySignature = v
  512. patchKeySignature.Add(1)
  513. }
  514. if v := pc.CapMap; v != nil {
  515. mut.CapMap = v
  516. patchCapMap.Add(1)
  517. }
  518. ms.peers[pc.NodeID] = mut.View()
  519. }
  520. return
  521. }
  522. func (ms *mapSession) addUserProfile(nm *netmap.NetworkMap, userID tailcfg.UserID) {
  523. if userID == 0 {
  524. return
  525. }
  526. if _, dup := nm.UserProfiles[userID]; dup {
  527. // Already populated it from a previous peer.
  528. return
  529. }
  530. if up, ok := ms.lastUserProfile[userID]; ok {
  531. nm.UserProfiles[userID] = up
  532. }
  533. }
  534. var debugPatchifyPeer = envknob.RegisterBool("TS_DEBUG_PATCHIFY_PEER")
  535. // patchifyPeersChanged mutates resp to promote PeersChanged entries to PeersChangedPatch
  536. // when possible.
  537. func (ms *mapSession) patchifyPeersChanged(resp *tailcfg.MapResponse) {
  538. filtered := resp.PeersChanged[:0]
  539. for _, n := range resp.PeersChanged {
  540. if p, ok := ms.patchifyPeer(n); ok {
  541. patchifiedPeer.Add(1)
  542. if debugPatchifyPeer() {
  543. patchj, _ := json.Marshal(p)
  544. ms.logf("debug: patchifyPeer[ID=%v]: %s", n.ID, patchj)
  545. }
  546. if p != nil {
  547. resp.PeersChangedPatch = append(resp.PeersChangedPatch, p)
  548. } else {
  549. patchifiedPeerEqual.Add(1)
  550. }
  551. } else {
  552. filtered = append(filtered, n)
  553. }
  554. }
  555. resp.PeersChanged = filtered
  556. if len(resp.PeersChanged) == 0 {
  557. resp.PeersChanged = nil
  558. }
  559. }
  560. var nodeFields = sync.OnceValue(getNodeFields)
  561. // getNodeFields returns the fails of tailcfg.Node.
  562. func getNodeFields() []string {
  563. rt := reflect.TypeFor[tailcfg.Node]()
  564. ret := make([]string, rt.NumField())
  565. for i := range rt.NumField() {
  566. ret[i] = rt.Field(i).Name
  567. }
  568. return ret
  569. }
  570. // patchifyPeer returns a *tailcfg.PeerChange of the session's existing copy of
  571. // the n.ID Node to n.
  572. //
  573. // It returns ok=false if a patch can't be made, (V, ok) on a delta, or (nil,
  574. // true) if all the fields were identical (a zero change).
  575. func (ms *mapSession) patchifyPeer(n *tailcfg.Node) (_ *tailcfg.PeerChange, ok bool) {
  576. was, ok := ms.peers[n.ID]
  577. if !ok {
  578. return nil, false
  579. }
  580. return peerChangeDiff(was, n)
  581. }
  582. // peerChangeDiff returns the difference from 'was' to 'n', if possible.
  583. //
  584. // It returns (nil, true) if the fields were identical.
  585. func peerChangeDiff(was tailcfg.NodeView, n *tailcfg.Node) (_ *tailcfg.PeerChange, ok bool) {
  586. var ret *tailcfg.PeerChange
  587. pc := func() *tailcfg.PeerChange {
  588. if ret == nil {
  589. ret = new(tailcfg.PeerChange)
  590. }
  591. return ret
  592. }
  593. for _, field := range nodeFields() {
  594. switch field {
  595. default:
  596. // The whole point of using reflect in this function is to panic
  597. // here in tests if we forget to handle a new field.
  598. panic("unhandled field: " + field)
  599. case "computedHostIfDifferent", "ComputedName", "ComputedNameWithHost":
  600. // Caller's responsibility to have populated these.
  601. continue
  602. case "DataPlaneAuditLogID":
  603. // Not sent for peers.
  604. case "Capabilities":
  605. // Deprecated; see https://github.com/tailscale/tailscale/issues/11508
  606. // And it was never sent by any known control server.
  607. case "ID":
  608. if was.ID() != n.ID {
  609. return nil, false
  610. }
  611. case "StableID":
  612. if was.StableID() != n.StableID {
  613. return nil, false
  614. }
  615. case "Name":
  616. if was.Name() != n.Name {
  617. return nil, false
  618. }
  619. case "User":
  620. if was.User() != n.User {
  621. return nil, false
  622. }
  623. case "Sharer":
  624. if was.Sharer() != n.Sharer {
  625. return nil, false
  626. }
  627. case "Key":
  628. if was.Key() != n.Key {
  629. pc().Key = ptr.To(n.Key)
  630. }
  631. case "KeyExpiry":
  632. if !was.KeyExpiry().Equal(n.KeyExpiry) {
  633. pc().KeyExpiry = ptr.To(n.KeyExpiry)
  634. }
  635. case "KeySignature":
  636. if !was.KeySignature().Equal(n.KeySignature) {
  637. pc().KeySignature = slices.Clone(n.KeySignature)
  638. }
  639. case "Machine":
  640. if was.Machine() != n.Machine {
  641. return nil, false
  642. }
  643. case "DiscoKey":
  644. if was.DiscoKey() != n.DiscoKey {
  645. pc().DiscoKey = ptr.To(n.DiscoKey)
  646. }
  647. case "Addresses":
  648. if !views.SliceEqual(was.Addresses(), views.SliceOf(n.Addresses)) {
  649. return nil, false
  650. }
  651. case "AllowedIPs":
  652. if !views.SliceEqual(was.AllowedIPs(), views.SliceOf(n.AllowedIPs)) {
  653. return nil, false
  654. }
  655. case "Endpoints":
  656. if !views.SliceEqual(was.Endpoints(), views.SliceOf(n.Endpoints)) {
  657. pc().Endpoints = slices.Clone(n.Endpoints)
  658. }
  659. case "LegacyDERPString":
  660. if was.LegacyDERPString() != "" || n.LegacyDERPString != "" {
  661. panic("unexpected; caller should've already called upgradeNode")
  662. }
  663. case "HomeDERP":
  664. if was.HomeDERP() != n.HomeDERP {
  665. pc().DERPRegion = n.HomeDERP
  666. }
  667. case "Hostinfo":
  668. if !was.Hostinfo().Valid() && !n.Hostinfo.Valid() {
  669. continue
  670. }
  671. if !was.Hostinfo().Valid() || !n.Hostinfo.Valid() {
  672. return nil, false
  673. }
  674. if !was.Hostinfo().Equal(n.Hostinfo) {
  675. return nil, false
  676. }
  677. case "Created":
  678. if !was.Created().Equal(n.Created) {
  679. return nil, false
  680. }
  681. case "Cap":
  682. if was.Cap() != n.Cap {
  683. pc().Cap = n.Cap
  684. }
  685. case "CapMap":
  686. if len(n.CapMap) != was.CapMap().Len() {
  687. // If they have different lengths, they're different.
  688. if n.CapMap == nil {
  689. pc().CapMap = make(tailcfg.NodeCapMap)
  690. } else {
  691. pc().CapMap = maps.Clone(n.CapMap)
  692. }
  693. } else {
  694. // If they have the same length, check that all their keys
  695. // have the same values.
  696. for k, v := range was.CapMap().All() {
  697. nv, ok := n.CapMap[k]
  698. if !ok || !views.SliceEqual(v, views.SliceOf(nv)) {
  699. pc().CapMap = maps.Clone(n.CapMap)
  700. break
  701. }
  702. }
  703. }
  704. case "Tags":
  705. if !views.SliceEqual(was.Tags(), views.SliceOf(n.Tags)) {
  706. return nil, false
  707. }
  708. case "PrimaryRoutes":
  709. if !views.SliceEqual(was.PrimaryRoutes(), views.SliceOf(n.PrimaryRoutes)) {
  710. return nil, false
  711. }
  712. case "Online":
  713. if wasOnline, ok := was.Online().GetOk(); ok && n.Online != nil && *n.Online != wasOnline {
  714. pc().Online = ptr.To(*n.Online)
  715. }
  716. case "LastSeen":
  717. if wasSeen, ok := was.LastSeen().GetOk(); ok && n.LastSeen != nil && !wasSeen.Equal(*n.LastSeen) {
  718. pc().LastSeen = ptr.To(*n.LastSeen)
  719. }
  720. case "MachineAuthorized":
  721. if was.MachineAuthorized() != n.MachineAuthorized {
  722. return nil, false
  723. }
  724. case "UnsignedPeerAPIOnly":
  725. if was.UnsignedPeerAPIOnly() != n.UnsignedPeerAPIOnly {
  726. return nil, false
  727. }
  728. case "IsWireGuardOnly":
  729. if was.IsWireGuardOnly() != n.IsWireGuardOnly {
  730. return nil, false
  731. }
  732. case "IsJailed":
  733. if was.IsJailed() != n.IsJailed {
  734. return nil, false
  735. }
  736. case "Expired":
  737. if was.Expired() != n.Expired {
  738. return nil, false
  739. }
  740. case "SelfNodeV4MasqAddrForThisPeer":
  741. va, vb := was.SelfNodeV4MasqAddrForThisPeer(), n.SelfNodeV4MasqAddrForThisPeer
  742. if !va.Valid() && vb == nil {
  743. continue
  744. }
  745. if va, ok := va.GetOk(); !ok || vb == nil || va != *vb {
  746. return nil, false
  747. }
  748. case "SelfNodeV6MasqAddrForThisPeer":
  749. va, vb := was.SelfNodeV6MasqAddrForThisPeer(), n.SelfNodeV6MasqAddrForThisPeer
  750. if !va.Valid() && vb == nil {
  751. continue
  752. }
  753. if va, ok := va.GetOk(); !ok || vb == nil || va != *vb {
  754. return nil, false
  755. }
  756. case "ExitNodeDNSResolvers":
  757. va, vb := was.ExitNodeDNSResolvers(), views.SliceOfViews(n.ExitNodeDNSResolvers)
  758. if va.Len() != vb.Len() {
  759. return nil, false
  760. }
  761. for i := range va.Len() {
  762. if !va.At(i).Equal(vb.At(i)) {
  763. return nil, false
  764. }
  765. }
  766. }
  767. }
  768. if ret != nil {
  769. ret.NodeID = n.ID
  770. }
  771. return ret, true
  772. }
  773. func (ms *mapSession) sortedPeers() []tailcfg.NodeView {
  774. ret := slicesx.MapValues(ms.peers)
  775. slices.SortFunc(ret, func(a, b tailcfg.NodeView) int {
  776. return cmp.Compare(a.ID(), b.ID())
  777. })
  778. return ret
  779. }
  780. // netmap returns a fully populated NetworkMap from the last state seen from
  781. // a call to updateStateFromResponse, filling in omitted
  782. // information from prior MapResponse values.
  783. func (ms *mapSession) netmap() *netmap.NetworkMap {
  784. peerViews := ms.sortedPeers()
  785. var msgs map[tailcfg.DisplayMessageID]tailcfg.DisplayMessage
  786. if len(ms.lastDisplayMessages) != 0 {
  787. msgs = ms.lastDisplayMessages
  788. } else if len(ms.lastHealth) > 0 {
  789. // Convert all ms.lastHealth to the new [netmap.NetworkMap.DisplayMessages]
  790. for _, h := range ms.lastHealth {
  791. id := "control-health-" + strhash(h) // Unique ID in case there is more than one health message
  792. mak.Set(&msgs, tailcfg.DisplayMessageID(id), tailcfg.DisplayMessage{
  793. Title: "Coordination server reports an issue",
  794. Severity: tailcfg.SeverityMedium,
  795. Text: "The coordination server is reporting a health issue: " + h,
  796. })
  797. }
  798. }
  799. nm := &netmap.NetworkMap{
  800. NodeKey: ms.publicNodeKey,
  801. PrivateKey: ms.privateNodeKey,
  802. MachineKey: ms.machinePubKey,
  803. Peers: peerViews,
  804. UserProfiles: make(map[tailcfg.UserID]tailcfg.UserProfileView),
  805. Domain: ms.lastDomain,
  806. DomainAuditLogID: ms.lastDomainAuditLogID,
  807. DNS: *ms.lastDNSConfig,
  808. PacketFilter: ms.lastParsedPacketFilter,
  809. PacketFilterRules: ms.lastPacketFilterRules,
  810. SSHPolicy: ms.lastSSHPolicy,
  811. CollectServices: ms.collectServices,
  812. DERPMap: ms.lastDERPMap,
  813. DisplayMessages: msgs,
  814. TKAEnabled: ms.lastTKAInfo != nil && !ms.lastTKAInfo.Disabled,
  815. }
  816. if ms.lastTKAInfo != nil && ms.lastTKAInfo.Head != "" {
  817. if err := nm.TKAHead.UnmarshalText([]byte(ms.lastTKAInfo.Head)); err != nil {
  818. ms.logf("error unmarshalling TKAHead: %v", err)
  819. nm.TKAEnabled = false
  820. }
  821. }
  822. if node := ms.lastNode; node.Valid() {
  823. nm.SelfNode = node
  824. nm.Expiry = node.KeyExpiry()
  825. nm.Name = node.Name()
  826. nm.AllCaps = ms.lastCapSet
  827. }
  828. ms.addUserProfile(nm, nm.User())
  829. for _, peer := range peerViews {
  830. ms.addUserProfile(nm, peer.Sharer())
  831. ms.addUserProfile(nm, peer.User())
  832. }
  833. if DevKnob.ForceProxyDNS() {
  834. nm.DNS.Proxied = true
  835. }
  836. return nm
  837. }
  838. func strhash(h string) string {
  839. s := sha256.New()
  840. io.WriteString(s, h)
  841. return hex.EncodeToString(s.Sum(nil))
  842. }