netmap.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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 is the current Tailnet name.
  56. Domain string
  57. UserProfiles map[tailcfg.UserID]tailcfg.UserProfile
  58. }
  59. // MagicDNSSuffix returns the domain's MagicDNS suffix (even if
  60. // MagicDNS isn't necessarily in use).
  61. //
  62. // It will neither start nor end with a period.
  63. func (nm *NetworkMap) MagicDNSSuffix() string {
  64. name := strings.Trim(nm.Name, ".")
  65. if i := strings.Index(name, "."); i != -1 {
  66. name = name[i+1:]
  67. }
  68. return name
  69. }
  70. func (nm *NetworkMap) String() string {
  71. return nm.Concise()
  72. }
  73. func (nm *NetworkMap) Concise() string {
  74. buf := new(strings.Builder)
  75. nm.printConciseHeader(buf)
  76. for _, p := range nm.Peers {
  77. printPeerConcise(buf, p)
  78. }
  79. return buf.String()
  80. }
  81. func (nm *NetworkMap) VeryConcise() string {
  82. buf := new(strings.Builder)
  83. nm.printConciseHeader(buf)
  84. return buf.String()
  85. }
  86. // printConciseHeader prints a concise header line representing nm to buf.
  87. //
  88. // If this function is changed to access different fields of nm, keep
  89. // in equalConciseHeader in sync.
  90. func (nm *NetworkMap) printConciseHeader(buf *strings.Builder) {
  91. fmt.Fprintf(buf, "netmap: self: %v auth=%v",
  92. nm.NodeKey.ShortString(), nm.MachineStatus)
  93. login := nm.UserProfiles[nm.User].LoginName
  94. if login == "" {
  95. if nm.User.IsZero() {
  96. login = "?"
  97. } else {
  98. login = fmt.Sprint(nm.User)
  99. }
  100. }
  101. fmt.Fprintf(buf, " u=%s", login)
  102. if nm.LocalPort != 0 {
  103. fmt.Fprintf(buf, " port=%v", nm.LocalPort)
  104. }
  105. if nm.Debug != nil {
  106. j, _ := json.Marshal(nm.Debug)
  107. fmt.Fprintf(buf, " debug=%s", j)
  108. }
  109. fmt.Fprintf(buf, " %v", nm.Addresses)
  110. buf.WriteByte('\n')
  111. }
  112. // equalConciseHeader reports whether a and b are equal for the fields
  113. // used by printConciseHeader.
  114. func (a *NetworkMap) equalConciseHeader(b *NetworkMap) bool {
  115. if a.NodeKey != b.NodeKey ||
  116. a.MachineStatus != b.MachineStatus ||
  117. a.LocalPort != b.LocalPort ||
  118. a.User != b.User ||
  119. len(a.Addresses) != len(b.Addresses) {
  120. return false
  121. }
  122. for i, a := range a.Addresses {
  123. if b.Addresses[i] != a {
  124. return false
  125. }
  126. }
  127. return (a.Debug == nil && b.Debug == nil) || reflect.DeepEqual(a.Debug, b.Debug)
  128. }
  129. // printPeerConcise appends to buf a line representing the peer p.
  130. //
  131. // If this function is changed to access different fields of p, keep
  132. // in nodeConciseEqual in sync.
  133. func printPeerConcise(buf *strings.Builder, p *tailcfg.Node) {
  134. aip := make([]string, len(p.AllowedIPs))
  135. for i, a := range p.AllowedIPs {
  136. s := strings.TrimSuffix(fmt.Sprint(a), "/32")
  137. aip[i] = s
  138. }
  139. ep := make([]string, len(p.Endpoints))
  140. for i, e := range p.Endpoints {
  141. // Align vertically on the ':' between IP and port
  142. colon := strings.IndexByte(e, ':')
  143. spaces := 0
  144. for colon > 0 && len(e)+spaces-colon < 6 {
  145. spaces++
  146. colon--
  147. }
  148. ep[i] = fmt.Sprintf("%21v", e+strings.Repeat(" ", spaces))
  149. }
  150. derp := p.DERP
  151. const derpPrefix = "127.3.3.40:"
  152. if strings.HasPrefix(derp, derpPrefix) {
  153. derp = "D" + derp[len(derpPrefix):]
  154. }
  155. var discoShort string
  156. if !p.DiscoKey.IsZero() {
  157. discoShort = p.DiscoKey.ShortString() + " "
  158. }
  159. // Most of the time, aip is just one element, so format the
  160. // table to look good in that case. This will also make multi-
  161. // subnet nodes stand out visually.
  162. fmt.Fprintf(buf, " %v %s%-2v %-15v : %v\n",
  163. p.Key.ShortString(),
  164. discoShort,
  165. derp,
  166. strings.Join(aip, " "),
  167. strings.Join(ep, " "))
  168. }
  169. // nodeConciseEqual reports whether a and b are equal for the fields accessed by printPeerConcise.
  170. func nodeConciseEqual(a, b *tailcfg.Node) bool {
  171. return a.Key == b.Key &&
  172. a.DERP == b.DERP &&
  173. a.DiscoKey == b.DiscoKey &&
  174. eqCIDRsIgnoreNil(a.AllowedIPs, b.AllowedIPs) &&
  175. eqStringsIgnoreNil(a.Endpoints, b.Endpoints)
  176. }
  177. func (b *NetworkMap) ConciseDiffFrom(a *NetworkMap) string {
  178. var diff strings.Builder
  179. // See if header (non-peers, "bare") part of the network map changed.
  180. // If so, print its diff lines first.
  181. if !a.equalConciseHeader(b) {
  182. diff.WriteByte('-')
  183. a.printConciseHeader(&diff)
  184. diff.WriteByte('+')
  185. b.printConciseHeader(&diff)
  186. }
  187. aps, bps := a.Peers, b.Peers
  188. for len(aps) > 0 && len(bps) > 0 {
  189. pa, pb := aps[0], bps[0]
  190. switch {
  191. case pa.ID == pb.ID:
  192. if !nodeConciseEqual(pa, pb) {
  193. diff.WriteByte('-')
  194. printPeerConcise(&diff, pa)
  195. diff.WriteByte('+')
  196. printPeerConcise(&diff, pb)
  197. }
  198. aps, bps = aps[1:], bps[1:]
  199. case pa.ID > pb.ID:
  200. // New peer in b.
  201. diff.WriteByte('+')
  202. printPeerConcise(&diff, pb)
  203. bps = bps[1:]
  204. case pb.ID > pa.ID:
  205. // Deleted peer in b.
  206. diff.WriteByte('-')
  207. printPeerConcise(&diff, pa)
  208. aps = aps[1:]
  209. }
  210. }
  211. for _, pa := range aps {
  212. diff.WriteByte('-')
  213. printPeerConcise(&diff, pa)
  214. }
  215. for _, pb := range bps {
  216. diff.WriteByte('+')
  217. printPeerConcise(&diff, pb)
  218. }
  219. return diff.String()
  220. }
  221. func (nm *NetworkMap) JSON() string {
  222. b, err := json.MarshalIndent(*nm, "", " ")
  223. if err != nil {
  224. return fmt.Sprintf("[json error: %v]", err)
  225. }
  226. return string(b)
  227. }
  228. // WGConfigFlags is a bitmask of flags to control the behavior of the
  229. // wireguard configuration generation done by NetMap.WGCfg.
  230. type WGConfigFlags int
  231. const (
  232. AllowSingleHosts WGConfigFlags = 1 << iota
  233. AllowSubnetRoutes
  234. )
  235. // eqStringsIgnoreNil reports whether a and b have the same length and
  236. // contents, but ignore whether a or b are nil.
  237. func eqStringsIgnoreNil(a, b []string) bool {
  238. if len(a) != len(b) {
  239. return false
  240. }
  241. for i, v := range a {
  242. if v != b[i] {
  243. return false
  244. }
  245. }
  246. return true
  247. }
  248. // eqCIDRsIgnoreNil reports whether a and b have the same length and
  249. // contents, but ignore whether a or b are nil.
  250. func eqCIDRsIgnoreNil(a, b []netaddr.IPPrefix) bool {
  251. if len(a) != len(b) {
  252. return false
  253. }
  254. for i, v := range a {
  255. if v != b[i] {
  256. return false
  257. }
  258. }
  259. return true
  260. }