direct.go 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package controlclient
  4. import (
  5. "bufio"
  6. "bytes"
  7. "context"
  8. "crypto/ed25519"
  9. "encoding/base64"
  10. "encoding/binary"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "log"
  16. "net/http"
  17. "net/http/httptest"
  18. "net/netip"
  19. "net/url"
  20. "os"
  21. "reflect"
  22. "runtime"
  23. "slices"
  24. "strings"
  25. "sync"
  26. "time"
  27. "go4.org/mem"
  28. "tailscale.com/control/controlknobs"
  29. "tailscale.com/envknob"
  30. "tailscale.com/health"
  31. "tailscale.com/hostinfo"
  32. "tailscale.com/ipn/ipnstate"
  33. "tailscale.com/logtail"
  34. "tailscale.com/net/dnscache"
  35. "tailscale.com/net/dnsfallback"
  36. "tailscale.com/net/interfaces"
  37. "tailscale.com/net/netmon"
  38. "tailscale.com/net/netutil"
  39. "tailscale.com/net/tlsdial"
  40. "tailscale.com/net/tsdial"
  41. "tailscale.com/net/tshttpproxy"
  42. "tailscale.com/tailcfg"
  43. "tailscale.com/tka"
  44. "tailscale.com/tstime"
  45. "tailscale.com/types/key"
  46. "tailscale.com/types/logger"
  47. "tailscale.com/types/netmap"
  48. "tailscale.com/types/persist"
  49. "tailscale.com/types/ptr"
  50. "tailscale.com/types/tkatype"
  51. "tailscale.com/util/clientmetric"
  52. "tailscale.com/util/multierr"
  53. "tailscale.com/util/singleflight"
  54. "tailscale.com/util/syspolicy"
  55. "tailscale.com/util/systemd"
  56. "tailscale.com/util/zstdframe"
  57. )
  58. // Direct is the client that connects to a tailcontrol server for a node.
  59. type Direct struct {
  60. httpc *http.Client // HTTP client used to talk to tailcontrol
  61. dialer *tsdial.Dialer
  62. dnsCache *dnscache.Resolver
  63. controlKnobs *controlknobs.Knobs // always non-nil
  64. serverURL string // URL of the tailcontrol server
  65. clock tstime.Clock
  66. logf logger.Logf
  67. netMon *netmon.Monitor // or nil
  68. discoPubKey key.DiscoPublic
  69. getMachinePrivKey func() (key.MachinePrivate, error)
  70. debugFlags []string
  71. skipIPForwardingCheck bool
  72. pinger Pinger
  73. popBrowser func(url string) // or nil
  74. c2nHandler http.Handler // or nil
  75. onClientVersion func(*tailcfg.ClientVersion) // or nil
  76. onControlTime func(time.Time) // or nil
  77. onTailnetDefaultAutoUpdate func(bool) // or nil
  78. dialPlan ControlDialPlanner // can be nil
  79. mu sync.Mutex // mutex guards the following fields
  80. serverLegacyKey key.MachinePublic // original ("legacy") nacl crypto_box-based public key; only used for signRegisterRequest on Windows now
  81. serverNoiseKey key.MachinePublic
  82. sfGroup singleflight.Group[struct{}, *NoiseClient] // protects noiseClient creation.
  83. noiseClient *NoiseClient
  84. persist persist.PersistView
  85. authKey string
  86. tryingNewKey key.NodePrivate
  87. expiry time.Time // or zero value if none/unknown
  88. hostinfo *tailcfg.Hostinfo // always non-nil
  89. netinfo *tailcfg.NetInfo
  90. endpoints []tailcfg.Endpoint
  91. tkaHead string
  92. lastPingURL string // last PingRequest.URL received, for dup suppression
  93. }
  94. // Observer is implemented by users of the control client (such as LocalBackend)
  95. // to get notified of changes in the control client's status.
  96. type Observer interface {
  97. // SetControlClientStatus is called when the client has a new status to
  98. // report. The Client is provided to allow the Observer to track which
  99. // Client is reporting the status, allowing it to ignore stale status
  100. // reports from previous Clients.
  101. SetControlClientStatus(Client, Status)
  102. }
  103. type Options struct {
  104. Persist persist.Persist // initial persistent data
  105. GetMachinePrivateKey func() (key.MachinePrivate, error) // returns the machine key to use
  106. ServerURL string // URL of the tailcontrol server
  107. AuthKey string // optional node auth key for auto registration
  108. Clock tstime.Clock
  109. Hostinfo *tailcfg.Hostinfo // non-nil passes ownership, nil means to use default using os.Hostname, etc
  110. DiscoPublicKey key.DiscoPublic
  111. Logf logger.Logf
  112. HTTPTestClient *http.Client // optional HTTP client to use (for tests only)
  113. NoiseTestClient *http.Client // optional HTTP client to use for noise RPCs (tests only)
  114. DebugFlags []string // debug settings to send to control
  115. NetMon *netmon.Monitor // optional network monitor
  116. PopBrowserURL func(url string) // optional func to open browser
  117. OnClientVersion func(*tailcfg.ClientVersion) // optional func to inform GUI of client version status
  118. OnControlTime func(time.Time) // optional func to notify callers of new time from control
  119. OnTailnetDefaultAutoUpdate func(bool) // optional func to inform GUI of default auto-update setting for the tailnet
  120. Dialer *tsdial.Dialer // non-nil
  121. C2NHandler http.Handler // or nil
  122. ControlKnobs *controlknobs.Knobs // or nil to ignore
  123. // Observer is called when there's a change in status to report
  124. // from the control client.
  125. Observer Observer
  126. // SkipIPForwardingCheck declares that the host's IP
  127. // forwarding works and should not be double-checked by the
  128. // controlclient package.
  129. SkipIPForwardingCheck bool
  130. // Pinger optionally specifies the Pinger to use to satisfy
  131. // MapResponse.PingRequest queries from the control plane.
  132. // If nil, PingRequest queries are not answered.
  133. Pinger Pinger
  134. // DialPlan contains and stores a previous dial plan that we received
  135. // from the control server; if nil, we fall back to using DNS.
  136. //
  137. // If we receive a new DialPlan from the server, this value will be
  138. // updated.
  139. DialPlan ControlDialPlanner
  140. }
  141. // ControlDialPlanner is the interface optionally supplied when creating a
  142. // control client to control exactly how TCP connections to the control plane
  143. // are dialed.
  144. //
  145. // It is usually implemented by an atomic.Pointer.
  146. type ControlDialPlanner interface {
  147. // Load returns the current plan for how to connect to control.
  148. //
  149. // The returned plan can be nil. If so, connections should be made by
  150. // resolving the control URL using DNS.
  151. Load() *tailcfg.ControlDialPlan
  152. // Store updates the dial plan with new directions from the control
  153. // server.
  154. //
  155. // The dial plan can span multiple connections to the control server.
  156. // That is, a dial plan received when connected over Wi-Fi is still
  157. // valid for a subsequent connection over LTE after a network switch.
  158. Store(*tailcfg.ControlDialPlan)
  159. }
  160. // Pinger is the LocalBackend.Ping method.
  161. type Pinger interface {
  162. // Ping is a request to do a ping with the peer handling the given IP.
  163. Ping(ctx context.Context, ip netip.Addr, pingType tailcfg.PingType, size int) (*ipnstate.PingResult, error)
  164. }
  165. // NetmapUpdater is the interface needed by the controlclient to enact change in
  166. // the world as a function of updates received from the network.
  167. type NetmapUpdater interface {
  168. UpdateFullNetmap(*netmap.NetworkMap)
  169. // TODO(bradfitz): add methods to do fine-grained updates, mutating just
  170. // parts of peers, without implementations of NetmapUpdater needing to do
  171. // the diff themselves between the previous full & next full network maps.
  172. }
  173. // NetmapDeltaUpdater is an optional interface that can be implemented by
  174. // NetmapUpdater implementations to receive delta updates from the controlclient
  175. // rather than just full updates.
  176. type NetmapDeltaUpdater interface {
  177. // UpdateNetmapDelta is called with discrete changes to the network map.
  178. //
  179. // The ok result is whether the implementation was able to apply the
  180. // mutations. It might return false if its internal state doesn't
  181. // support applying them or a NetmapUpdater it's wrapping doesn't
  182. // implement the NetmapDeltaUpdater optional method.
  183. UpdateNetmapDelta([]netmap.NodeMutation) (ok bool)
  184. }
  185. // NewDirect returns a new Direct client.
  186. func NewDirect(opts Options) (*Direct, error) {
  187. if opts.ServerURL == "" {
  188. return nil, errors.New("controlclient.New: no server URL specified")
  189. }
  190. if opts.GetMachinePrivateKey == nil {
  191. return nil, errors.New("controlclient.New: no GetMachinePrivateKey specified")
  192. }
  193. if opts.ControlKnobs == nil {
  194. opts.ControlKnobs = &controlknobs.Knobs{}
  195. }
  196. opts.ServerURL = strings.TrimRight(opts.ServerURL, "/")
  197. serverURL, err := url.Parse(opts.ServerURL)
  198. if err != nil {
  199. return nil, err
  200. }
  201. if opts.Clock == nil {
  202. opts.Clock = tstime.StdClock{}
  203. }
  204. if opts.Logf == nil {
  205. // TODO(apenwarr): remove this default and fail instead.
  206. // TODO(bradfitz): ... but then it shouldn't be in Options.
  207. opts.Logf = log.Printf
  208. }
  209. dnsCache := &dnscache.Resolver{
  210. Forward: dnscache.Get().Forward, // use default cache's forwarder
  211. UseLastGood: true,
  212. LookupIPFallback: dnsfallback.MakeLookupFunc(opts.Logf, opts.NetMon),
  213. Logf: opts.Logf,
  214. NetMon: opts.NetMon,
  215. }
  216. httpc := opts.HTTPTestClient
  217. if httpc == nil && runtime.GOOS == "js" {
  218. // In js/wasm, net/http.Transport (as of Go 1.18) will
  219. // only use the browser's Fetch API if you're using
  220. // the DefaultClient (or a client without dial hooks
  221. // etc set).
  222. httpc = http.DefaultClient
  223. }
  224. if httpc == nil {
  225. tr := http.DefaultTransport.(*http.Transport).Clone()
  226. tr.Proxy = tshttpproxy.ProxyFromEnvironment
  227. tshttpproxy.SetTransportGetProxyConnectHeader(tr)
  228. tr.TLSClientConfig = tlsdial.Config(serverURL.Hostname(), health.Global, tr.TLSClientConfig)
  229. tr.DialContext = dnscache.Dialer(opts.Dialer.SystemDial, dnsCache)
  230. tr.DialTLSContext = dnscache.TLSDialer(opts.Dialer.SystemDial, dnsCache, tr.TLSClientConfig)
  231. tr.ForceAttemptHTTP2 = true
  232. // Disable implicit gzip compression; the various
  233. // handlers (register, map, set-dns, etc) do their own
  234. // zstd compression per naclbox.
  235. tr.DisableCompression = true
  236. httpc = &http.Client{Transport: tr}
  237. }
  238. c := &Direct{
  239. httpc: httpc,
  240. controlKnobs: opts.ControlKnobs,
  241. getMachinePrivKey: opts.GetMachinePrivateKey,
  242. serverURL: opts.ServerURL,
  243. clock: opts.Clock,
  244. logf: opts.Logf,
  245. persist: opts.Persist.View(),
  246. authKey: opts.AuthKey,
  247. discoPubKey: opts.DiscoPublicKey,
  248. debugFlags: opts.DebugFlags,
  249. netMon: opts.NetMon,
  250. skipIPForwardingCheck: opts.SkipIPForwardingCheck,
  251. pinger: opts.Pinger,
  252. popBrowser: opts.PopBrowserURL,
  253. onClientVersion: opts.OnClientVersion,
  254. onTailnetDefaultAutoUpdate: opts.OnTailnetDefaultAutoUpdate,
  255. onControlTime: opts.OnControlTime,
  256. c2nHandler: opts.C2NHandler,
  257. dialer: opts.Dialer,
  258. dnsCache: dnsCache,
  259. dialPlan: opts.DialPlan,
  260. }
  261. if opts.Hostinfo == nil {
  262. c.SetHostinfo(hostinfo.New())
  263. } else {
  264. c.SetHostinfo(opts.Hostinfo)
  265. if ni := opts.Hostinfo.NetInfo; ni != nil {
  266. c.SetNetInfo(ni)
  267. }
  268. }
  269. if opts.NoiseTestClient != nil {
  270. c.noiseClient = &NoiseClient{
  271. Client: opts.NoiseTestClient,
  272. }
  273. c.serverNoiseKey = key.NewMachine().Public() // prevent early error before hitting test client
  274. }
  275. return c, nil
  276. }
  277. // Close closes the underlying Noise connection(s).
  278. func (c *Direct) Close() error {
  279. c.mu.Lock()
  280. defer c.mu.Unlock()
  281. if c.noiseClient != nil {
  282. if err := c.noiseClient.Close(); err != nil {
  283. return err
  284. }
  285. }
  286. c.noiseClient = nil
  287. return nil
  288. }
  289. // SetHostinfo clones the provided Hostinfo and remembers it for the
  290. // next update. It reports whether the Hostinfo has changed.
  291. func (c *Direct) SetHostinfo(hi *tailcfg.Hostinfo) bool {
  292. if hi == nil {
  293. panic("nil Hostinfo")
  294. }
  295. hi = ptr.To(*hi)
  296. hi.NetInfo = nil
  297. c.mu.Lock()
  298. defer c.mu.Unlock()
  299. if hi.Equal(c.hostinfo) {
  300. return false
  301. }
  302. c.hostinfo = hi.Clone()
  303. j, _ := json.Marshal(c.hostinfo)
  304. c.logf("[v1] HostInfo: %s", j)
  305. return true
  306. }
  307. // SetNetInfo clones the provided NetInfo and remembers it for the
  308. // next update. It reports whether the NetInfo has changed.
  309. func (c *Direct) SetNetInfo(ni *tailcfg.NetInfo) bool {
  310. if ni == nil {
  311. panic("nil NetInfo")
  312. }
  313. c.mu.Lock()
  314. defer c.mu.Unlock()
  315. if reflect.DeepEqual(ni, c.netinfo) {
  316. return false
  317. }
  318. c.netinfo = ni.Clone()
  319. c.logf("NetInfo: %v", ni)
  320. return true
  321. }
  322. // SetNetInfo stores a new TKA head value for next update.
  323. // It reports whether the TKA head changed.
  324. func (c *Direct) SetTKAHead(tkaHead string) bool {
  325. c.mu.Lock()
  326. defer c.mu.Unlock()
  327. if tkaHead == c.tkaHead {
  328. return false
  329. }
  330. c.tkaHead = tkaHead
  331. c.logf("tkaHead: %v", tkaHead)
  332. return true
  333. }
  334. func (c *Direct) GetPersist() persist.PersistView {
  335. c.mu.Lock()
  336. defer c.mu.Unlock()
  337. return c.persist
  338. }
  339. func (c *Direct) TryLogout(ctx context.Context) error {
  340. c.logf("[v1] direct.TryLogout()")
  341. mustRegen, newURL, _, err := c.doLogin(ctx, loginOpt{Logout: true})
  342. c.logf("[v1] TryLogout control response: mustRegen=%v, newURL=%v, err=%v", mustRegen, newURL, err)
  343. c.mu.Lock()
  344. c.persist = new(persist.Persist).View()
  345. c.mu.Unlock()
  346. return err
  347. }
  348. func (c *Direct) TryLogin(ctx context.Context, t *tailcfg.Oauth2Token, flags LoginFlags) (url string, err error) {
  349. c.logf("[v1] direct.TryLogin(token=%v, flags=%v)", t != nil, flags)
  350. return c.doLoginOrRegen(ctx, loginOpt{Token: t, Flags: flags})
  351. }
  352. // WaitLoginURL sits in a long poll waiting for the user to authenticate at url.
  353. //
  354. // On success, newURL and err will both be nil.
  355. func (c *Direct) WaitLoginURL(ctx context.Context, url string) (newURL string, err error) {
  356. c.logf("[v1] direct.WaitLoginURL")
  357. return c.doLoginOrRegen(ctx, loginOpt{URL: url})
  358. }
  359. func (c *Direct) doLoginOrRegen(ctx context.Context, opt loginOpt) (newURL string, err error) {
  360. mustRegen, url, oldNodeKeySignature, err := c.doLogin(ctx, opt)
  361. if err != nil {
  362. return url, err
  363. }
  364. if mustRegen {
  365. opt.Regen = true
  366. opt.OldNodeKeySignature = oldNodeKeySignature
  367. _, url, _, err = c.doLogin(ctx, opt)
  368. }
  369. return url, err
  370. }
  371. // SetExpirySooner attempts to shorten the expiry to the specified time.
  372. func (c *Direct) SetExpirySooner(ctx context.Context, expiry time.Time) error {
  373. c.logf("[v1] direct.SetExpirySooner()")
  374. newURL, err := c.doLoginOrRegen(ctx, loginOpt{Expiry: &expiry})
  375. c.logf("[v1] SetExpirySooner control response: newURL=%v, err=%v", newURL, err)
  376. return err
  377. }
  378. type loginOpt struct {
  379. Token *tailcfg.Oauth2Token
  380. Flags LoginFlags
  381. Regen bool // generate a new nodekey, can be overridden in doLogin
  382. URL string
  383. Logout bool // set the expiry to the far past, expiring the node
  384. // Expiry, if non-nil, attempts to set the node expiry to the
  385. // specified time and cannot be used to extend the expiry.
  386. // It is ignored if Logout is set since Logout works by setting a
  387. // expiry time in the far past.
  388. Expiry *time.Time
  389. // OldNodeKeySignature indicates the former NodeKeySignature
  390. // that must be resigned for the new node-key.
  391. OldNodeKeySignature tkatype.MarshaledSignature
  392. }
  393. // hostInfoLocked returns a Clone of c.hostinfo and c.netinfo.
  394. // It must only be called with c.mu held.
  395. func (c *Direct) hostInfoLocked() *tailcfg.Hostinfo {
  396. hi := c.hostinfo.Clone()
  397. hi.NetInfo = c.netinfo.Clone()
  398. return hi
  399. }
  400. func (c *Direct) doLogin(ctx context.Context, opt loginOpt) (mustRegen bool, newURL string, nks tkatype.MarshaledSignature, err error) {
  401. c.mu.Lock()
  402. persist := c.persist.AsStruct()
  403. tryingNewKey := c.tryingNewKey
  404. serverKey := c.serverLegacyKey
  405. serverNoiseKey := c.serverNoiseKey
  406. authKey, isWrapped, wrappedSig, wrappedKey := decodeWrappedAuthkey(c.authKey, c.logf)
  407. hi := c.hostInfoLocked()
  408. backendLogID := hi.BackendLogID
  409. expired := !c.expiry.IsZero() && c.expiry.Before(c.clock.Now())
  410. c.mu.Unlock()
  411. machinePrivKey, err := c.getMachinePrivKey()
  412. if err != nil {
  413. return false, "", nil, fmt.Errorf("getMachinePrivKey: %w", err)
  414. }
  415. if machinePrivKey.IsZero() {
  416. return false, "", nil, errors.New("getMachinePrivKey returned zero key")
  417. }
  418. regen := opt.Regen
  419. if opt.Logout {
  420. c.logf("logging out...")
  421. } else {
  422. if expired {
  423. c.logf("Old key expired -> regen=true")
  424. systemd.Status("key expired; run 'tailscale up' to authenticate")
  425. regen = true
  426. }
  427. if (opt.Flags & LoginInteractive) != 0 {
  428. c.logf("LoginInteractive -> regen=true")
  429. regen = true
  430. }
  431. }
  432. c.logf("doLogin(regen=%v, hasUrl=%v)", regen, opt.URL != "")
  433. if serverKey.IsZero() {
  434. keys, err := loadServerPubKeys(ctx, c.httpc, c.serverURL)
  435. if err != nil {
  436. return regen, opt.URL, nil, err
  437. }
  438. c.logf("control server key from %s: ts2021=%s, legacy=%v", c.serverURL, keys.PublicKey.ShortString(), keys.LegacyPublicKey.ShortString())
  439. c.mu.Lock()
  440. c.serverLegacyKey = keys.LegacyPublicKey
  441. c.serverNoiseKey = keys.PublicKey
  442. c.mu.Unlock()
  443. serverKey = keys.LegacyPublicKey
  444. serverNoiseKey = keys.PublicKey
  445. // Proactively shut down our TLS TCP connection.
  446. // We're not going to need it and it's nicer to the
  447. // server.
  448. c.httpc.CloseIdleConnections()
  449. }
  450. if serverNoiseKey.IsZero() {
  451. return false, "", nil, errors.New("control server is too old; no noise key")
  452. }
  453. var oldNodeKey key.NodePublic
  454. switch {
  455. case opt.Logout:
  456. tryingNewKey = persist.PrivateNodeKey
  457. case opt.URL != "":
  458. // Nothing.
  459. case regen || persist.PrivateNodeKey.IsZero():
  460. c.logf("Generating a new nodekey.")
  461. persist.OldPrivateNodeKey = persist.PrivateNodeKey
  462. tryingNewKey = key.NewNode()
  463. default:
  464. // Try refreshing the current key first
  465. tryingNewKey = persist.PrivateNodeKey
  466. }
  467. if !persist.OldPrivateNodeKey.IsZero() {
  468. oldNodeKey = persist.OldPrivateNodeKey.Public()
  469. }
  470. if persist.NetworkLockKey.IsZero() {
  471. persist.NetworkLockKey = key.NewNLPrivate()
  472. }
  473. nlPub := persist.NetworkLockKey.Public()
  474. if tryingNewKey.IsZero() {
  475. if opt.Logout {
  476. return false, "", nil, errors.New("no nodekey to log out")
  477. }
  478. log.Fatalf("tryingNewKey is empty, give up")
  479. }
  480. var nodeKeySignature tkatype.MarshaledSignature
  481. if !oldNodeKey.IsZero() && opt.OldNodeKeySignature != nil {
  482. if nodeKeySignature, err = resignNKS(persist.NetworkLockKey, tryingNewKey.Public(), opt.OldNodeKeySignature); err != nil {
  483. c.logf("Failed re-signing node-key signature: %v", err)
  484. }
  485. } else if isWrapped {
  486. // We were given a wrapped pre-auth key, which means that in addition
  487. // to being a regular pre-auth key there was a suffix with information to
  488. // generate a tailnet-lock signature.
  489. nk, err := tryingNewKey.Public().MarshalBinary()
  490. if err != nil {
  491. return false, "", nil, fmt.Errorf("marshalling node-key: %w", err)
  492. }
  493. sig := &tka.NodeKeySignature{
  494. SigKind: tka.SigRotation,
  495. Pubkey: nk,
  496. Nested: wrappedSig,
  497. }
  498. sigHash := sig.SigHash()
  499. sig.Signature = ed25519.Sign(wrappedKey, sigHash[:])
  500. nodeKeySignature = sig.Serialize()
  501. }
  502. if backendLogID == "" {
  503. err = errors.New("hostinfo: BackendLogID missing")
  504. return regen, opt.URL, nil, err
  505. }
  506. tailnet, err := syspolicy.GetString(syspolicy.Tailnet, "")
  507. if err != nil {
  508. c.logf("unable to provide Tailnet field in register request. err: %v", err)
  509. }
  510. now := c.clock.Now().Round(time.Second)
  511. request := tailcfg.RegisterRequest{
  512. Version: 1,
  513. OldNodeKey: oldNodeKey,
  514. NodeKey: tryingNewKey.Public(),
  515. NLKey: nlPub,
  516. Hostinfo: hi,
  517. Followup: opt.URL,
  518. Timestamp: &now,
  519. Ephemeral: (opt.Flags & LoginEphemeral) != 0,
  520. NodeKeySignature: nodeKeySignature,
  521. Tailnet: tailnet,
  522. }
  523. if opt.Logout {
  524. request.Expiry = time.Unix(123, 0) // far in the past
  525. } else if opt.Expiry != nil {
  526. request.Expiry = *opt.Expiry
  527. }
  528. c.logf("RegisterReq: onode=%v node=%v fup=%v nks=%v",
  529. request.OldNodeKey.ShortString(),
  530. request.NodeKey.ShortString(), opt.URL != "", len(nodeKeySignature) > 0)
  531. if opt.Token != nil || authKey != "" {
  532. request.Auth = &tailcfg.RegisterResponseAuth{
  533. Oauth2Token: opt.Token,
  534. AuthKey: authKey,
  535. }
  536. }
  537. err = signRegisterRequest(&request, c.serverURL, c.serverLegacyKey, machinePrivKey.Public())
  538. if err != nil {
  539. // If signing failed, clear all related fields
  540. request.SignatureType = tailcfg.SignatureNone
  541. request.Timestamp = nil
  542. request.DeviceCert = nil
  543. request.Signature = nil
  544. // Don't log the common error types. Signatures are not usually enabled,
  545. // so these are expected.
  546. if !errors.Is(err, errCertificateNotConfigured) && !errors.Is(err, errNoCertStore) {
  547. c.logf("RegisterReq sign error: %v", err)
  548. }
  549. }
  550. if debugRegister() {
  551. j, _ := json.MarshalIndent(request, "", "\t")
  552. c.logf("RegisterRequest: %s", j)
  553. }
  554. // URL and httpc are protocol specific.
  555. request.Version = tailcfg.CurrentCapabilityVersion
  556. httpc, err := c.getNoiseClient()
  557. if err != nil {
  558. return regen, opt.URL, nil, fmt.Errorf("getNoiseClient: %w", err)
  559. }
  560. url := fmt.Sprintf("%s/machine/register", c.serverURL)
  561. url = strings.Replace(url, "http:", "https:", 1)
  562. bodyData, err := encode(request)
  563. if err != nil {
  564. return regen, opt.URL, nil, err
  565. }
  566. req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(bodyData))
  567. if err != nil {
  568. return regen, opt.URL, nil, err
  569. }
  570. addLBHeader(req, request.OldNodeKey)
  571. addLBHeader(req, request.NodeKey)
  572. res, err := httpc.Do(req)
  573. if err != nil {
  574. return regen, opt.URL, nil, fmt.Errorf("register request: %w", err)
  575. }
  576. if res.StatusCode != 200 {
  577. msg, _ := io.ReadAll(res.Body)
  578. res.Body.Close()
  579. return regen, opt.URL, nil, fmt.Errorf("register request: http %d: %.200s",
  580. res.StatusCode, strings.TrimSpace(string(msg)))
  581. }
  582. resp := tailcfg.RegisterResponse{}
  583. if err := decode(res, &resp); err != nil {
  584. c.logf("error decoding RegisterResponse with server key %s and machine key %s: %v", serverKey, machinePrivKey.Public(), err)
  585. return regen, opt.URL, nil, fmt.Errorf("register request: %v", err)
  586. }
  587. if debugRegister() {
  588. j, _ := json.MarshalIndent(resp, "", "\t")
  589. c.logf("RegisterResponse: %s", j)
  590. }
  591. // Log without PII:
  592. c.logf("RegisterReq: got response; nodeKeyExpired=%v, machineAuthorized=%v; authURL=%v",
  593. resp.NodeKeyExpired, resp.MachineAuthorized, resp.AuthURL != "")
  594. if resp.Error != "" {
  595. return false, "", nil, UserVisibleError(resp.Error)
  596. }
  597. if len(resp.NodeKeySignature) > 0 {
  598. return true, "", resp.NodeKeySignature, nil
  599. }
  600. if resp.NodeKeyExpired {
  601. if regen {
  602. return true, "", nil, fmt.Errorf("weird: regen=true but server says NodeKeyExpired: %v", request.NodeKey)
  603. }
  604. c.logf("server reports new node key %v has expired",
  605. request.NodeKey.ShortString())
  606. return true, "", nil, nil
  607. }
  608. persist.UserProfile = tailcfg.UserProfile{
  609. ID: resp.User.ID,
  610. DisplayName: resp.Login.DisplayName,
  611. ProfilePicURL: resp.Login.ProfilePicURL,
  612. LoginName: resp.Login.LoginName,
  613. }
  614. // TODO(crawshaw): RegisterResponse should be able to mechanically
  615. // communicate some extra instructions from the server:
  616. // - new node key required
  617. // - machine key no longer supported
  618. // - user is disabled
  619. if resp.AuthURL != "" {
  620. c.logf("AuthURL is %v", resp.AuthURL)
  621. } else {
  622. c.logf("[v1] No AuthURL")
  623. }
  624. c.mu.Lock()
  625. if resp.AuthURL == "" {
  626. // key rotation is complete
  627. persist.PrivateNodeKey = tryingNewKey
  628. } else {
  629. // save it for the retry-with-URL
  630. c.tryingNewKey = tryingNewKey
  631. }
  632. c.persist = persist.View()
  633. c.mu.Unlock()
  634. if ctx.Err() != nil {
  635. return regen, "", nil, ctx.Err()
  636. }
  637. return false, resp.AuthURL, nil, nil
  638. }
  639. // resignNKS re-signs a node-key signature for a new node-key.
  640. //
  641. // This only matters on network-locked tailnets, because node-key signatures are
  642. // how other nodes know that a node-key is authentic. When the node-key is
  643. // rotated then the existing signature becomes invalid, so this function is
  644. // responsible for generating a new wrapping signature to certify the new node-key.
  645. //
  646. // The signature itself is a SigRotation signature, which embeds the old signature
  647. // and certifies the new node-key as a replacement for the old by signing the new
  648. // signature with RotationPubkey (which is the node's own network-lock key).
  649. func resignNKS(priv key.NLPrivate, nodeKey key.NodePublic, oldNKS tkatype.MarshaledSignature) (tkatype.MarshaledSignature, error) {
  650. var oldSig tka.NodeKeySignature
  651. if err := oldSig.Unserialize(oldNKS); err != nil {
  652. return nil, fmt.Errorf("decoding NKS: %w", err)
  653. }
  654. nk, err := nodeKey.MarshalBinary()
  655. if err != nil {
  656. return nil, fmt.Errorf("marshalling node-key: %w", err)
  657. }
  658. if bytes.Equal(nk, oldSig.Pubkey) {
  659. // The old signature is valid for the node-key we are using, so just
  660. // use it verbatim.
  661. return oldNKS, nil
  662. }
  663. newSig := tka.NodeKeySignature{
  664. SigKind: tka.SigRotation,
  665. Pubkey: nk,
  666. Nested: &oldSig,
  667. }
  668. if newSig.Signature, err = priv.SignNKS(newSig.SigHash()); err != nil {
  669. return nil, fmt.Errorf("signing NKS: %w", err)
  670. }
  671. return newSig.Serialize(), nil
  672. }
  673. // newEndpoints acquires c.mu and sets the local port and endpoints and reports
  674. // whether they've changed.
  675. //
  676. // It does not retain the provided slice.
  677. func (c *Direct) newEndpoints(endpoints []tailcfg.Endpoint) (changed bool) {
  678. c.mu.Lock()
  679. defer c.mu.Unlock()
  680. // Nothing new?
  681. if slices.Equal(c.endpoints, endpoints) {
  682. return false // unchanged
  683. }
  684. c.logf("[v2] client.newEndpoints(%v)", endpoints)
  685. c.endpoints = slices.Clone(endpoints)
  686. return true // changed
  687. }
  688. // SetEndpoints updates the list of locally advertised endpoints.
  689. // It won't be replicated to the server until a *fresh* call to PollNetMap().
  690. // You don't need to restart PollNetMap if we return changed==false.
  691. func (c *Direct) SetEndpoints(endpoints []tailcfg.Endpoint) (changed bool) {
  692. // (no log message on function entry, because it clutters the logs
  693. // if endpoints haven't changed. newEndpoints() will log it.)
  694. return c.newEndpoints(endpoints)
  695. }
  696. // PollNetMap makes a /map request to download the network map, calling
  697. // NetmapUpdater on each update from the control plane.
  698. //
  699. // It always returns a non-nil error describing the reason for the failure or
  700. // why the request ended.
  701. func (c *Direct) PollNetMap(ctx context.Context, nu NetmapUpdater) error {
  702. return c.sendMapRequest(ctx, true, nu)
  703. }
  704. type rememberLastNetmapUpdater struct {
  705. last *netmap.NetworkMap
  706. }
  707. func (nu *rememberLastNetmapUpdater) UpdateFullNetmap(nm *netmap.NetworkMap) {
  708. nu.last = nm
  709. }
  710. // FetchNetMapForTest fetches the netmap once.
  711. func (c *Direct) FetchNetMapForTest(ctx context.Context) (*netmap.NetworkMap, error) {
  712. var nu rememberLastNetmapUpdater
  713. err := c.sendMapRequest(ctx, false, &nu)
  714. if err == nil && nu.last == nil {
  715. return nil, errors.New("[unexpected] sendMapRequest success without callback")
  716. }
  717. return nu.last, err
  718. }
  719. // SendUpdate makes a /map request to update the server of our latest state, but
  720. // does not fetch anything. It returns an error if the server did not return a
  721. // successful 200 OK response.
  722. func (c *Direct) SendUpdate(ctx context.Context) error {
  723. return c.sendMapRequest(ctx, false, nil)
  724. }
  725. // If we go more than watchdogTimeout without hearing from the server,
  726. // end the long poll. We should be receiving a keep alive ping
  727. // every minute.
  728. const watchdogTimeout = 120 * time.Second
  729. // sendMapRequest makes a /map request to download the network map, calling cb
  730. // with each new netmap. If isStreaming, it will poll forever and only returns
  731. // if the context expires or the server returns an error/closes the connection
  732. // and as such always returns a non-nil error.
  733. //
  734. // If nu is nil, OmitPeers will be set to true.
  735. func (c *Direct) sendMapRequest(ctx context.Context, isStreaming bool, nu NetmapUpdater) error {
  736. if isStreaming && nu == nil {
  737. panic("cb must be non-nil if isStreaming is true")
  738. }
  739. metricMapRequests.Add(1)
  740. metricMapRequestsActive.Add(1)
  741. defer metricMapRequestsActive.Add(-1)
  742. if isStreaming {
  743. metricMapRequestsPoll.Add(1)
  744. } else {
  745. metricMapRequestsLite.Add(1)
  746. }
  747. c.mu.Lock()
  748. persist := c.persist
  749. serverURL := c.serverURL
  750. serverNoiseKey := c.serverNoiseKey
  751. hi := c.hostInfoLocked()
  752. backendLogID := hi.BackendLogID
  753. var epStrs []string
  754. var eps []netip.AddrPort
  755. var epTypes []tailcfg.EndpointType
  756. for _, ep := range c.endpoints {
  757. eps = append(eps, ep.Addr)
  758. epStrs = append(epStrs, ep.Addr.String())
  759. epTypes = append(epTypes, ep.Type)
  760. }
  761. c.mu.Unlock()
  762. if serverNoiseKey.IsZero() {
  763. return errors.New("control server is too old; no noise key")
  764. }
  765. machinePrivKey, err := c.getMachinePrivKey()
  766. if err != nil {
  767. return fmt.Errorf("getMachinePrivKey: %w", err)
  768. }
  769. if machinePrivKey.IsZero() {
  770. return errors.New("getMachinePrivKey returned zero key")
  771. }
  772. if persist.PrivateNodeKey().IsZero() {
  773. return errors.New("privateNodeKey is zero")
  774. }
  775. if backendLogID == "" {
  776. return errors.New("hostinfo: BackendLogID missing")
  777. }
  778. c.logf("[v1] PollNetMap: stream=%v ep=%v", isStreaming, epStrs)
  779. vlogf := logger.Discard
  780. if DevKnob.DumpNetMaps() {
  781. // TODO(bradfitz): update this to use "[v2]" prefix perhaps? but we don't
  782. // want to upload it always.
  783. vlogf = c.logf
  784. }
  785. nodeKey := persist.PublicNodeKey()
  786. request := &tailcfg.MapRequest{
  787. Version: tailcfg.CurrentCapabilityVersion,
  788. KeepAlive: true,
  789. NodeKey: nodeKey,
  790. DiscoKey: c.discoPubKey,
  791. Endpoints: eps,
  792. EndpointTypes: epTypes,
  793. Stream: isStreaming,
  794. Hostinfo: hi,
  795. DebugFlags: c.debugFlags,
  796. OmitPeers: nu == nil,
  797. TKAHead: c.tkaHead,
  798. }
  799. var extraDebugFlags []string
  800. if hi != nil && c.netMon != nil && !c.skipIPForwardingCheck &&
  801. ipForwardingBroken(hi.RoutableIPs, c.netMon.InterfaceState()) {
  802. extraDebugFlags = append(extraDebugFlags, "warn-ip-forwarding-off")
  803. }
  804. if health.Global.RouterHealth() != nil {
  805. extraDebugFlags = append(extraDebugFlags, "warn-router-unhealthy")
  806. }
  807. extraDebugFlags = health.Global.AppendWarnableDebugFlags(extraDebugFlags)
  808. if hostinfo.DisabledEtcAptSource() {
  809. extraDebugFlags = append(extraDebugFlags, "warn-etc-apt-source-disabled")
  810. }
  811. if len(extraDebugFlags) > 0 {
  812. old := request.DebugFlags
  813. request.DebugFlags = append(old[:len(old):len(old)], extraDebugFlags...)
  814. }
  815. request.Compress = "zstd"
  816. bodyData, err := encode(request)
  817. if err != nil {
  818. vlogf("netmap: encode: %v", err)
  819. return err
  820. }
  821. ctx, cancel := context.WithCancel(ctx)
  822. defer cancel()
  823. machinePubKey := machinePrivKey.Public()
  824. t0 := c.clock.Now()
  825. httpc, err := c.getNoiseClient()
  826. if err != nil {
  827. return fmt.Errorf("getNoiseClient: %w", err)
  828. }
  829. url := fmt.Sprintf("%s/machine/map", serverURL)
  830. url = strings.Replace(url, "http:", "https:", 1)
  831. // Create a watchdog timer that breaks the connection if we don't receive a
  832. // MapResponse from the network at least once every two minutes. The
  833. // watchdog timer is stopped every time we receive a MapResponse (so it
  834. // doesn't run when we're processing a MapResponse message, including any
  835. // long-running requested operations like Debug.Sleep) and is reset whenever
  836. // we go back to blocking on network reads.
  837. // The watchdog timer also covers the initial request (effectively the
  838. // pre-body and initial-body read timeouts) as we do not have any other
  839. // keep-alive mechanism for the initial request.
  840. watchdogTimer, watchdogTimedOut := c.clock.NewTimer(watchdogTimeout)
  841. defer watchdogTimer.Stop()
  842. go func() {
  843. select {
  844. case <-ctx.Done():
  845. vlogf("netmap: ending timeout goroutine")
  846. return
  847. case <-watchdogTimedOut:
  848. c.logf("map response long-poll timed out!")
  849. cancel()
  850. return
  851. }
  852. }()
  853. req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(bodyData))
  854. if err != nil {
  855. return err
  856. }
  857. addLBHeader(req, nodeKey)
  858. res, err := httpc.Do(req)
  859. if err != nil {
  860. vlogf("netmap: Do: %v", err)
  861. return err
  862. }
  863. vlogf("netmap: Do = %v after %v", res.StatusCode, time.Since(t0).Round(time.Millisecond))
  864. if res.StatusCode != 200 {
  865. msg, _ := io.ReadAll(res.Body)
  866. res.Body.Close()
  867. return fmt.Errorf("initial fetch failed %d: %.200s",
  868. res.StatusCode, strings.TrimSpace(string(msg)))
  869. }
  870. defer res.Body.Close()
  871. health.Global.NoteMapRequestHeard(request)
  872. watchdogTimer.Reset(watchdogTimeout)
  873. if nu == nil {
  874. io.Copy(io.Discard, res.Body)
  875. return nil
  876. }
  877. sess := newMapSession(persist.PrivateNodeKey(), nu, c.controlKnobs)
  878. defer sess.Close()
  879. sess.cancel = cancel
  880. sess.logf = c.logf
  881. sess.vlogf = vlogf
  882. sess.altClock = c.clock
  883. sess.machinePubKey = machinePubKey
  884. sess.onDebug = c.handleDebugMessage
  885. sess.onSelfNodeChanged = func(nm *netmap.NetworkMap) {
  886. c.mu.Lock()
  887. defer c.mu.Unlock()
  888. // If we are the ones who last updated persist, then we can update it
  889. // again. Otherwise, we should not touch it. Also, it's only worth
  890. // change it if the Node info changed.
  891. if persist == c.persist {
  892. newPersist := persist.AsStruct()
  893. newPersist.NodeID = nm.SelfNode.StableID()
  894. newPersist.UserProfile = nm.UserProfiles[nm.User()]
  895. c.persist = newPersist.View()
  896. persist = c.persist
  897. }
  898. c.expiry = nm.Expiry
  899. }
  900. // gotNonKeepAliveMessage is whether we've yet received a MapResponse message without
  901. // KeepAlive set.
  902. var gotNonKeepAliveMessage bool
  903. // If allowStream, then the server will use an HTTP long poll to
  904. // return incremental results. There is always one response right
  905. // away, followed by a delay, and eventually others.
  906. // If !allowStream, it'll still send the first result in exactly
  907. // the same format before just closing the connection.
  908. // We can use this same read loop either way.
  909. var msg []byte
  910. for mapResIdx := 0; mapResIdx == 0 || isStreaming; mapResIdx++ {
  911. watchdogTimer.Reset(watchdogTimeout)
  912. vlogf("netmap: starting size read after %v (poll %v)", time.Since(t0).Round(time.Millisecond), mapResIdx)
  913. var siz [4]byte
  914. if _, err := io.ReadFull(res.Body, siz[:]); err != nil {
  915. vlogf("netmap: size read error after %v: %v", time.Since(t0).Round(time.Millisecond), err)
  916. return err
  917. }
  918. size := binary.LittleEndian.Uint32(siz[:])
  919. vlogf("netmap: read size %v after %v", size, time.Since(t0).Round(time.Millisecond))
  920. msg = append(msg[:0], make([]byte, size)...)
  921. if _, err := io.ReadFull(res.Body, msg); err != nil {
  922. vlogf("netmap: body read error: %v", err)
  923. return err
  924. }
  925. vlogf("netmap: read body after %v", time.Since(t0).Round(time.Millisecond))
  926. var resp tailcfg.MapResponse
  927. if err := c.decodeMsg(msg, &resp); err != nil {
  928. vlogf("netmap: decode error: %v", err)
  929. return err
  930. }
  931. watchdogTimer.Stop()
  932. metricMapResponseMessages.Add(1)
  933. if isStreaming {
  934. health.Global.GotStreamedMapResponse()
  935. }
  936. if pr := resp.PingRequest; pr != nil && c.isUniquePingRequest(pr) {
  937. metricMapResponsePings.Add(1)
  938. go c.answerPing(pr)
  939. }
  940. if u := resp.PopBrowserURL; u != "" && u != sess.lastPopBrowserURL {
  941. sess.lastPopBrowserURL = u
  942. if c.popBrowser != nil {
  943. c.logf("netmap: control says to open URL %v; opening...", u)
  944. c.popBrowser(u)
  945. } else {
  946. c.logf("netmap: control says to open URL %v; no popBrowser func", u)
  947. }
  948. }
  949. if resp.ClientVersion != nil && c.onClientVersion != nil {
  950. c.onClientVersion(resp.ClientVersion)
  951. }
  952. if resp.ControlTime != nil && !resp.ControlTime.IsZero() {
  953. c.logf.JSON(1, "controltime", resp.ControlTime.UTC())
  954. if c.onControlTime != nil {
  955. c.onControlTime(*resp.ControlTime)
  956. }
  957. }
  958. if resp.KeepAlive {
  959. vlogf("netmap: got keep-alive")
  960. } else {
  961. vlogf("netmap: got new map")
  962. }
  963. if resp.ControlDialPlan != nil {
  964. if c.dialPlan != nil {
  965. c.logf("netmap: got new dial plan from control")
  966. c.dialPlan.Store(resp.ControlDialPlan)
  967. } else {
  968. c.logf("netmap: [unexpected] new dial plan; nowhere to store it")
  969. }
  970. }
  971. if resp.KeepAlive {
  972. metricMapResponseKeepAlives.Add(1)
  973. continue
  974. }
  975. if au, ok := resp.DefaultAutoUpdate.Get(); ok {
  976. if c.onTailnetDefaultAutoUpdate != nil {
  977. c.onTailnetDefaultAutoUpdate(au)
  978. }
  979. }
  980. metricMapResponseMap.Add(1)
  981. if gotNonKeepAliveMessage {
  982. // If we've already seen a non-keep-alive message, this is a delta update.
  983. metricMapResponseMapDelta.Add(1)
  984. } else if resp.Node == nil {
  985. // The very first non-keep-alive message should have Node populated.
  986. c.logf("initial MapResponse lacked Node")
  987. return errors.New("initial MapResponse lacked node")
  988. }
  989. gotNonKeepAliveMessage = true
  990. if err := sess.HandleNonKeepAliveMapResponse(ctx, &resp); err != nil {
  991. return err
  992. }
  993. }
  994. if ctx.Err() != nil {
  995. return ctx.Err()
  996. }
  997. return nil
  998. }
  999. func (c *Direct) handleDebugMessage(ctx context.Context, debug *tailcfg.Debug) error {
  1000. if code := debug.Exit; code != nil {
  1001. c.logf("exiting process with status %v per controlplane", *code)
  1002. os.Exit(*code)
  1003. }
  1004. if debug.DisableLogTail {
  1005. logtail.Disable()
  1006. envknob.SetNoLogsNoSupport()
  1007. }
  1008. if sleep := time.Duration(debug.SleepSeconds * float64(time.Second)); sleep > 0 {
  1009. if err := sleepAsRequested(ctx, c.logf, sleep, c.clock); err != nil {
  1010. return err
  1011. }
  1012. }
  1013. return nil
  1014. }
  1015. // initDisplayNames mutates any tailcfg.Nodes in resp to populate their display names,
  1016. // calling InitDisplayNames on each.
  1017. //
  1018. // The magicDNSSuffix used is based on selfNode.
  1019. func initDisplayNames(selfNode tailcfg.NodeView, resp *tailcfg.MapResponse) {
  1020. if resp.Node == nil && len(resp.Peers) == 0 && len(resp.PeersChanged) == 0 {
  1021. // Fast path for a common case (delta updates). No need to compute
  1022. // magicDNSSuffix.
  1023. return
  1024. }
  1025. magicDNSSuffix := netmap.MagicDNSSuffixOfNodeName(selfNode.Name())
  1026. if resp.Node != nil {
  1027. resp.Node.InitDisplayNames(magicDNSSuffix)
  1028. }
  1029. for _, n := range resp.Peers {
  1030. n.InitDisplayNames(magicDNSSuffix)
  1031. }
  1032. for _, n := range resp.PeersChanged {
  1033. n.InitDisplayNames(magicDNSSuffix)
  1034. }
  1035. }
  1036. // decode JSON decodes the res.Body into v.
  1037. func decode(res *http.Response, v any) error {
  1038. defer res.Body.Close()
  1039. msg, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
  1040. if err != nil {
  1041. return err
  1042. }
  1043. if res.StatusCode != 200 {
  1044. return fmt.Errorf("%d: %v", res.StatusCode, string(msg))
  1045. }
  1046. return json.Unmarshal(msg, v)
  1047. }
  1048. var (
  1049. debugMap = envknob.RegisterBool("TS_DEBUG_MAP")
  1050. debugRegister = envknob.RegisterBool("TS_DEBUG_REGISTER")
  1051. )
  1052. var jsonEscapedZero = []byte(`\u0000`)
  1053. // decodeMsg is responsible for uncompressing msg and unmarshaling into v.
  1054. func (c *Direct) decodeMsg(compressedMsg []byte, v any) error {
  1055. b, err := zstdframe.AppendDecode(nil, compressedMsg)
  1056. if err != nil {
  1057. return err
  1058. }
  1059. if debugMap() {
  1060. var buf bytes.Buffer
  1061. json.Indent(&buf, b, "", " ")
  1062. log.Printf("MapResponse: %s", buf.Bytes())
  1063. }
  1064. if bytes.Contains(b, jsonEscapedZero) {
  1065. log.Printf("[unexpected] zero byte in controlclient.Direct.decodeMsg into %T: %q", v, b)
  1066. }
  1067. if err := json.Unmarshal(b, v); err != nil {
  1068. return fmt.Errorf("response: %v", err)
  1069. }
  1070. return nil
  1071. }
  1072. // encode JSON encodes v as JSON, logging tailcfg.MapRequest values if
  1073. // debugMap is set.
  1074. func encode(v any) ([]byte, error) {
  1075. b, err := json.Marshal(v)
  1076. if err != nil {
  1077. return nil, err
  1078. }
  1079. if debugMap() {
  1080. if _, ok := v.(*tailcfg.MapRequest); ok {
  1081. log.Printf("MapRequest: %s", b)
  1082. }
  1083. }
  1084. return b, nil
  1085. }
  1086. func loadServerPubKeys(ctx context.Context, httpc *http.Client, serverURL string) (*tailcfg.OverTLSPublicKeyResponse, error) {
  1087. keyURL := fmt.Sprintf("%v/key?v=%d", serverURL, tailcfg.CurrentCapabilityVersion)
  1088. req, err := http.NewRequestWithContext(ctx, "GET", keyURL, nil)
  1089. if err != nil {
  1090. return nil, fmt.Errorf("create control key request: %v", err)
  1091. }
  1092. res, err := httpc.Do(req)
  1093. if err != nil {
  1094. return nil, fmt.Errorf("fetch control key: %v", err)
  1095. }
  1096. defer res.Body.Close()
  1097. b, err := io.ReadAll(io.LimitReader(res.Body, 64<<10))
  1098. if err != nil {
  1099. return nil, fmt.Errorf("fetch control key response: %v", err)
  1100. }
  1101. if res.StatusCode != 200 {
  1102. return nil, fmt.Errorf("fetch control key: %d", res.StatusCode)
  1103. }
  1104. var out tailcfg.OverTLSPublicKeyResponse
  1105. jsonErr := json.Unmarshal(b, &out)
  1106. if jsonErr == nil {
  1107. return &out, nil
  1108. }
  1109. // Some old control servers might not be updated to send the new format.
  1110. // Accept the old pre-JSON format too.
  1111. out = tailcfg.OverTLSPublicKeyResponse{}
  1112. k, err := key.ParseMachinePublicUntyped(mem.B(b))
  1113. if err != nil {
  1114. return nil, multierr.New(jsonErr, err)
  1115. }
  1116. out.LegacyPublicKey = k
  1117. return &out, nil
  1118. }
  1119. // DevKnob contains temporary internal-only debug knobs.
  1120. // They're unexported to not draw attention to them.
  1121. var DevKnob = initDevKnob()
  1122. type devKnobs struct {
  1123. DumpNetMaps func() bool
  1124. ForceProxyDNS func() bool
  1125. StripEndpoints func() bool // strip endpoints from control (only use disco messages)
  1126. StripCaps func() bool // strip all local node's control-provided capabilities
  1127. }
  1128. func initDevKnob() devKnobs {
  1129. return devKnobs{
  1130. DumpNetMaps: envknob.RegisterBool("TS_DEBUG_NETMAP"),
  1131. ForceProxyDNS: envknob.RegisterBool("TS_DEBUG_PROXY_DNS"),
  1132. StripEndpoints: envknob.RegisterBool("TS_DEBUG_STRIP_ENDPOINTS"),
  1133. StripCaps: envknob.RegisterBool("TS_DEBUG_STRIP_CAPS"),
  1134. }
  1135. }
  1136. var clock tstime.Clock = tstime.StdClock{}
  1137. // ipForwardingBroken reports whether the system's IP forwarding is disabled
  1138. // and will definitely not work for the routes provided.
  1139. //
  1140. // It should not return false positives.
  1141. //
  1142. // TODO(bradfitz): Change controlclient.Options.SkipIPForwardingCheck into a
  1143. // func([]netip.Prefix) error signature instead.
  1144. func ipForwardingBroken(routes []netip.Prefix, state *interfaces.State) bool {
  1145. warn, err := netutil.CheckIPForwarding(routes, state)
  1146. if err != nil {
  1147. // Oh well, we tried. This is just for debugging.
  1148. // We don't want false positives.
  1149. // TODO: maybe we want a different warning for inability to check?
  1150. return false
  1151. }
  1152. return warn != nil
  1153. }
  1154. // isUniquePingRequest reports whether pr contains a new PingRequest.URL
  1155. // not already handled, noting its value when returning true.
  1156. func (c *Direct) isUniquePingRequest(pr *tailcfg.PingRequest) bool {
  1157. if pr == nil || pr.URL == "" {
  1158. // Bogus.
  1159. return false
  1160. }
  1161. c.mu.Lock()
  1162. defer c.mu.Unlock()
  1163. if pr.URL == c.lastPingURL {
  1164. return false
  1165. }
  1166. c.lastPingURL = pr.URL
  1167. return true
  1168. }
  1169. func (c *Direct) answerPing(pr *tailcfg.PingRequest) {
  1170. httpc := c.httpc
  1171. useNoise := pr.URLIsNoise || pr.Types == "c2n"
  1172. if useNoise {
  1173. nc, err := c.getNoiseClient()
  1174. if err != nil {
  1175. c.logf("failed to get noise client for ping request: %v", err)
  1176. return
  1177. }
  1178. httpc = nc.Client
  1179. }
  1180. if pr.URL == "" {
  1181. c.logf("invalid PingRequest with no URL")
  1182. return
  1183. }
  1184. switch pr.Types {
  1185. case "":
  1186. answerHeadPing(c.logf, httpc, pr)
  1187. return
  1188. case "c2n":
  1189. if !useNoise && !envknob.Bool("TS_DEBUG_PERMIT_HTTP_C2N") {
  1190. c.logf("refusing to answer c2n ping without noise")
  1191. return
  1192. }
  1193. answerC2NPing(c.logf, c.c2nHandler, httpc, pr)
  1194. return
  1195. }
  1196. for _, t := range strings.Split(pr.Types, ",") {
  1197. switch pt := tailcfg.PingType(t); pt {
  1198. case tailcfg.PingTSMP, tailcfg.PingDisco, tailcfg.PingICMP, tailcfg.PingPeerAPI:
  1199. go doPingerPing(c.logf, httpc, pr, c.pinger, pt)
  1200. default:
  1201. c.logf("unsupported ping request type: %q", t)
  1202. }
  1203. }
  1204. }
  1205. func answerHeadPing(logf logger.Logf, c *http.Client, pr *tailcfg.PingRequest) {
  1206. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  1207. defer cancel()
  1208. req, err := http.NewRequestWithContext(ctx, "HEAD", pr.URL, nil)
  1209. if err != nil {
  1210. logf("answerHeadPing: NewRequestWithContext: %v", err)
  1211. return
  1212. }
  1213. if pr.Log {
  1214. logf("answerHeadPing: sending HEAD ping to %v ...", pr.URL)
  1215. }
  1216. t0 := clock.Now()
  1217. _, err = c.Do(req)
  1218. d := clock.Since(t0).Round(time.Millisecond)
  1219. if err != nil {
  1220. logf("answerHeadPing error: %v to %v (after %v)", err, pr.URL, d)
  1221. } else if pr.Log {
  1222. logf("answerHeadPing complete to %v (after %v)", pr.URL, d)
  1223. }
  1224. }
  1225. func answerC2NPing(logf logger.Logf, c2nHandler http.Handler, c *http.Client, pr *tailcfg.PingRequest) {
  1226. if c2nHandler == nil {
  1227. logf("answerC2NPing: c2nHandler not defined")
  1228. return
  1229. }
  1230. hreq, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(pr.Payload)))
  1231. if err != nil {
  1232. logf("answerC2NPing: ReadRequest: %v", err)
  1233. return
  1234. }
  1235. if pr.Log {
  1236. logf("answerC2NPing: got c2n request for %v ...", hreq.RequestURI)
  1237. }
  1238. handlerTimeout := time.Minute
  1239. if v := hreq.Header.Get("C2n-Handler-Timeout"); v != "" {
  1240. handlerTimeout, _ = time.ParseDuration(v)
  1241. }
  1242. handlerCtx, cancel := context.WithTimeout(context.Background(), handlerTimeout)
  1243. defer cancel()
  1244. hreq = hreq.WithContext(handlerCtx)
  1245. rec := httptest.NewRecorder()
  1246. c2nHandler.ServeHTTP(rec, hreq)
  1247. cancel()
  1248. c2nResBuf := new(bytes.Buffer)
  1249. rec.Result().Write(c2nResBuf)
  1250. replyCtx, cancel := context.WithTimeout(context.Background(), time.Minute)
  1251. defer cancel()
  1252. req, err := http.NewRequestWithContext(replyCtx, "POST", pr.URL, c2nResBuf)
  1253. if err != nil {
  1254. logf("answerC2NPing: NewRequestWithContext: %v", err)
  1255. return
  1256. }
  1257. if pr.Log {
  1258. logf("answerC2NPing: sending POST ping to %v ...", pr.URL)
  1259. }
  1260. t0 := clock.Now()
  1261. _, err = c.Do(req)
  1262. d := time.Since(t0).Round(time.Millisecond)
  1263. if err != nil {
  1264. logf("answerC2NPing error: %v to %v (after %v)", err, pr.URL, d)
  1265. } else if pr.Log {
  1266. logf("answerC2NPing complete to %v (after %v)", pr.URL, d)
  1267. }
  1268. }
  1269. // sleepAsRequest implements the sleep for a tailcfg.Debug message requesting
  1270. // that the client sleep. The complication is that while we're sleeping (if for
  1271. // a long time), we need to periodically reset the watchdog timer before it
  1272. // expires.
  1273. func sleepAsRequested(ctx context.Context, logf logger.Logf, d time.Duration, clock tstime.Clock) error {
  1274. const maxSleep = 5 * time.Minute
  1275. if d > maxSleep {
  1276. logf("sleeping for %v, capped from server-requested %v ...", maxSleep, d)
  1277. d = maxSleep
  1278. } else {
  1279. logf("sleeping for server-requested %v ...", d)
  1280. }
  1281. timer, timerChannel := clock.NewTimer(d)
  1282. defer timer.Stop()
  1283. select {
  1284. case <-ctx.Done():
  1285. return ctx.Err()
  1286. case <-timerChannel:
  1287. return nil
  1288. }
  1289. }
  1290. // getNoiseClient returns the noise client, creating one if one doesn't exist.
  1291. func (c *Direct) getNoiseClient() (*NoiseClient, error) {
  1292. c.mu.Lock()
  1293. serverNoiseKey := c.serverNoiseKey
  1294. nc := c.noiseClient
  1295. c.mu.Unlock()
  1296. if serverNoiseKey.IsZero() {
  1297. return nil, errors.New("zero serverNoiseKey")
  1298. }
  1299. if nc != nil {
  1300. return nc, nil
  1301. }
  1302. var dp func() *tailcfg.ControlDialPlan
  1303. if c.dialPlan != nil {
  1304. dp = c.dialPlan.Load
  1305. }
  1306. nc, err, _ := c.sfGroup.Do(struct{}{}, func() (*NoiseClient, error) {
  1307. k, err := c.getMachinePrivKey()
  1308. if err != nil {
  1309. return nil, err
  1310. }
  1311. c.logf("[v1] creating new noise client")
  1312. nc, err := NewNoiseClient(NoiseOpts{
  1313. PrivKey: k,
  1314. ServerPubKey: serverNoiseKey,
  1315. ServerURL: c.serverURL,
  1316. Dialer: c.dialer,
  1317. DNSCache: c.dnsCache,
  1318. Logf: c.logf,
  1319. NetMon: c.netMon,
  1320. DialPlan: dp,
  1321. })
  1322. if err != nil {
  1323. return nil, err
  1324. }
  1325. c.mu.Lock()
  1326. defer c.mu.Unlock()
  1327. c.noiseClient = nc
  1328. return nc, nil
  1329. })
  1330. if err != nil {
  1331. return nil, err
  1332. }
  1333. return nc, nil
  1334. }
  1335. // setDNSNoise sends the SetDNSRequest request to the control plane server over Noise,
  1336. // requesting a DNS record be created or updated.
  1337. func (c *Direct) setDNSNoise(ctx context.Context, req *tailcfg.SetDNSRequest) error {
  1338. newReq := *req
  1339. newReq.Version = tailcfg.CurrentCapabilityVersion
  1340. nc, err := c.getNoiseClient()
  1341. if err != nil {
  1342. return err
  1343. }
  1344. res, err := nc.post(ctx, "/machine/set-dns", newReq.NodeKey, &newReq)
  1345. if err != nil {
  1346. return err
  1347. }
  1348. defer res.Body.Close()
  1349. if res.StatusCode != 200 {
  1350. msg, _ := io.ReadAll(res.Body)
  1351. return fmt.Errorf("set-dns response: %v, %.200s", res.Status, strings.TrimSpace(string(msg)))
  1352. }
  1353. var setDNSRes tailcfg.SetDNSResponse
  1354. if err := json.NewDecoder(res.Body).Decode(&setDNSRes); err != nil {
  1355. c.logf("error decoding SetDNSResponse: %v", err)
  1356. return fmt.Errorf("set-dns-response: %w", err)
  1357. }
  1358. return nil
  1359. }
  1360. // SetDNS sends the SetDNSRequest request to the control plane server,
  1361. // requesting a DNS record be created or updated.
  1362. func (c *Direct) SetDNS(ctx context.Context, req *tailcfg.SetDNSRequest) (err error) {
  1363. metricSetDNS.Add(1)
  1364. defer func() {
  1365. if err != nil {
  1366. metricSetDNSError.Add(1)
  1367. }
  1368. }()
  1369. return c.setDNSNoise(ctx, req)
  1370. }
  1371. func (c *Direct) DoNoiseRequest(req *http.Request) (*http.Response, error) {
  1372. nc, err := c.getNoiseClient()
  1373. if err != nil {
  1374. return nil, err
  1375. }
  1376. return nc.Do(req)
  1377. }
  1378. // GetSingleUseNoiseRoundTripper returns a RoundTripper that can be only be used
  1379. // once (and must be used once) to make a single HTTP request over the noise
  1380. // channel to the coordination server.
  1381. //
  1382. // In addition to the RoundTripper, it returns the HTTP/2 channel's early noise
  1383. // payload, if any.
  1384. func (c *Direct) GetSingleUseNoiseRoundTripper(ctx context.Context) (http.RoundTripper, *tailcfg.EarlyNoise, error) {
  1385. nc, err := c.getNoiseClient()
  1386. if err != nil {
  1387. return nil, nil, err
  1388. }
  1389. return nc.GetSingleUseRoundTripper(ctx)
  1390. }
  1391. // doPingerPing sends a Ping to pr.IP using pinger, and sends an http request back to
  1392. // pr.URL with ping response data.
  1393. func doPingerPing(logf logger.Logf, c *http.Client, pr *tailcfg.PingRequest, pinger Pinger, pingType tailcfg.PingType) {
  1394. if pr.URL == "" || !pr.IP.IsValid() || pinger == nil {
  1395. logf("invalid ping request: missing url, ip or pinger")
  1396. return
  1397. }
  1398. start := clock.Now()
  1399. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  1400. defer cancel()
  1401. res, err := pinger.Ping(ctx, pr.IP, pingType, 0)
  1402. if err != nil {
  1403. d := time.Since(start).Round(time.Millisecond)
  1404. logf("doPingerPing: ping error of type %q to %v after %v: %v", pingType, pr.IP, d, err)
  1405. return
  1406. }
  1407. postPingResult(start, logf, c, pr, res.ToPingResponse(pingType))
  1408. }
  1409. func postPingResult(start time.Time, logf logger.Logf, c *http.Client, pr *tailcfg.PingRequest, res *tailcfg.PingResponse) error {
  1410. duration := time.Since(start)
  1411. if pr.Log {
  1412. if res.Err == "" {
  1413. logf("ping to %v completed in %v. pinger.Ping took %v seconds", pr.IP, res.LatencySeconds, duration)
  1414. } else {
  1415. logf("ping to %v failed after %v: %v", pr.IP, duration, res.Err)
  1416. }
  1417. }
  1418. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  1419. defer cancel()
  1420. jsonPingRes, err := json.Marshal(res)
  1421. if err != nil {
  1422. return err
  1423. }
  1424. // Send the results of the Ping, back to control URL.
  1425. req, err := http.NewRequestWithContext(ctx, "POST", pr.URL, bytes.NewReader(jsonPingRes))
  1426. if err != nil {
  1427. return fmt.Errorf("http.NewRequestWithContext(%q): %w", pr.URL, err)
  1428. }
  1429. if pr.Log {
  1430. logf("postPingResult: sending ping results to %v ...", pr.URL)
  1431. }
  1432. t0 := clock.Now()
  1433. _, err = c.Do(req)
  1434. d := time.Since(t0).Round(time.Millisecond)
  1435. if err != nil {
  1436. return fmt.Errorf("postPingResult error: %w to %v (after %v)", err, pr.URL, d)
  1437. } else if pr.Log {
  1438. logf("postPingResult complete to %v (after %v)", pr.URL, d)
  1439. }
  1440. return nil
  1441. }
  1442. // ReportHealthChange reports to the control plane a change to this node's
  1443. // health.
  1444. func (c *Direct) ReportHealthChange(sys health.Subsystem, sysErr error) {
  1445. if sys == health.SysOverall {
  1446. // We don't report these. These include things like the network is down
  1447. // (in which case we can't report anyway) or the user wanted things
  1448. // stopped, as opposed to the more unexpected failure types in the other
  1449. // subsystems.
  1450. return
  1451. }
  1452. np, err := c.getNoiseClient()
  1453. if err != nil {
  1454. // Don't report errors to control if the server doesn't support noise.
  1455. return
  1456. }
  1457. nodeKey, ok := c.GetPersist().PublicNodeKeyOK()
  1458. if !ok {
  1459. return
  1460. }
  1461. req := &tailcfg.HealthChangeRequest{
  1462. Subsys: string(sys),
  1463. NodeKey: nodeKey,
  1464. }
  1465. if sysErr != nil {
  1466. req.Error = sysErr.Error()
  1467. }
  1468. // Best effort, no logging:
  1469. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  1470. defer cancel()
  1471. res, err := np.post(ctx, "/machine/update-health", nodeKey, req)
  1472. if err != nil {
  1473. return
  1474. }
  1475. res.Body.Close()
  1476. }
  1477. // decodeWrappedAuthkey separates wrapping information from an authkey, if any.
  1478. // In all cases the authkey is returned, sans wrapping information if any.
  1479. //
  1480. // If the authkey is wrapped, isWrapped returns true, along with the wrapping signature
  1481. // and private key.
  1482. func decodeWrappedAuthkey(key string, logf logger.Logf) (authKey string, isWrapped bool, sig *tka.NodeKeySignature, priv ed25519.PrivateKey) {
  1483. authKey, suffix, found := strings.Cut(key, "--TL")
  1484. if !found {
  1485. return key, false, nil, nil
  1486. }
  1487. sigBytes, privBytes, found := strings.Cut(suffix, "-")
  1488. if !found {
  1489. logf("decoding wrapped auth-key: did not find delimiter")
  1490. return key, false, nil, nil
  1491. }
  1492. rawSig, err := base64.RawStdEncoding.DecodeString(sigBytes)
  1493. if err != nil {
  1494. logf("decoding wrapped auth-key: signature decode: %v", err)
  1495. return key, false, nil, nil
  1496. }
  1497. rawPriv, err := base64.RawStdEncoding.DecodeString(privBytes)
  1498. if err != nil {
  1499. logf("decoding wrapped auth-key: priv decode: %v", err)
  1500. return key, false, nil, nil
  1501. }
  1502. sig = new(tka.NodeKeySignature)
  1503. if err := sig.Unserialize([]byte(rawSig)); err != nil {
  1504. logf("decoding wrapped auth-key: signature: %v", err)
  1505. return key, false, nil, nil
  1506. }
  1507. priv = ed25519.PrivateKey(rawPriv)
  1508. return authKey, true, sig, priv
  1509. }
  1510. func addLBHeader(req *http.Request, nodeKey key.NodePublic) {
  1511. if !nodeKey.IsZero() {
  1512. req.Header.Add(tailcfg.LBHeader, nodeKey.String())
  1513. }
  1514. }
  1515. var (
  1516. metricMapRequestsActive = clientmetric.NewGauge("controlclient_map_requests_active")
  1517. metricMapRequests = clientmetric.NewCounter("controlclient_map_requests")
  1518. metricMapRequestsLite = clientmetric.NewCounter("controlclient_map_requests_lite")
  1519. metricMapRequestsPoll = clientmetric.NewCounter("controlclient_map_requests_poll")
  1520. metricMapResponseMessages = clientmetric.NewCounter("controlclient_map_response_message") // any message type
  1521. metricMapResponsePings = clientmetric.NewCounter("controlclient_map_response_ping")
  1522. metricMapResponseKeepAlives = clientmetric.NewCounter("controlclient_map_response_keepalive")
  1523. metricMapResponseMap = clientmetric.NewCounter("controlclient_map_response_map") // any non-keepalive map response
  1524. metricMapResponseMapDelta = clientmetric.NewCounter("controlclient_map_response_map_delta") // 2nd+ non-keepalive map response
  1525. metricSetDNS = clientmetric.NewCounter("controlclient_setdns")
  1526. metricSetDNSError = clientmetric.NewCounter("controlclient_setdns_error")
  1527. )