2
0

map.go 23 KB

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