direct.go 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689
  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(), 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. request.Auth.Oauth2Token = opt.Token
  532. request.Auth.Provider = persist.Provider
  533. request.Auth.LoginName = persist.UserProfile.LoginName
  534. request.Auth.AuthKey = authKey
  535. err = signRegisterRequest(&request, c.serverURL, c.serverLegacyKey, machinePrivKey.Public())
  536. if err != nil {
  537. // If signing failed, clear all related fields
  538. request.SignatureType = tailcfg.SignatureNone
  539. request.Timestamp = nil
  540. request.DeviceCert = nil
  541. request.Signature = nil
  542. // Don't log the common error types. Signatures are not usually enabled,
  543. // so these are expected.
  544. if !errors.Is(err, errCertificateNotConfigured) && !errors.Is(err, errNoCertStore) {
  545. c.logf("RegisterReq sign error: %v", err)
  546. }
  547. }
  548. if debugRegister() {
  549. j, _ := json.MarshalIndent(request, "", "\t")
  550. c.logf("RegisterRequest: %s", j)
  551. }
  552. // URL and httpc are protocol specific.
  553. request.Version = tailcfg.CurrentCapabilityVersion
  554. httpc, err := c.getNoiseClient()
  555. if err != nil {
  556. return regen, opt.URL, nil, fmt.Errorf("getNoiseClient: %w", err)
  557. }
  558. url := fmt.Sprintf("%s/machine/register", c.serverURL)
  559. url = strings.Replace(url, "http:", "https:", 1)
  560. bodyData, err := encode(request)
  561. if err != nil {
  562. return regen, opt.URL, nil, err
  563. }
  564. req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(bodyData))
  565. if err != nil {
  566. return regen, opt.URL, nil, err
  567. }
  568. addLBHeader(req, request.OldNodeKey)
  569. addLBHeader(req, request.NodeKey)
  570. res, err := httpc.Do(req)
  571. if err != nil {
  572. return regen, opt.URL, nil, fmt.Errorf("register request: %w", err)
  573. }
  574. if res.StatusCode != 200 {
  575. msg, _ := io.ReadAll(res.Body)
  576. res.Body.Close()
  577. return regen, opt.URL, nil, fmt.Errorf("register request: http %d: %.200s",
  578. res.StatusCode, strings.TrimSpace(string(msg)))
  579. }
  580. resp := tailcfg.RegisterResponse{}
  581. if err := decode(res, &resp); err != nil {
  582. c.logf("error decoding RegisterResponse with server key %s and machine key %s: %v", serverKey, machinePrivKey.Public(), err)
  583. return regen, opt.URL, nil, fmt.Errorf("register request: %v", err)
  584. }
  585. if debugRegister() {
  586. j, _ := json.MarshalIndent(resp, "", "\t")
  587. c.logf("RegisterResponse: %s", j)
  588. }
  589. // Log without PII:
  590. c.logf("RegisterReq: got response; nodeKeyExpired=%v, machineAuthorized=%v; authURL=%v",
  591. resp.NodeKeyExpired, resp.MachineAuthorized, resp.AuthURL != "")
  592. if resp.Error != "" {
  593. return false, "", nil, UserVisibleError(resp.Error)
  594. }
  595. if len(resp.NodeKeySignature) > 0 {
  596. return true, "", resp.NodeKeySignature, nil
  597. }
  598. if resp.NodeKeyExpired {
  599. if regen {
  600. return true, "", nil, fmt.Errorf("weird: regen=true but server says NodeKeyExpired: %v", request.NodeKey)
  601. }
  602. c.logf("server reports new node key %v has expired",
  603. request.NodeKey.ShortString())
  604. return true, "", nil, nil
  605. }
  606. if resp.Login.Provider != "" {
  607. persist.Provider = resp.Login.Provider
  608. }
  609. persist.UserProfile = tailcfg.UserProfile{
  610. ID: resp.User.ID,
  611. DisplayName: resp.Login.DisplayName,
  612. ProfilePicURL: resp.Login.ProfilePicURL,
  613. LoginName: resp.Login.LoginName,
  614. }
  615. // TODO(crawshaw): RegisterResponse should be able to mechanically
  616. // communicate some extra instructions from the server:
  617. // - new node key required
  618. // - machine key no longer supported
  619. // - user is disabled
  620. if resp.AuthURL != "" {
  621. c.logf("AuthURL is %v", resp.AuthURL)
  622. } else {
  623. c.logf("[v1] No AuthURL")
  624. }
  625. c.mu.Lock()
  626. if resp.AuthURL == "" {
  627. // key rotation is complete
  628. persist.PrivateNodeKey = tryingNewKey
  629. } else {
  630. // save it for the retry-with-URL
  631. c.tryingNewKey = tryingNewKey
  632. }
  633. c.persist = persist.View()
  634. c.mu.Unlock()
  635. if ctx.Err() != nil {
  636. return regen, "", nil, ctx.Err()
  637. }
  638. return false, resp.AuthURL, nil, nil
  639. }
  640. // resignNKS re-signs a node-key signature for a new node-key.
  641. //
  642. // This only matters on network-locked tailnets, because node-key signatures are
  643. // how other nodes know that a node-key is authentic. When the node-key is
  644. // rotated then the existing signature becomes invalid, so this function is
  645. // responsible for generating a new wrapping signature to certify the new node-key.
  646. //
  647. // The signature itself is a SigRotation signature, which embeds the old signature
  648. // and certifies the new node-key as a replacement for the old by signing the new
  649. // signature with RotationPubkey (which is the node's own network-lock key).
  650. func resignNKS(priv key.NLPrivate, nodeKey key.NodePublic, oldNKS tkatype.MarshaledSignature) (tkatype.MarshaledSignature, error) {
  651. var oldSig tka.NodeKeySignature
  652. if err := oldSig.Unserialize(oldNKS); err != nil {
  653. return nil, fmt.Errorf("decoding NKS: %w", err)
  654. }
  655. nk, err := nodeKey.MarshalBinary()
  656. if err != nil {
  657. return nil, fmt.Errorf("marshalling node-key: %w", err)
  658. }
  659. if bytes.Equal(nk, oldSig.Pubkey) {
  660. // The old signature is valid for the node-key we are using, so just
  661. // use it verbatim.
  662. return oldNKS, nil
  663. }
  664. newSig := tka.NodeKeySignature{
  665. SigKind: tka.SigRotation,
  666. Pubkey: nk,
  667. Nested: &oldSig,
  668. }
  669. if newSig.Signature, err = priv.SignNKS(newSig.SigHash()); err != nil {
  670. return nil, fmt.Errorf("signing NKS: %w", err)
  671. }
  672. return newSig.Serialize(), nil
  673. }
  674. // newEndpoints acquires c.mu and sets the local port and endpoints and reports
  675. // whether they've changed.
  676. //
  677. // It does not retain the provided slice.
  678. func (c *Direct) newEndpoints(endpoints []tailcfg.Endpoint) (changed bool) {
  679. c.mu.Lock()
  680. defer c.mu.Unlock()
  681. // Nothing new?
  682. if slices.Equal(c.endpoints, endpoints) {
  683. return false // unchanged
  684. }
  685. c.logf("[v2] client.newEndpoints(%v)", endpoints)
  686. c.endpoints = slices.Clone(endpoints)
  687. return true // changed
  688. }
  689. // SetEndpoints updates the list of locally advertised endpoints.
  690. // It won't be replicated to the server until a *fresh* call to PollNetMap().
  691. // You don't need to restart PollNetMap if we return changed==false.
  692. func (c *Direct) SetEndpoints(endpoints []tailcfg.Endpoint) (changed bool) {
  693. // (no log message on function entry, because it clutters the logs
  694. // if endpoints haven't changed. newEndpoints() will log it.)
  695. return c.newEndpoints(endpoints)
  696. }
  697. // PollNetMap makes a /map request to download the network map, calling
  698. // NetmapUpdater on each update from the control plane.
  699. //
  700. // It always returns a non-nil error describing the reason for the failure or
  701. // why the request ended.
  702. func (c *Direct) PollNetMap(ctx context.Context, nu NetmapUpdater) error {
  703. return c.sendMapRequest(ctx, true, nu)
  704. }
  705. type rememberLastNetmapUpdater struct {
  706. last *netmap.NetworkMap
  707. }
  708. func (nu *rememberLastNetmapUpdater) UpdateFullNetmap(nm *netmap.NetworkMap) {
  709. nu.last = nm
  710. }
  711. // FetchNetMapForTest fetches the netmap once.
  712. func (c *Direct) FetchNetMapForTest(ctx context.Context) (*netmap.NetworkMap, error) {
  713. var nu rememberLastNetmapUpdater
  714. err := c.sendMapRequest(ctx, false, &nu)
  715. if err == nil && nu.last == nil {
  716. return nil, errors.New("[unexpected] sendMapRequest success without callback")
  717. }
  718. return nu.last, err
  719. }
  720. // SendUpdate makes a /map request to update the server of our latest state, but
  721. // does not fetch anything. It returns an error if the server did not return a
  722. // successful 200 OK response.
  723. func (c *Direct) SendUpdate(ctx context.Context) error {
  724. return c.sendMapRequest(ctx, false, nil)
  725. }
  726. // If we go more than watchdogTimeout without hearing from the server,
  727. // end the long poll. We should be receiving a keep alive ping
  728. // every minute.
  729. const watchdogTimeout = 120 * time.Second
  730. // sendMapRequest makes a /map request to download the network map, calling cb
  731. // with each new netmap. If isStreaming, it will poll forever and only returns
  732. // if the context expires or the server returns an error/closes the connection
  733. // and as such always returns a non-nil error.
  734. //
  735. // If nu is nil, OmitPeers will be set to true.
  736. func (c *Direct) sendMapRequest(ctx context.Context, isStreaming bool, nu NetmapUpdater) error {
  737. if isStreaming && nu == nil {
  738. panic("cb must be non-nil if isStreaming is true")
  739. }
  740. metricMapRequests.Add(1)
  741. metricMapRequestsActive.Add(1)
  742. defer metricMapRequestsActive.Add(-1)
  743. if isStreaming {
  744. metricMapRequestsPoll.Add(1)
  745. } else {
  746. metricMapRequestsLite.Add(1)
  747. }
  748. c.mu.Lock()
  749. persist := c.persist
  750. serverURL := c.serverURL
  751. serverNoiseKey := c.serverNoiseKey
  752. hi := c.hostInfoLocked()
  753. backendLogID := hi.BackendLogID
  754. var epStrs []string
  755. var eps []netip.AddrPort
  756. var epTypes []tailcfg.EndpointType
  757. for _, ep := range c.endpoints {
  758. eps = append(eps, ep.Addr)
  759. epStrs = append(epStrs, ep.Addr.String())
  760. epTypes = append(epTypes, ep.Type)
  761. }
  762. c.mu.Unlock()
  763. if serverNoiseKey.IsZero() {
  764. return errors.New("control server is too old; no noise key")
  765. }
  766. machinePrivKey, err := c.getMachinePrivKey()
  767. if err != nil {
  768. return fmt.Errorf("getMachinePrivKey: %w", err)
  769. }
  770. if machinePrivKey.IsZero() {
  771. return errors.New("getMachinePrivKey returned zero key")
  772. }
  773. if persist.PrivateNodeKey().IsZero() {
  774. return errors.New("privateNodeKey is zero")
  775. }
  776. if backendLogID == "" {
  777. return errors.New("hostinfo: BackendLogID missing")
  778. }
  779. c.logf("[v1] PollNetMap: stream=%v ep=%v", isStreaming, epStrs)
  780. vlogf := logger.Discard
  781. if DevKnob.DumpNetMaps() {
  782. // TODO(bradfitz): update this to use "[v2]" prefix perhaps? but we don't
  783. // want to upload it always.
  784. vlogf = c.logf
  785. }
  786. nodeKey := persist.PublicNodeKey()
  787. request := &tailcfg.MapRequest{
  788. Version: tailcfg.CurrentCapabilityVersion,
  789. KeepAlive: true,
  790. NodeKey: nodeKey,
  791. DiscoKey: c.discoPubKey,
  792. Endpoints: eps,
  793. EndpointTypes: epTypes,
  794. Stream: isStreaming,
  795. Hostinfo: hi,
  796. DebugFlags: c.debugFlags,
  797. OmitPeers: nu == nil,
  798. TKAHead: c.tkaHead,
  799. }
  800. var extraDebugFlags []string
  801. if hi != nil && c.netMon != nil && !c.skipIPForwardingCheck &&
  802. ipForwardingBroken(hi.RoutableIPs, c.netMon.InterfaceState()) {
  803. extraDebugFlags = append(extraDebugFlags, "warn-ip-forwarding-off")
  804. }
  805. if health.RouterHealth() != nil {
  806. extraDebugFlags = append(extraDebugFlags, "warn-router-unhealthy")
  807. }
  808. extraDebugFlags = health.AppendWarnableDebugFlags(extraDebugFlags)
  809. if hostinfo.DisabledEtcAptSource() {
  810. extraDebugFlags = append(extraDebugFlags, "warn-etc-apt-source-disabled")
  811. }
  812. if len(extraDebugFlags) > 0 {
  813. old := request.DebugFlags
  814. request.DebugFlags = append(old[:len(old):len(old)], extraDebugFlags...)
  815. }
  816. request.Compress = "zstd"
  817. bodyData, err := encode(request)
  818. if err != nil {
  819. vlogf("netmap: encode: %v", err)
  820. return err
  821. }
  822. ctx, cancel := context.WithCancel(ctx)
  823. defer cancel()
  824. machinePubKey := machinePrivKey.Public()
  825. t0 := c.clock.Now()
  826. httpc, err := c.getNoiseClient()
  827. if err != nil {
  828. return fmt.Errorf("getNoiseClient: %w", err)
  829. }
  830. url := fmt.Sprintf("%s/machine/map", serverURL)
  831. url = strings.Replace(url, "http:", "https:", 1)
  832. // Create a watchdog timer that breaks the connection if we don't receive a
  833. // MapResponse from the network at least once every two minutes. The
  834. // watchdog timer is stopped every time we receive a MapResponse (so it
  835. // doesn't run when we're processing a MapResponse message, including any
  836. // long-running requested operations like Debug.Sleep) and is reset whenever
  837. // we go back to blocking on network reads.
  838. // The watchdog timer also covers the initial request (effectively the
  839. // pre-body and initial-body read timeouts) as we do not have any other
  840. // keep-alive mechanism for the initial request.
  841. watchdogTimer, watchdogTimedOut := c.clock.NewTimer(watchdogTimeout)
  842. defer watchdogTimer.Stop()
  843. go func() {
  844. select {
  845. case <-ctx.Done():
  846. vlogf("netmap: ending timeout goroutine")
  847. return
  848. case <-watchdogTimedOut:
  849. c.logf("map response long-poll timed out!")
  850. cancel()
  851. return
  852. }
  853. }()
  854. req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(bodyData))
  855. if err != nil {
  856. return err
  857. }
  858. addLBHeader(req, nodeKey)
  859. res, err := httpc.Do(req)
  860. if err != nil {
  861. vlogf("netmap: Do: %v", err)
  862. return err
  863. }
  864. vlogf("netmap: Do = %v after %v", res.StatusCode, time.Since(t0).Round(time.Millisecond))
  865. if res.StatusCode != 200 {
  866. msg, _ := io.ReadAll(res.Body)
  867. res.Body.Close()
  868. return fmt.Errorf("initial fetch failed %d: %.200s",
  869. res.StatusCode, strings.TrimSpace(string(msg)))
  870. }
  871. defer res.Body.Close()
  872. health.NoteMapRequestHeard(request)
  873. watchdogTimer.Reset(watchdogTimeout)
  874. if nu == nil {
  875. io.Copy(io.Discard, res.Body)
  876. return nil
  877. }
  878. sess := newMapSession(persist.PrivateNodeKey(), nu, c.controlKnobs)
  879. defer sess.Close()
  880. sess.cancel = cancel
  881. sess.logf = c.logf
  882. sess.vlogf = vlogf
  883. sess.altClock = c.clock
  884. sess.machinePubKey = machinePubKey
  885. sess.onDebug = c.handleDebugMessage
  886. sess.onSelfNodeChanged = func(nm *netmap.NetworkMap) {
  887. c.mu.Lock()
  888. defer c.mu.Unlock()
  889. // If we are the ones who last updated persist, then we can update it
  890. // again. Otherwise, we should not touch it. Also, it's only worth
  891. // change it if the Node info changed.
  892. if persist == c.persist {
  893. newPersist := persist.AsStruct()
  894. newPersist.NodeID = nm.SelfNode.StableID()
  895. newPersist.UserProfile = nm.UserProfiles[nm.User()]
  896. c.persist = newPersist.View()
  897. persist = c.persist
  898. }
  899. c.expiry = nm.Expiry
  900. }
  901. // gotNonKeepAliveMessage is whether we've yet received a MapResponse message without
  902. // KeepAlive set.
  903. var gotNonKeepAliveMessage bool
  904. // If allowStream, then the server will use an HTTP long poll to
  905. // return incremental results. There is always one response right
  906. // away, followed by a delay, and eventually others.
  907. // If !allowStream, it'll still send the first result in exactly
  908. // the same format before just closing the connection.
  909. // We can use this same read loop either way.
  910. var msg []byte
  911. for mapResIdx := 0; mapResIdx == 0 || isStreaming; mapResIdx++ {
  912. watchdogTimer.Reset(watchdogTimeout)
  913. vlogf("netmap: starting size read after %v (poll %v)", time.Since(t0).Round(time.Millisecond), mapResIdx)
  914. var siz [4]byte
  915. if _, err := io.ReadFull(res.Body, siz[:]); err != nil {
  916. vlogf("netmap: size read error after %v: %v", time.Since(t0).Round(time.Millisecond), err)
  917. return err
  918. }
  919. size := binary.LittleEndian.Uint32(siz[:])
  920. vlogf("netmap: read size %v after %v", size, time.Since(t0).Round(time.Millisecond))
  921. msg = append(msg[:0], make([]byte, size)...)
  922. if _, err := io.ReadFull(res.Body, msg); err != nil {
  923. vlogf("netmap: body read error: %v", err)
  924. return err
  925. }
  926. vlogf("netmap: read body after %v", time.Since(t0).Round(time.Millisecond))
  927. var resp tailcfg.MapResponse
  928. if err := c.decodeMsg(msg, &resp); err != nil {
  929. vlogf("netmap: decode error: %v", err)
  930. return err
  931. }
  932. watchdogTimer.Stop()
  933. metricMapResponseMessages.Add(1)
  934. if isStreaming {
  935. health.GotStreamedMapResponse()
  936. }
  937. if pr := resp.PingRequest; pr != nil && c.isUniquePingRequest(pr) {
  938. metricMapResponsePings.Add(1)
  939. go c.answerPing(pr)
  940. }
  941. if u := resp.PopBrowserURL; u != "" && u != sess.lastPopBrowserURL {
  942. sess.lastPopBrowserURL = u
  943. if c.popBrowser != nil {
  944. c.logf("netmap: control says to open URL %v; opening...", u)
  945. c.popBrowser(u)
  946. } else {
  947. c.logf("netmap: control says to open URL %v; no popBrowser func", u)
  948. }
  949. }
  950. if resp.ClientVersion != nil && c.onClientVersion != nil {
  951. c.onClientVersion(resp.ClientVersion)
  952. }
  953. if resp.ControlTime != nil && !resp.ControlTime.IsZero() {
  954. c.logf.JSON(1, "controltime", resp.ControlTime.UTC())
  955. if c.onControlTime != nil {
  956. c.onControlTime(*resp.ControlTime)
  957. }
  958. }
  959. if resp.KeepAlive {
  960. vlogf("netmap: got keep-alive")
  961. } else {
  962. vlogf("netmap: got new map")
  963. }
  964. if resp.ControlDialPlan != nil {
  965. if c.dialPlan != nil {
  966. c.logf("netmap: got new dial plan from control")
  967. c.dialPlan.Store(resp.ControlDialPlan)
  968. } else {
  969. c.logf("netmap: [unexpected] new dial plan; nowhere to store it")
  970. }
  971. }
  972. if resp.KeepAlive {
  973. metricMapResponseKeepAlives.Add(1)
  974. continue
  975. }
  976. if au, ok := resp.DefaultAutoUpdate.Get(); ok {
  977. if c.onTailnetDefaultAutoUpdate != nil {
  978. c.onTailnetDefaultAutoUpdate(au)
  979. }
  980. }
  981. metricMapResponseMap.Add(1)
  982. if gotNonKeepAliveMessage {
  983. // If we've already seen a non-keep-alive message, this is a delta update.
  984. metricMapResponseMapDelta.Add(1)
  985. } else if resp.Node == nil {
  986. // The very first non-keep-alive message should have Node populated.
  987. c.logf("initial MapResponse lacked Node")
  988. return errors.New("initial MapResponse lacked node")
  989. }
  990. gotNonKeepAliveMessage = true
  991. if err := sess.HandleNonKeepAliveMapResponse(ctx, &resp); err != nil {
  992. return err
  993. }
  994. }
  995. if ctx.Err() != nil {
  996. return ctx.Err()
  997. }
  998. return nil
  999. }
  1000. func (c *Direct) handleDebugMessage(ctx context.Context, debug *tailcfg.Debug) error {
  1001. if code := debug.Exit; code != nil {
  1002. c.logf("exiting process with status %v per controlplane", *code)
  1003. os.Exit(*code)
  1004. }
  1005. if debug.DisableLogTail {
  1006. logtail.Disable()
  1007. envknob.SetNoLogsNoSupport()
  1008. }
  1009. if sleep := time.Duration(debug.SleepSeconds * float64(time.Second)); sleep > 0 {
  1010. if err := sleepAsRequested(ctx, c.logf, sleep, c.clock); err != nil {
  1011. return err
  1012. }
  1013. }
  1014. return nil
  1015. }
  1016. // initDisplayNames mutates any tailcfg.Nodes in resp to populate their display names,
  1017. // calling InitDisplayNames on each.
  1018. //
  1019. // The magicDNSSuffix used is based on selfNode.
  1020. func initDisplayNames(selfNode tailcfg.NodeView, resp *tailcfg.MapResponse) {
  1021. if resp.Node == nil && len(resp.Peers) == 0 && len(resp.PeersChanged) == 0 {
  1022. // Fast path for a common case (delta updates). No need to compute
  1023. // magicDNSSuffix.
  1024. return
  1025. }
  1026. magicDNSSuffix := netmap.MagicDNSSuffixOfNodeName(selfNode.Name())
  1027. if resp.Node != nil {
  1028. resp.Node.InitDisplayNames(magicDNSSuffix)
  1029. }
  1030. for _, n := range resp.Peers {
  1031. n.InitDisplayNames(magicDNSSuffix)
  1032. }
  1033. for _, n := range resp.PeersChanged {
  1034. n.InitDisplayNames(magicDNSSuffix)
  1035. }
  1036. }
  1037. // decode JSON decodes the res.Body into v.
  1038. func decode(res *http.Response, v any) error {
  1039. defer res.Body.Close()
  1040. msg, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
  1041. if err != nil {
  1042. return err
  1043. }
  1044. if res.StatusCode != 200 {
  1045. return fmt.Errorf("%d: %v", res.StatusCode, string(msg))
  1046. }
  1047. return json.Unmarshal(msg, v)
  1048. }
  1049. var (
  1050. debugMap = envknob.RegisterBool("TS_DEBUG_MAP")
  1051. debugRegister = envknob.RegisterBool("TS_DEBUG_REGISTER")
  1052. )
  1053. var jsonEscapedZero = []byte(`\u0000`)
  1054. // decodeMsg is responsible for uncompressing msg and unmarshaling into v.
  1055. func (c *Direct) decodeMsg(compressedMsg []byte, v any) error {
  1056. b, err := zstdframe.AppendDecode(nil, compressedMsg)
  1057. if err != nil {
  1058. return err
  1059. }
  1060. if debugMap() {
  1061. var buf bytes.Buffer
  1062. json.Indent(&buf, b, "", " ")
  1063. log.Printf("MapResponse: %s", buf.Bytes())
  1064. }
  1065. if bytes.Contains(b, jsonEscapedZero) {
  1066. log.Printf("[unexpected] zero byte in controlclient.Direct.decodeMsg into %T: %q", v, b)
  1067. }
  1068. if err := json.Unmarshal(b, v); err != nil {
  1069. return fmt.Errorf("response: %v", err)
  1070. }
  1071. return nil
  1072. }
  1073. // encode JSON encodes v as JSON, logging tailcfg.MapRequest values if
  1074. // debugMap is set.
  1075. func encode(v any) ([]byte, error) {
  1076. b, err := json.Marshal(v)
  1077. if err != nil {
  1078. return nil, err
  1079. }
  1080. if debugMap() {
  1081. if _, ok := v.(*tailcfg.MapRequest); ok {
  1082. log.Printf("MapRequest: %s", b)
  1083. }
  1084. }
  1085. return b, nil
  1086. }
  1087. func loadServerPubKeys(ctx context.Context, httpc *http.Client, serverURL string) (*tailcfg.OverTLSPublicKeyResponse, error) {
  1088. keyURL := fmt.Sprintf("%v/key?v=%d", serverURL, tailcfg.CurrentCapabilityVersion)
  1089. req, err := http.NewRequestWithContext(ctx, "GET", keyURL, nil)
  1090. if err != nil {
  1091. return nil, fmt.Errorf("create control key request: %v", err)
  1092. }
  1093. res, err := httpc.Do(req)
  1094. if err != nil {
  1095. return nil, fmt.Errorf("fetch control key: %v", err)
  1096. }
  1097. defer res.Body.Close()
  1098. b, err := io.ReadAll(io.LimitReader(res.Body, 64<<10))
  1099. if err != nil {
  1100. return nil, fmt.Errorf("fetch control key response: %v", err)
  1101. }
  1102. if res.StatusCode != 200 {
  1103. return nil, fmt.Errorf("fetch control key: %d", res.StatusCode)
  1104. }
  1105. var out tailcfg.OverTLSPublicKeyResponse
  1106. jsonErr := json.Unmarshal(b, &out)
  1107. if jsonErr == nil {
  1108. return &out, nil
  1109. }
  1110. // Some old control servers might not be updated to send the new format.
  1111. // Accept the old pre-JSON format too.
  1112. out = tailcfg.OverTLSPublicKeyResponse{}
  1113. k, err := key.ParseMachinePublicUntyped(mem.B(b))
  1114. if err != nil {
  1115. return nil, multierr.New(jsonErr, err)
  1116. }
  1117. out.LegacyPublicKey = k
  1118. return &out, nil
  1119. }
  1120. // DevKnob contains temporary internal-only debug knobs.
  1121. // They're unexported to not draw attention to them.
  1122. var DevKnob = initDevKnob()
  1123. type devKnobs struct {
  1124. DumpNetMaps func() bool
  1125. ForceProxyDNS func() bool
  1126. StripEndpoints func() bool // strip endpoints from control (only use disco messages)
  1127. StripCaps func() bool // strip all local node's control-provided capabilities
  1128. }
  1129. func initDevKnob() devKnobs {
  1130. return devKnobs{
  1131. DumpNetMaps: envknob.RegisterBool("TS_DEBUG_NETMAP"),
  1132. ForceProxyDNS: envknob.RegisterBool("TS_DEBUG_PROXY_DNS"),
  1133. StripEndpoints: envknob.RegisterBool("TS_DEBUG_STRIP_ENDPOINTS"),
  1134. StripCaps: envknob.RegisterBool("TS_DEBUG_STRIP_CAPS"),
  1135. }
  1136. }
  1137. var clock tstime.Clock = tstime.StdClock{}
  1138. // ipForwardingBroken reports whether the system's IP forwarding is disabled
  1139. // and will definitely not work for the routes provided.
  1140. //
  1141. // It should not return false positives.
  1142. //
  1143. // TODO(bradfitz): Change controlclient.Options.SkipIPForwardingCheck into a
  1144. // func([]netip.Prefix) error signature instead.
  1145. func ipForwardingBroken(routes []netip.Prefix, state *interfaces.State) bool {
  1146. warn, err := netutil.CheckIPForwarding(routes, state)
  1147. if err != nil {
  1148. // Oh well, we tried. This is just for debugging.
  1149. // We don't want false positives.
  1150. // TODO: maybe we want a different warning for inability to check?
  1151. return false
  1152. }
  1153. return warn != nil
  1154. }
  1155. // isUniquePingRequest reports whether pr contains a new PingRequest.URL
  1156. // not already handled, noting its value when returning true.
  1157. func (c *Direct) isUniquePingRequest(pr *tailcfg.PingRequest) bool {
  1158. if pr == nil || pr.URL == "" {
  1159. // Bogus.
  1160. return false
  1161. }
  1162. c.mu.Lock()
  1163. defer c.mu.Unlock()
  1164. if pr.URL == c.lastPingURL {
  1165. return false
  1166. }
  1167. c.lastPingURL = pr.URL
  1168. return true
  1169. }
  1170. func (c *Direct) answerPing(pr *tailcfg.PingRequest) {
  1171. httpc := c.httpc
  1172. useNoise := pr.URLIsNoise || pr.Types == "c2n"
  1173. if useNoise {
  1174. nc, err := c.getNoiseClient()
  1175. if err != nil {
  1176. c.logf("failed to get noise client for ping request: %v", err)
  1177. return
  1178. }
  1179. httpc = nc.Client
  1180. }
  1181. if pr.URL == "" {
  1182. c.logf("invalid PingRequest with no URL")
  1183. return
  1184. }
  1185. switch pr.Types {
  1186. case "":
  1187. answerHeadPing(c.logf, httpc, pr)
  1188. return
  1189. case "c2n":
  1190. if !useNoise && !envknob.Bool("TS_DEBUG_PERMIT_HTTP_C2N") {
  1191. c.logf("refusing to answer c2n ping without noise")
  1192. return
  1193. }
  1194. answerC2NPing(c.logf, c.c2nHandler, httpc, pr)
  1195. return
  1196. }
  1197. for _, t := range strings.Split(pr.Types, ",") {
  1198. switch pt := tailcfg.PingType(t); pt {
  1199. case tailcfg.PingTSMP, tailcfg.PingDisco, tailcfg.PingICMP, tailcfg.PingPeerAPI:
  1200. go doPingerPing(c.logf, httpc, pr, c.pinger, pt)
  1201. default:
  1202. c.logf("unsupported ping request type: %q", t)
  1203. }
  1204. }
  1205. }
  1206. func answerHeadPing(logf logger.Logf, c *http.Client, pr *tailcfg.PingRequest) {
  1207. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  1208. defer cancel()
  1209. req, err := http.NewRequestWithContext(ctx, "HEAD", pr.URL, nil)
  1210. if err != nil {
  1211. logf("answerHeadPing: NewRequestWithContext: %v", err)
  1212. return
  1213. }
  1214. if pr.Log {
  1215. logf("answerHeadPing: sending HEAD ping to %v ...", pr.URL)
  1216. }
  1217. t0 := clock.Now()
  1218. _, err = c.Do(req)
  1219. d := clock.Since(t0).Round(time.Millisecond)
  1220. if err != nil {
  1221. logf("answerHeadPing error: %v to %v (after %v)", err, pr.URL, d)
  1222. } else if pr.Log {
  1223. logf("answerHeadPing complete to %v (after %v)", pr.URL, d)
  1224. }
  1225. }
  1226. func answerC2NPing(logf logger.Logf, c2nHandler http.Handler, c *http.Client, pr *tailcfg.PingRequest) {
  1227. if c2nHandler == nil {
  1228. logf("answerC2NPing: c2nHandler not defined")
  1229. return
  1230. }
  1231. hreq, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(pr.Payload)))
  1232. if err != nil {
  1233. logf("answerC2NPing: ReadRequest: %v", err)
  1234. return
  1235. }
  1236. if pr.Log {
  1237. logf("answerC2NPing: got c2n request for %v ...", hreq.RequestURI)
  1238. }
  1239. handlerTimeout := time.Minute
  1240. if v := hreq.Header.Get("C2n-Handler-Timeout"); v != "" {
  1241. handlerTimeout, _ = time.ParseDuration(v)
  1242. }
  1243. handlerCtx, cancel := context.WithTimeout(context.Background(), handlerTimeout)
  1244. defer cancel()
  1245. hreq = hreq.WithContext(handlerCtx)
  1246. rec := httptest.NewRecorder()
  1247. c2nHandler.ServeHTTP(rec, hreq)
  1248. cancel()
  1249. c2nResBuf := new(bytes.Buffer)
  1250. rec.Result().Write(c2nResBuf)
  1251. replyCtx, cancel := context.WithTimeout(context.Background(), time.Minute)
  1252. defer cancel()
  1253. req, err := http.NewRequestWithContext(replyCtx, "POST", pr.URL, c2nResBuf)
  1254. if err != nil {
  1255. logf("answerC2NPing: NewRequestWithContext: %v", err)
  1256. return
  1257. }
  1258. if pr.Log {
  1259. logf("answerC2NPing: sending POST ping to %v ...", pr.URL)
  1260. }
  1261. t0 := clock.Now()
  1262. _, err = c.Do(req)
  1263. d := time.Since(t0).Round(time.Millisecond)
  1264. if err != nil {
  1265. logf("answerC2NPing error: %v to %v (after %v)", err, pr.URL, d)
  1266. } else if pr.Log {
  1267. logf("answerC2NPing complete to %v (after %v)", pr.URL, d)
  1268. }
  1269. }
  1270. // sleepAsRequest implements the sleep for a tailcfg.Debug message requesting
  1271. // that the client sleep. The complication is that while we're sleeping (if for
  1272. // a long time), we need to periodically reset the watchdog timer before it
  1273. // expires.
  1274. func sleepAsRequested(ctx context.Context, logf logger.Logf, d time.Duration, clock tstime.Clock) error {
  1275. const maxSleep = 5 * time.Minute
  1276. if d > maxSleep {
  1277. logf("sleeping for %v, capped from server-requested %v ...", maxSleep, d)
  1278. d = maxSleep
  1279. } else {
  1280. logf("sleeping for server-requested %v ...", d)
  1281. }
  1282. timer, timerChannel := clock.NewTimer(d)
  1283. defer timer.Stop()
  1284. select {
  1285. case <-ctx.Done():
  1286. return ctx.Err()
  1287. case <-timerChannel:
  1288. return nil
  1289. }
  1290. }
  1291. // getNoiseClient returns the noise client, creating one if one doesn't exist.
  1292. func (c *Direct) getNoiseClient() (*NoiseClient, error) {
  1293. c.mu.Lock()
  1294. serverNoiseKey := c.serverNoiseKey
  1295. nc := c.noiseClient
  1296. c.mu.Unlock()
  1297. if serverNoiseKey.IsZero() {
  1298. return nil, errors.New("zero serverNoiseKey")
  1299. }
  1300. if nc != nil {
  1301. return nc, nil
  1302. }
  1303. var dp func() *tailcfg.ControlDialPlan
  1304. if c.dialPlan != nil {
  1305. dp = c.dialPlan.Load
  1306. }
  1307. nc, err, _ := c.sfGroup.Do(struct{}{}, func() (*NoiseClient, error) {
  1308. k, err := c.getMachinePrivKey()
  1309. if err != nil {
  1310. return nil, err
  1311. }
  1312. c.logf("[v1] creating new noise client")
  1313. nc, err := NewNoiseClient(NoiseOpts{
  1314. PrivKey: k,
  1315. ServerPubKey: serverNoiseKey,
  1316. ServerURL: c.serverURL,
  1317. Dialer: c.dialer,
  1318. DNSCache: c.dnsCache,
  1319. Logf: c.logf,
  1320. NetMon: c.netMon,
  1321. DialPlan: dp,
  1322. })
  1323. if err != nil {
  1324. return nil, err
  1325. }
  1326. c.mu.Lock()
  1327. defer c.mu.Unlock()
  1328. c.noiseClient = nc
  1329. return nc, nil
  1330. })
  1331. if err != nil {
  1332. return nil, err
  1333. }
  1334. return nc, nil
  1335. }
  1336. // setDNSNoise sends the SetDNSRequest request to the control plane server over Noise,
  1337. // requesting a DNS record be created or updated.
  1338. func (c *Direct) setDNSNoise(ctx context.Context, req *tailcfg.SetDNSRequest) error {
  1339. newReq := *req
  1340. newReq.Version = tailcfg.CurrentCapabilityVersion
  1341. nc, err := c.getNoiseClient()
  1342. if err != nil {
  1343. return err
  1344. }
  1345. res, err := nc.post(ctx, "/machine/set-dns", newReq.NodeKey, &newReq)
  1346. if err != nil {
  1347. return err
  1348. }
  1349. defer res.Body.Close()
  1350. if res.StatusCode != 200 {
  1351. msg, _ := io.ReadAll(res.Body)
  1352. return fmt.Errorf("set-dns response: %v, %.200s", res.Status, strings.TrimSpace(string(msg)))
  1353. }
  1354. var setDNSRes tailcfg.SetDNSResponse
  1355. if err := json.NewDecoder(res.Body).Decode(&setDNSRes); err != nil {
  1356. c.logf("error decoding SetDNSResponse: %v", err)
  1357. return fmt.Errorf("set-dns-response: %w", err)
  1358. }
  1359. return nil
  1360. }
  1361. // SetDNS sends the SetDNSRequest request to the control plane server,
  1362. // requesting a DNS record be created or updated.
  1363. func (c *Direct) SetDNS(ctx context.Context, req *tailcfg.SetDNSRequest) (err error) {
  1364. metricSetDNS.Add(1)
  1365. defer func() {
  1366. if err != nil {
  1367. metricSetDNSError.Add(1)
  1368. }
  1369. }()
  1370. return c.setDNSNoise(ctx, req)
  1371. }
  1372. func (c *Direct) DoNoiseRequest(req *http.Request) (*http.Response, error) {
  1373. nc, err := c.getNoiseClient()
  1374. if err != nil {
  1375. return nil, err
  1376. }
  1377. return nc.Do(req)
  1378. }
  1379. // GetSingleUseNoiseRoundTripper returns a RoundTripper that can be only be used
  1380. // once (and must be used once) to make a single HTTP request over the noise
  1381. // channel to the coordination server.
  1382. //
  1383. // In addition to the RoundTripper, it returns the HTTP/2 channel's early noise
  1384. // payload, if any.
  1385. func (c *Direct) GetSingleUseNoiseRoundTripper(ctx context.Context) (http.RoundTripper, *tailcfg.EarlyNoise, error) {
  1386. nc, err := c.getNoiseClient()
  1387. if err != nil {
  1388. return nil, nil, err
  1389. }
  1390. return nc.GetSingleUseRoundTripper(ctx)
  1391. }
  1392. // doPingerPing sends a Ping to pr.IP using pinger, and sends an http request back to
  1393. // pr.URL with ping response data.
  1394. func doPingerPing(logf logger.Logf, c *http.Client, pr *tailcfg.PingRequest, pinger Pinger, pingType tailcfg.PingType) {
  1395. if pr.URL == "" || !pr.IP.IsValid() || pinger == nil {
  1396. logf("invalid ping request: missing url, ip or pinger")
  1397. return
  1398. }
  1399. start := clock.Now()
  1400. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  1401. defer cancel()
  1402. res, err := pinger.Ping(ctx, pr.IP, pingType, 0)
  1403. if err != nil {
  1404. d := time.Since(start).Round(time.Millisecond)
  1405. logf("doPingerPing: ping error of type %q to %v after %v: %v", pingType, pr.IP, d, err)
  1406. return
  1407. }
  1408. postPingResult(start, logf, c, pr, res.ToPingResponse(pingType))
  1409. }
  1410. func postPingResult(start time.Time, logf logger.Logf, c *http.Client, pr *tailcfg.PingRequest, res *tailcfg.PingResponse) error {
  1411. duration := time.Since(start)
  1412. if pr.Log {
  1413. if res.Err == "" {
  1414. logf("ping to %v completed in %v. pinger.Ping took %v seconds", pr.IP, res.LatencySeconds, duration)
  1415. } else {
  1416. logf("ping to %v failed after %v: %v", pr.IP, duration, res.Err)
  1417. }
  1418. }
  1419. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  1420. defer cancel()
  1421. jsonPingRes, err := json.Marshal(res)
  1422. if err != nil {
  1423. return err
  1424. }
  1425. // Send the results of the Ping, back to control URL.
  1426. req, err := http.NewRequestWithContext(ctx, "POST", pr.URL, bytes.NewReader(jsonPingRes))
  1427. if err != nil {
  1428. return fmt.Errorf("http.NewRequestWithContext(%q): %w", pr.URL, err)
  1429. }
  1430. if pr.Log {
  1431. logf("postPingResult: sending ping results to %v ...", pr.URL)
  1432. }
  1433. t0 := clock.Now()
  1434. _, err = c.Do(req)
  1435. d := time.Since(t0).Round(time.Millisecond)
  1436. if err != nil {
  1437. return fmt.Errorf("postPingResult error: %w to %v (after %v)", err, pr.URL, d)
  1438. } else if pr.Log {
  1439. logf("postPingResult complete to %v (after %v)", pr.URL, d)
  1440. }
  1441. return nil
  1442. }
  1443. // ReportHealthChange reports to the control plane a change to this node's
  1444. // health.
  1445. func (c *Direct) ReportHealthChange(sys health.Subsystem, sysErr error) {
  1446. if sys == health.SysOverall {
  1447. // We don't report these. These include things like the network is down
  1448. // (in which case we can't report anyway) or the user wanted things
  1449. // stopped, as opposed to the more unexpected failure types in the other
  1450. // subsystems.
  1451. return
  1452. }
  1453. np, err := c.getNoiseClient()
  1454. if err != nil {
  1455. // Don't report errors to control if the server doesn't support noise.
  1456. return
  1457. }
  1458. nodeKey, ok := c.GetPersist().PublicNodeKeyOK()
  1459. if !ok {
  1460. return
  1461. }
  1462. req := &tailcfg.HealthChangeRequest{
  1463. Subsys: string(sys),
  1464. NodeKey: nodeKey,
  1465. }
  1466. if sysErr != nil {
  1467. req.Error = sysErr.Error()
  1468. }
  1469. // Best effort, no logging:
  1470. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  1471. defer cancel()
  1472. res, err := np.post(ctx, "/machine/update-health", nodeKey, req)
  1473. if err != nil {
  1474. return
  1475. }
  1476. res.Body.Close()
  1477. }
  1478. // decodeWrappedAuthkey separates wrapping information from an authkey, if any.
  1479. // In all cases the authkey is returned, sans wrapping information if any.
  1480. //
  1481. // If the authkey is wrapped, isWrapped returns true, along with the wrapping signature
  1482. // and private key.
  1483. func decodeWrappedAuthkey(key string, logf logger.Logf) (authKey string, isWrapped bool, sig *tka.NodeKeySignature, priv ed25519.PrivateKey) {
  1484. authKey, suffix, found := strings.Cut(key, "--TL")
  1485. if !found {
  1486. return key, false, nil, nil
  1487. }
  1488. sigBytes, privBytes, found := strings.Cut(suffix, "-")
  1489. if !found {
  1490. logf("decoding wrapped auth-key: did not find delimiter")
  1491. return key, false, nil, nil
  1492. }
  1493. rawSig, err := base64.RawStdEncoding.DecodeString(sigBytes)
  1494. if err != nil {
  1495. logf("decoding wrapped auth-key: signature decode: %v", err)
  1496. return key, false, nil, nil
  1497. }
  1498. rawPriv, err := base64.RawStdEncoding.DecodeString(privBytes)
  1499. if err != nil {
  1500. logf("decoding wrapped auth-key: priv decode: %v", err)
  1501. return key, false, nil, nil
  1502. }
  1503. sig = new(tka.NodeKeySignature)
  1504. if err := sig.Unserialize([]byte(rawSig)); err != nil {
  1505. logf("decoding wrapped auth-key: signature: %v", err)
  1506. return key, false, nil, nil
  1507. }
  1508. priv = ed25519.PrivateKey(rawPriv)
  1509. return authKey, true, sig, priv
  1510. }
  1511. func addLBHeader(req *http.Request, nodeKey key.NodePublic) {
  1512. if !nodeKey.IsZero() {
  1513. req.Header.Add(tailcfg.LBHeader, nodeKey.String())
  1514. }
  1515. }
  1516. var (
  1517. metricMapRequestsActive = clientmetric.NewGauge("controlclient_map_requests_active")
  1518. metricMapRequests = clientmetric.NewCounter("controlclient_map_requests")
  1519. metricMapRequestsLite = clientmetric.NewCounter("controlclient_map_requests_lite")
  1520. metricMapRequestsPoll = clientmetric.NewCounter("controlclient_map_requests_poll")
  1521. metricMapResponseMessages = clientmetric.NewCounter("controlclient_map_response_message") // any message type
  1522. metricMapResponsePings = clientmetric.NewCounter("controlclient_map_response_ping")
  1523. metricMapResponseKeepAlives = clientmetric.NewCounter("controlclient_map_response_keepalive")
  1524. metricMapResponseMap = clientmetric.NewCounter("controlclient_map_response_map") // any non-keepalive map response
  1525. metricMapResponseMapDelta = clientmetric.NewCounter("controlclient_map_response_map_delta") // 2nd+ non-keepalive map response
  1526. metricSetDNS = clientmetric.NewCounter("controlclient_setdns")
  1527. metricSetDNSError = clientmetric.NewCounter("controlclient_setdns_error")
  1528. )