map.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. // Copyright (c) 2021 Tailscale Inc & AUTHORS All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package controlclient
  5. import (
  6. "fmt"
  7. "log"
  8. "net/netip"
  9. "sort"
  10. "tailscale.com/envknob"
  11. "tailscale.com/tailcfg"
  12. "tailscale.com/types/key"
  13. "tailscale.com/types/logger"
  14. "tailscale.com/types/netmap"
  15. "tailscale.com/types/opt"
  16. "tailscale.com/wgengine/filter"
  17. )
  18. // mapSession holds the state over a long-polled "map" request to the
  19. // control plane.
  20. //
  21. // It accepts incremental tailcfg.MapResponse values to
  22. // netMapForResponse and returns fully inflated NetworkMaps, filling
  23. // in the omitted data implicit from prior MapResponse values from
  24. // within the same session (the same long-poll HTTP response to the
  25. // one MapRequest).
  26. type mapSession struct {
  27. // Immutable fields.
  28. privateNodeKey key.NodePrivate
  29. logf logger.Logf
  30. vlogf logger.Logf
  31. machinePubKey key.MachinePublic
  32. keepSharerAndUserSplit bool // see Options.KeepSharerAndUserSplit
  33. // Fields storing state over the the coards of multiple MapResponses.
  34. lastNode *tailcfg.Node
  35. lastDNSConfig *tailcfg.DNSConfig
  36. lastDERPMap *tailcfg.DERPMap
  37. lastUserProfile map[tailcfg.UserID]tailcfg.UserProfile
  38. lastParsedPacketFilter []filter.Match
  39. lastSSHPolicy *tailcfg.SSHPolicy
  40. collectServices bool
  41. previousPeers []*tailcfg.Node // for delta-purposes
  42. lastDomain string
  43. lastHealth []string
  44. lastPopBrowserURL string
  45. stickyDebug tailcfg.Debug // accumulated opt.Bool values
  46. // netMapBuilding is non-nil during a netmapForResponse call,
  47. // containing the value to be returned, once fully populated.
  48. netMapBuilding *netmap.NetworkMap
  49. }
  50. func newMapSession(privateNodeKey key.NodePrivate) *mapSession {
  51. ms := &mapSession{
  52. privateNodeKey: privateNodeKey,
  53. logf: logger.Discard,
  54. vlogf: logger.Discard,
  55. lastDNSConfig: new(tailcfg.DNSConfig),
  56. lastUserProfile: map[tailcfg.UserID]tailcfg.UserProfile{},
  57. }
  58. return ms
  59. }
  60. func (ms *mapSession) addUserProfile(userID tailcfg.UserID) {
  61. nm := ms.netMapBuilding
  62. if _, dup := nm.UserProfiles[userID]; dup {
  63. // Already populated it from a previous peer.
  64. return
  65. }
  66. if up, ok := ms.lastUserProfile[userID]; ok {
  67. nm.UserProfiles[userID] = up
  68. }
  69. }
  70. // netmapForResponse returns a fully populated NetworkMap from a full
  71. // or incremental MapResponse within the session, filling in omitted
  72. // information from prior MapResponse values.
  73. func (ms *mapSession) netmapForResponse(resp *tailcfg.MapResponse) *netmap.NetworkMap {
  74. undeltaPeers(resp, ms.previousPeers)
  75. ms.previousPeers = cloneNodes(resp.Peers) // defensive/lazy clone, since this escapes to who knows where
  76. for _, up := range resp.UserProfiles {
  77. ms.lastUserProfile[up.ID] = up
  78. }
  79. if resp.DERPMap != nil {
  80. ms.vlogf("netmap: new map contains DERP map")
  81. ms.lastDERPMap = resp.DERPMap
  82. }
  83. if pf := resp.PacketFilter; pf != nil {
  84. var err error
  85. ms.lastParsedPacketFilter, err = filter.MatchesFromFilterRules(pf)
  86. if err != nil {
  87. ms.logf("parsePacketFilter: %v", err)
  88. }
  89. }
  90. if c := resp.DNSConfig; c != nil {
  91. ms.lastDNSConfig = c
  92. }
  93. if p := resp.SSHPolicy; p != nil {
  94. ms.lastSSHPolicy = p
  95. }
  96. if v, ok := resp.CollectServices.Get(); ok {
  97. ms.collectServices = v
  98. }
  99. if resp.Domain != "" {
  100. ms.lastDomain = resp.Domain
  101. }
  102. if resp.Health != nil {
  103. ms.lastHealth = resp.Health
  104. }
  105. debug := resp.Debug
  106. if debug != nil {
  107. if debug.RandomizeClientPort {
  108. debug.SetRandomizeClientPort.Set(true)
  109. }
  110. if debug.ForceBackgroundSTUN {
  111. debug.SetForceBackgroundSTUN.Set(true)
  112. }
  113. copyDebugOptBools(&ms.stickyDebug, debug)
  114. } else if ms.stickyDebug != (tailcfg.Debug{}) {
  115. debug = new(tailcfg.Debug)
  116. }
  117. if debug != nil {
  118. copyDebugOptBools(debug, &ms.stickyDebug)
  119. if !debug.ForceBackgroundSTUN {
  120. debug.ForceBackgroundSTUN, _ = ms.stickyDebug.SetForceBackgroundSTUN.Get()
  121. }
  122. if !debug.RandomizeClientPort {
  123. debug.RandomizeClientPort, _ = ms.stickyDebug.SetRandomizeClientPort.Get()
  124. }
  125. }
  126. nm := &netmap.NetworkMap{
  127. NodeKey: ms.privateNodeKey.Public(),
  128. PrivateKey: ms.privateNodeKey,
  129. MachineKey: ms.machinePubKey,
  130. Peers: resp.Peers,
  131. UserProfiles: make(map[tailcfg.UserID]tailcfg.UserProfile),
  132. Domain: ms.lastDomain,
  133. DNS: *ms.lastDNSConfig,
  134. PacketFilter: ms.lastParsedPacketFilter,
  135. SSHPolicy: ms.lastSSHPolicy,
  136. CollectServices: ms.collectServices,
  137. DERPMap: ms.lastDERPMap,
  138. Debug: debug,
  139. ControlHealth: ms.lastHealth,
  140. }
  141. ms.netMapBuilding = nm
  142. if resp.Node != nil {
  143. ms.lastNode = resp.Node
  144. }
  145. if node := ms.lastNode.Clone(); node != nil {
  146. nm.SelfNode = node
  147. nm.Expiry = node.KeyExpiry
  148. nm.Name = node.Name
  149. nm.Addresses = filterSelfAddresses(node.Addresses)
  150. nm.User = node.User
  151. if node.Hostinfo.Valid() {
  152. nm.Hostinfo = *node.Hostinfo.AsStruct()
  153. }
  154. if node.MachineAuthorized {
  155. nm.MachineStatus = tailcfg.MachineAuthorized
  156. } else {
  157. nm.MachineStatus = tailcfg.MachineUnauthorized
  158. }
  159. }
  160. ms.addUserProfile(nm.User)
  161. magicDNSSuffix := nm.MagicDNSSuffix()
  162. if nm.SelfNode != nil {
  163. nm.SelfNode.InitDisplayNames(magicDNSSuffix)
  164. }
  165. for _, peer := range resp.Peers {
  166. peer.InitDisplayNames(magicDNSSuffix)
  167. if !peer.Sharer.IsZero() {
  168. if ms.keepSharerAndUserSplit {
  169. ms.addUserProfile(peer.Sharer)
  170. } else {
  171. peer.User = peer.Sharer
  172. }
  173. }
  174. ms.addUserProfile(peer.User)
  175. }
  176. if DevKnob.ForceProxyDNS() {
  177. nm.DNS.Proxied = true
  178. }
  179. ms.netMapBuilding = nil
  180. return nm
  181. }
  182. // undeltaPeers updates mapRes.Peers to be complete based on the
  183. // provided previous peer list and the PeersRemoved and PeersChanged
  184. // fields in mapRes, as well as the PeerSeenChange and OnlineChange
  185. // maps.
  186. //
  187. // It then also nils out the delta fields.
  188. func undeltaPeers(mapRes *tailcfg.MapResponse, prev []*tailcfg.Node) {
  189. if len(mapRes.Peers) > 0 {
  190. // Not delta encoded.
  191. if !nodesSorted(mapRes.Peers) {
  192. log.Printf("netmap: undeltaPeers: MapResponse.Peers not sorted; sorting")
  193. sortNodes(mapRes.Peers)
  194. }
  195. return
  196. }
  197. var removed map[tailcfg.NodeID]bool
  198. if pr := mapRes.PeersRemoved; len(pr) > 0 {
  199. removed = make(map[tailcfg.NodeID]bool, len(pr))
  200. for _, id := range pr {
  201. removed[id] = true
  202. }
  203. }
  204. changed := mapRes.PeersChanged
  205. if !nodesSorted(changed) {
  206. log.Printf("netmap: undeltaPeers: MapResponse.PeersChanged not sorted; sorting")
  207. sortNodes(changed)
  208. }
  209. if !nodesSorted(prev) {
  210. // Internal error (unrelated to the network) if we get here.
  211. log.Printf("netmap: undeltaPeers: [unexpected] prev not sorted; sorting")
  212. sortNodes(prev)
  213. }
  214. newFull := prev
  215. if len(removed) > 0 || len(changed) > 0 {
  216. newFull = make([]*tailcfg.Node, 0, len(prev)-len(removed))
  217. for len(prev) > 0 && len(changed) > 0 {
  218. pID := prev[0].ID
  219. cID := changed[0].ID
  220. if removed[pID] {
  221. prev = prev[1:]
  222. continue
  223. }
  224. switch {
  225. case pID < cID:
  226. newFull = append(newFull, prev[0])
  227. prev = prev[1:]
  228. case pID == cID:
  229. newFull = append(newFull, changed[0])
  230. prev, changed = prev[1:], changed[1:]
  231. case cID < pID:
  232. newFull = append(newFull, changed[0])
  233. changed = changed[1:]
  234. }
  235. }
  236. newFull = append(newFull, changed...)
  237. for _, n := range prev {
  238. if !removed[n.ID] {
  239. newFull = append(newFull, n)
  240. }
  241. }
  242. sortNodes(newFull)
  243. }
  244. if len(mapRes.PeerSeenChange) != 0 || len(mapRes.OnlineChange) != 0 || len(mapRes.PeersChangedPatch) != 0 {
  245. peerByID := make(map[tailcfg.NodeID]*tailcfg.Node, len(newFull))
  246. for _, n := range newFull {
  247. peerByID[n.ID] = n
  248. }
  249. now := clockNow()
  250. for nodeID, seen := range mapRes.PeerSeenChange {
  251. if n, ok := peerByID[nodeID]; ok {
  252. if seen {
  253. n.LastSeen = &now
  254. } else {
  255. n.LastSeen = nil
  256. }
  257. }
  258. }
  259. for nodeID, online := range mapRes.OnlineChange {
  260. if n, ok := peerByID[nodeID]; ok {
  261. online := online
  262. n.Online = &online
  263. }
  264. }
  265. for _, ec := range mapRes.PeersChangedPatch {
  266. if n, ok := peerByID[ec.NodeID]; ok {
  267. if ec.DERPRegion != 0 {
  268. n.DERP = fmt.Sprintf("%s:%v", tailcfg.DerpMagicIP, ec.DERPRegion)
  269. }
  270. if ec.Endpoints != nil {
  271. n.Endpoints = ec.Endpoints
  272. }
  273. if ec.Key != nil {
  274. n.Key = *ec.Key
  275. }
  276. if ec.DiscoKey != nil {
  277. n.DiscoKey = *ec.DiscoKey
  278. }
  279. if v := ec.Online; v != nil {
  280. n.Online = ptrCopy(v)
  281. }
  282. if v := ec.LastSeen; v != nil {
  283. n.LastSeen = ptrCopy(v)
  284. }
  285. if v := ec.KeyExpiry; v != nil {
  286. n.KeyExpiry = *v
  287. }
  288. if v := ec.Capabilities; v != nil {
  289. n.Capabilities = *v
  290. }
  291. if v := ec.KeySignature; v != nil {
  292. n.KeySignature = v
  293. }
  294. }
  295. }
  296. }
  297. mapRes.Peers = newFull
  298. mapRes.PeersChanged = nil
  299. mapRes.PeersRemoved = nil
  300. }
  301. // ptrCopy returns a pointer to a newly allocated shallow copy of *v.
  302. func ptrCopy[T any](v *T) *T {
  303. if v == nil {
  304. return nil
  305. }
  306. ret := new(T)
  307. *ret = *v
  308. return ret
  309. }
  310. func nodesSorted(v []*tailcfg.Node) bool {
  311. for i, n := range v {
  312. if i > 0 && n.ID <= v[i-1].ID {
  313. return false
  314. }
  315. }
  316. return true
  317. }
  318. func sortNodes(v []*tailcfg.Node) {
  319. sort.Slice(v, func(i, j int) bool { return v[i].ID < v[j].ID })
  320. }
  321. func cloneNodes(v1 []*tailcfg.Node) []*tailcfg.Node {
  322. if v1 == nil {
  323. return nil
  324. }
  325. v2 := make([]*tailcfg.Node, len(v1))
  326. for i, n := range v1 {
  327. v2[i] = n.Clone()
  328. }
  329. return v2
  330. }
  331. var debugSelfIPv6Only = envknob.RegisterBool("TS_DEBUG_SELF_V6_ONLY")
  332. func filterSelfAddresses(in []netip.Prefix) (ret []netip.Prefix) {
  333. switch {
  334. default:
  335. return in
  336. case debugSelfIPv6Only():
  337. for _, a := range in {
  338. if a.Addr().Is6() {
  339. ret = append(ret, a)
  340. }
  341. }
  342. return ret
  343. }
  344. }
  345. func copyDebugOptBools(dst, src *tailcfg.Debug) {
  346. copy := func(v *opt.Bool, s opt.Bool) {
  347. if s != "" {
  348. *v = s
  349. }
  350. }
  351. copy(&dst.DERPRoute, src.DERPRoute)
  352. copy(&dst.DisableSubnetsIfPAC, src.DisableSubnetsIfPAC)
  353. copy(&dst.DisableUPnP, src.DisableUPnP)
  354. copy(&dst.OneCGNATRoute, src.OneCGNATRoute)
  355. copy(&dst.SetForceBackgroundSTUN, src.SetForceBackgroundSTUN)
  356. copy(&dst.SetRandomizeClientPort, src.SetRandomizeClientPort)
  357. copy(&dst.TrimWGConfig, src.TrimWGConfig)
  358. }