direct.go 53 KB

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