map.go 22 KB

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