direct.go 52 KB

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