netmap.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. // Copyright (c) 2020 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 netmap contains the netmap.NetworkMap type.
  5. package netmap
  6. import (
  7. "encoding/json"
  8. "fmt"
  9. "reflect"
  10. "strings"
  11. "time"
  12. "inet.af/netaddr"
  13. "tailscale.com/tailcfg"
  14. "tailscale.com/types/key"
  15. "tailscale.com/wgengine/filter"
  16. )
  17. // NetworkMap is the current state of the world.
  18. //
  19. // The fields should all be considered read-only. They might
  20. // alias parts of previous NetworkMap values.
  21. type NetworkMap struct {
  22. // Core networking
  23. SelfNode *tailcfg.Node
  24. NodeKey key.NodePublic
  25. PrivateKey key.NodePrivate
  26. Expiry time.Time
  27. // Name is the DNS name assigned to this node.
  28. Name string
  29. Addresses []netaddr.IPPrefix // same as tailcfg.Node.Addresses (IP addresses of this Node directly)
  30. LocalPort uint16 // used for debugging
  31. MachineStatus tailcfg.MachineStatus
  32. MachineKey key.MachinePublic
  33. Peers []*tailcfg.Node // sorted by Node.ID
  34. DNS tailcfg.DNSConfig
  35. Hostinfo tailcfg.Hostinfo
  36. PacketFilter []filter.Match
  37. // CollectServices reports whether this node's Tailnet has
  38. // requested that info about services be included in HostInfo.
  39. // If set, Hostinfo.ShieldsUp blocks services collection; that
  40. // takes precedence over this field.
  41. CollectServices bool
  42. // DERPMap is the last DERP server map received. It's reused
  43. // between updates and should not be modified.
  44. DERPMap *tailcfg.DERPMap
  45. // Debug knobs from control server for debug or feature gating.
  46. Debug *tailcfg.Debug
  47. // ControlHealth are the list of health check problems for this
  48. // node from the perspective of the control plane.
  49. // If empty, there are no known problems from the control plane's
  50. // point of view, but the node might know about its own health
  51. // check problems.
  52. ControlHealth []string
  53. // ACLs
  54. User tailcfg.UserID
  55. Domain string
  56. UserProfiles map[tailcfg.UserID]tailcfg.UserProfile
  57. }
  58. // MagicDNSSuffix returns the domain's MagicDNS suffix (even if
  59. // MagicDNS isn't necessarily in use).
  60. //
  61. // It will neither start nor end with a period.
  62. func (nm *NetworkMap) MagicDNSSuffix() string {
  63. name := strings.Trim(nm.Name, ".")
  64. if i := strings.Index(name, "."); i != -1 {
  65. name = name[i+1:]
  66. }
  67. return name
  68. }
  69. func (nm *NetworkMap) String() string {
  70. return nm.Concise()
  71. }
  72. func (nm *NetworkMap) Concise() string {
  73. buf := new(strings.Builder)
  74. nm.printConciseHeader(buf)
  75. for _, p := range nm.Peers {
  76. printPeerConcise(buf, p)
  77. }
  78. return buf.String()
  79. }
  80. func (nm *NetworkMap) VeryConcise() string {
  81. buf := new(strings.Builder)
  82. nm.printConciseHeader(buf)
  83. return buf.String()
  84. }
  85. // printConciseHeader prints a concise header line representing nm to buf.
  86. //
  87. // If this function is changed to access different fields of nm, keep
  88. // in equalConciseHeader in sync.
  89. func (nm *NetworkMap) printConciseHeader(buf *strings.Builder) {
  90. fmt.Fprintf(buf, "netmap: self: %v auth=%v",
  91. nm.NodeKey.ShortString(), nm.MachineStatus)
  92. login := nm.UserProfiles[nm.User].LoginName
  93. if login == "" {
  94. if nm.User.IsZero() {
  95. login = "?"
  96. } else {
  97. login = fmt.Sprint(nm.User)
  98. }
  99. }
  100. fmt.Fprintf(buf, " u=%s", login)
  101. if nm.LocalPort != 0 {
  102. fmt.Fprintf(buf, " port=%v", nm.LocalPort)
  103. }
  104. if nm.Debug != nil {
  105. j, _ := json.Marshal(nm.Debug)
  106. fmt.Fprintf(buf, " debug=%s", j)
  107. }
  108. fmt.Fprintf(buf, " %v", nm.Addresses)
  109. buf.WriteByte('\n')
  110. }
  111. // equalConciseHeader reports whether a and b are equal for the fields
  112. // used by printConciseHeader.
  113. func (a *NetworkMap) equalConciseHeader(b *NetworkMap) bool {
  114. if a.NodeKey != b.NodeKey ||
  115. a.MachineStatus != b.MachineStatus ||
  116. a.LocalPort != b.LocalPort ||
  117. a.User != b.User ||
  118. len(a.Addresses) != len(b.Addresses) {
  119. return false
  120. }
  121. for i, a := range a.Addresses {
  122. if b.Addresses[i] != a {
  123. return false
  124. }
  125. }
  126. return (a.Debug == nil && b.Debug == nil) || reflect.DeepEqual(a.Debug, b.Debug)
  127. }
  128. // printPeerConcise appends to buf a line representing the peer p.
  129. //
  130. // If this function is changed to access different fields of p, keep
  131. // in nodeConciseEqual in sync.
  132. func printPeerConcise(buf *strings.Builder, p *tailcfg.Node) {
  133. aip := make([]string, len(p.AllowedIPs))
  134. for i, a := range p.AllowedIPs {
  135. s := strings.TrimSuffix(fmt.Sprint(a), "/32")
  136. aip[i] = s
  137. }
  138. ep := make([]string, len(p.Endpoints))
  139. for i, e := range p.Endpoints {
  140. // Align vertically on the ':' between IP and port
  141. colon := strings.IndexByte(e, ':')
  142. spaces := 0
  143. for colon > 0 && len(e)+spaces-colon < 6 {
  144. spaces++
  145. colon--
  146. }
  147. ep[i] = fmt.Sprintf("%21v", e+strings.Repeat(" ", spaces))
  148. }
  149. derp := p.DERP
  150. const derpPrefix = "127.3.3.40:"
  151. if strings.HasPrefix(derp, derpPrefix) {
  152. derp = "D" + derp[len(derpPrefix):]
  153. }
  154. var discoShort string
  155. if !p.DiscoKey.IsZero() {
  156. discoShort = p.DiscoKey.ShortString() + " "
  157. }
  158. // Most of the time, aip is just one element, so format the
  159. // table to look good in that case. This will also make multi-
  160. // subnet nodes stand out visually.
  161. fmt.Fprintf(buf, " %v %s%-2v %-15v : %v\n",
  162. p.Key.ShortString(),
  163. discoShort,
  164. derp,
  165. strings.Join(aip, " "),
  166. strings.Join(ep, " "))
  167. }
  168. // nodeConciseEqual reports whether a and b are equal for the fields accessed by printPeerConcise.
  169. func nodeConciseEqual(a, b *tailcfg.Node) bool {
  170. return a.Key == b.Key &&
  171. a.DERP == b.DERP &&
  172. a.DiscoKey == b.DiscoKey &&
  173. eqCIDRsIgnoreNil(a.AllowedIPs, b.AllowedIPs) &&
  174. eqStringsIgnoreNil(a.Endpoints, b.Endpoints)
  175. }
  176. func (b *NetworkMap) ConciseDiffFrom(a *NetworkMap) string {
  177. var diff strings.Builder
  178. // See if header (non-peers, "bare") part of the network map changed.
  179. // If so, print its diff lines first.
  180. if !a.equalConciseHeader(b) {
  181. diff.WriteByte('-')
  182. a.printConciseHeader(&diff)
  183. diff.WriteByte('+')
  184. b.printConciseHeader(&diff)
  185. }
  186. aps, bps := a.Peers, b.Peers
  187. for len(aps) > 0 && len(bps) > 0 {
  188. pa, pb := aps[0], bps[0]
  189. switch {
  190. case pa.ID == pb.ID:
  191. if !nodeConciseEqual(pa, pb) {
  192. diff.WriteByte('-')
  193. printPeerConcise(&diff, pa)
  194. diff.WriteByte('+')
  195. printPeerConcise(&diff, pb)
  196. }
  197. aps, bps = aps[1:], bps[1:]
  198. case pa.ID > pb.ID:
  199. // New peer in b.
  200. diff.WriteByte('+')
  201. printPeerConcise(&diff, pb)
  202. bps = bps[1:]
  203. case pb.ID > pa.ID:
  204. // Deleted peer in b.
  205. diff.WriteByte('-')
  206. printPeerConcise(&diff, pa)
  207. aps = aps[1:]
  208. }
  209. }
  210. for _, pa := range aps {
  211. diff.WriteByte('-')
  212. printPeerConcise(&diff, pa)
  213. }
  214. for _, pb := range bps {
  215. diff.WriteByte('+')
  216. printPeerConcise(&diff, pb)
  217. }
  218. return diff.String()
  219. }
  220. func (nm *NetworkMap) JSON() string {
  221. b, err := json.MarshalIndent(*nm, "", " ")
  222. if err != nil {
  223. return fmt.Sprintf("[json error: %v]", err)
  224. }
  225. return string(b)
  226. }
  227. // WGConfigFlags is a bitmask of flags to control the behavior of the
  228. // wireguard configuration generation done by NetMap.WGCfg.
  229. type WGConfigFlags int
  230. const (
  231. AllowSingleHosts WGConfigFlags = 1 << iota
  232. AllowSubnetRoutes
  233. )
  234. // eqStringsIgnoreNil reports whether a and b have the same length and
  235. // contents, but ignore whether a or b are nil.
  236. func eqStringsIgnoreNil(a, b []string) bool {
  237. if len(a) != len(b) {
  238. return false
  239. }
  240. for i, v := range a {
  241. if v != b[i] {
  242. return false
  243. }
  244. }
  245. return true
  246. }
  247. // eqCIDRsIgnoreNil reports whether a and b have the same length and
  248. // contents, but ignore whether a or b are nil.
  249. func eqCIDRsIgnoreNil(a, b []netaddr.IPPrefix) bool {
  250. if len(a) != len(b) {
  251. return false
  252. }
  253. for i, v := range a {
  254. if v != b[i] {
  255. return false
  256. }
  257. }
  258. return true
  259. }