netmap.go 7.0 KB

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