map.go 23 KB

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