ipnstate.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package ipnstate captures the entire state of the Tailscale network.
  4. //
  5. // It's a leaf package so ipn, wgengine, and magicsock can all depend on it.
  6. package ipnstate
  7. import (
  8. "fmt"
  9. "html"
  10. "io"
  11. "log"
  12. "net/netip"
  13. "slices"
  14. "sort"
  15. "strings"
  16. "time"
  17. "tailscale.com/tailcfg"
  18. "tailscale.com/tka"
  19. "tailscale.com/types/key"
  20. "tailscale.com/types/ptr"
  21. "tailscale.com/types/views"
  22. "tailscale.com/util/dnsname"
  23. "tailscale.com/version"
  24. )
  25. //go:generate go run tailscale.com/cmd/cloner -clonefunc=false -type=TKAPeer
  26. // Status represents the entire state of the IPN network.
  27. type Status struct {
  28. // Version is the daemon's long version (see version.Long).
  29. Version string
  30. // TUN is whether /dev/net/tun (or equivalent kernel interface) is being
  31. // used. If false, it's running in userspace mode.
  32. TUN bool
  33. // BackendState is an ipn.State string value:
  34. // "NoState", "NeedsLogin", "NeedsMachineAuth", "Stopped",
  35. // "Starting", "Running".
  36. BackendState string
  37. // HaveNodeKey is whether the current profile has a node key configured.
  38. HaveNodeKey bool `json:",omitempty"`
  39. AuthURL string // current URL provided by control to authorize client
  40. TailscaleIPs []netip.Addr // Tailscale IP(s) assigned to this node
  41. Self *PeerStatus
  42. // ExitNodeStatus describes the current exit node.
  43. // If nil, an exit node is not in use.
  44. ExitNodeStatus *ExitNodeStatus `json:"ExitNodeStatus,omitempty"`
  45. // Health contains health check problems.
  46. // Empty means everything is good. (or at least that no known
  47. // problems are detected)
  48. Health []string
  49. // This field is the legacy name of CurrentTailnet.MagicDNSSuffix.
  50. //
  51. // Deprecated: use CurrentTailnet.MagicDNSSuffix instead.
  52. MagicDNSSuffix string
  53. // CurrentTailnet is information about the tailnet that the node
  54. // is currently connected to. When not connected, this field is nil.
  55. CurrentTailnet *TailnetStatus
  56. // CertDomains are the set of DNS names for which the control
  57. // plane server will assist with provisioning TLS
  58. // certificates. See SetDNSRequest for dns-01 ACME challenges
  59. // for e.g. LetsEncrypt. These names are FQDNs without
  60. // trailing periods, and without any "_acme-challenge." prefix.
  61. CertDomains []string
  62. // Peer is the state of each peer, keyed by each peer's current public key.
  63. Peer map[key.NodePublic]*PeerStatus
  64. // User contains profile information about UserIDs referenced by
  65. // PeerStatus.UserID, PeerStatus.AltSharerUserID, etc.
  66. User map[tailcfg.UserID]tailcfg.UserProfile
  67. // ClientVersion, when non-nil, contains information about the latest
  68. // version of the Tailscale client that's available. Depending on
  69. // the platform and client settings, it may not be available.
  70. ClientVersion *tailcfg.ClientVersion
  71. }
  72. // TKAKey describes a key trusted by network lock.
  73. type TKAKey struct {
  74. Key key.NLPublic
  75. Metadata map[string]string
  76. Votes uint
  77. }
  78. // TKAPeer describes a peer and its network lock details.
  79. type TKAPeer struct {
  80. Name string // DNS
  81. ID tailcfg.NodeID
  82. StableID tailcfg.StableNodeID
  83. TailscaleIPs []netip.Addr // Tailscale IP(s) assigned to this node
  84. NodeKey key.NodePublic
  85. NodeKeySignature tka.NodeKeySignature
  86. }
  87. // NetworkLockStatus represents whether network-lock is enabled,
  88. // along with details about the locally-known state of the tailnet
  89. // key authority.
  90. type NetworkLockStatus struct {
  91. // Enabled is true if network lock is enabled.
  92. Enabled bool
  93. // Head describes the AUM hash of the leaf AUM. Head is nil
  94. // if network lock is not enabled.
  95. Head *[32]byte
  96. // PublicKey describes the node's network-lock public key.
  97. // It may be zero if the node has not logged in.
  98. PublicKey key.NLPublic
  99. // NodeKey describes the node's current node-key. This field is not
  100. // populated if the node is not operating (i.e. waiting for a login).
  101. NodeKey *key.NodePublic
  102. // NodeKeySigned is true if our node is authorized by network-lock.
  103. NodeKeySigned bool
  104. // NodeKeySignature is the current signature of this node's key.
  105. NodeKeySignature *tka.NodeKeySignature
  106. // TrustedKeys describes the keys currently trusted to make changes
  107. // to network-lock.
  108. TrustedKeys []TKAKey
  109. // VisiblePeers describes peers which are visible in the netmap that
  110. // have valid Tailnet Lock signatures signatures.
  111. VisiblePeers []*TKAPeer
  112. // FilteredPeers describes peers which were removed from the netmap
  113. // (i.e. no connectivity) because they failed tailnet lock
  114. // checks.
  115. FilteredPeers []*TKAPeer
  116. // StateID is a nonce associated with the network lock authority,
  117. // generated upon enablement. This field is not populated if the
  118. // network lock is disabled.
  119. StateID uint64
  120. }
  121. // NetworkLockUpdate describes a change to network-lock state.
  122. type NetworkLockUpdate struct {
  123. Hash [32]byte
  124. Change string // values of tka.AUMKind.String()
  125. // Raw contains the serialized AUM. The AUM is sent in serialized
  126. // form to avoid transitive dependences bloating this package.
  127. Raw []byte
  128. }
  129. // TailnetStatus is information about a Tailscale network ("tailnet").
  130. type TailnetStatus struct {
  131. // Name is the name of the network that's currently in use.
  132. Name string
  133. // MagicDNSSuffix is the network's MagicDNS suffix for nodes
  134. // in the network such as "userfoo.tailscale.net".
  135. // There are no surrounding dots.
  136. // MagicDNSSuffix should be populated regardless of whether a domain
  137. // has MagicDNS enabled.
  138. MagicDNSSuffix string
  139. // MagicDNSEnabled is whether or not the network has MagicDNS enabled.
  140. // Note that the current device may still not support MagicDNS if
  141. // `--accept-dns=false` was used.
  142. MagicDNSEnabled bool
  143. }
  144. // ExitNodeStatus describes the current exit node.
  145. type ExitNodeStatus struct {
  146. // ID is the exit node's ID.
  147. ID tailcfg.StableNodeID
  148. // Online is whether the exit node is alive.
  149. Online bool
  150. // TailscaleIPs are the exit node's IP addresses assigned to the node.
  151. TailscaleIPs []netip.Prefix
  152. }
  153. func (s *Status) Peers() []key.NodePublic {
  154. kk := make([]key.NodePublic, 0, len(s.Peer))
  155. for k := range s.Peer {
  156. kk = append(kk, k)
  157. }
  158. sort.Slice(kk, func(i, j int) bool { return kk[i].Less(kk[j]) })
  159. return kk
  160. }
  161. type PeerStatusLite struct {
  162. // NodeKey is this peer's public node key.
  163. NodeKey key.NodePublic
  164. // TxBytes/RxBytes are the total number of bytes transmitted to/received
  165. // from this peer.
  166. TxBytes, RxBytes int64
  167. // LastHandshake is the last time a handshake succeeded with this peer. (Or
  168. // we got key confirmation via the first data message, which is
  169. // approximately the same thing.)
  170. //
  171. // The time.Time zero value means that no handshake has succeeded, at least
  172. // since this peer was last known to WireGuard. (Tailscale removes peers
  173. // from the wireguard peer that are idle.)
  174. LastHandshake time.Time
  175. }
  176. // PeerStatus describes a peer node and its current state.
  177. // WARNING: The fields in PeerStatus are merged by the AddPeer method in the StatusBuilder.
  178. // When adding a new field to PeerStatus, you must update AddPeer to handle merging
  179. // the new field. The AddPeer function is responsible for combining multiple updates
  180. // to the same peer, and any new field that is not merged properly may lead to
  181. // inconsistencies or lost data in the peer status.
  182. type PeerStatus struct {
  183. ID tailcfg.StableNodeID
  184. PublicKey key.NodePublic
  185. HostName string // HostInfo's Hostname (not a DNS name or necessarily unique)
  186. // DNSName is the Peer's FQDN. It ends with a dot.
  187. // It has the form "host.<MagicDNSSuffix>."
  188. DNSName string
  189. OS string // HostInfo.OS
  190. UserID tailcfg.UserID
  191. // AltSharerUserID is the user who shared this node
  192. // if it's different than UserID. Otherwise it's zero.
  193. AltSharerUserID tailcfg.UserID `json:",omitempty"`
  194. // TailscaleIPs are the IP addresses assigned to the node.
  195. TailscaleIPs []netip.Addr
  196. // AllowedIPs are IP addresses allowed to route to this node.
  197. AllowedIPs *views.Slice[netip.Prefix] `json:",omitempty"`
  198. // Tags are the list of ACL tags applied to this node.
  199. // See tailscale.com/tailcfg#Node.Tags for more information.
  200. Tags *views.Slice[string] `json:",omitempty"`
  201. // PrimaryRoutes are the routes this node is currently the primary
  202. // subnet router for, as determined by the control plane. It does
  203. // not include the IPs in TailscaleIPs.
  204. PrimaryRoutes *views.Slice[netip.Prefix] `json:",omitempty"`
  205. // Endpoints:
  206. Addrs []string
  207. CurAddr string // one of Addrs, or unique if roaming
  208. Relay string // DERP region
  209. PeerRelay string // peer relay address (ip:port:vni)
  210. RxBytes int64
  211. TxBytes int64
  212. Created time.Time // time registered with tailcontrol
  213. LastWrite time.Time // time last packet sent
  214. LastSeen time.Time // last seen to tailcontrol; only present if offline
  215. LastHandshake time.Time // with local wireguard
  216. Online bool // whether node is connected to the control plane
  217. ExitNode bool // true if this is the currently selected exit node.
  218. ExitNodeOption bool // true if this node can be an exit node (offered && approved)
  219. // Active is whether the node was recently active. The
  220. // definition is somewhat undefined but has historically and
  221. // currently means that there was some packet sent to this
  222. // peer in the past two minutes. That definition is subject to
  223. // change.
  224. Active bool
  225. // PeerAPIURL are the URLs of the node's PeerAPI servers.
  226. PeerAPIURL []string
  227. // TaildropTargetStatus represents the node's eligibility to have files shared to it.
  228. TaildropTarget TaildropTargetStatus
  229. // Reason why this peer cannot receive files. Empty if CanReceiveFiles=true
  230. NoFileSharingReason string
  231. // Capabilities are capabilities that the node has.
  232. // They're free-form strings, but should be in the form of URLs/URIs
  233. // such as:
  234. // "https://tailscale.com/cap/is-admin"
  235. // "https://tailscale.com/cap/file-sharing"
  236. // "funnel"
  237. //
  238. // Deprecated: use CapMap instead. See https://github.com/tailscale/tailscale/issues/11508
  239. // Every value is Capabilities is also a key in CapMap, even if it
  240. // has no values in that map.
  241. Capabilities []tailcfg.NodeCapability `json:",omitempty"`
  242. // CapMap is a map of capabilities to their values.
  243. CapMap tailcfg.NodeCapMap `json:",omitempty"`
  244. // SSH_HostKeys are the node's SSH host keys, if known.
  245. SSH_HostKeys []string `json:"sshHostKeys,omitempty"`
  246. // ShareeNode indicates this node exists in the netmap because
  247. // it's owned by a shared-to user and that node might connect
  248. // to us. These nodes should be hidden by "tailscale status"
  249. // etc by default.
  250. ShareeNode bool `json:",omitempty"`
  251. // InNetworkMap means that this peer was seen in our latest network map.
  252. // In theory, all of InNetworkMap and InMagicSock and InEngine should all be true.
  253. InNetworkMap bool
  254. // InMagicSock means that this peer is being tracked by magicsock.
  255. // In theory, all of InNetworkMap and InMagicSock and InEngine should all be true.
  256. InMagicSock bool
  257. // InEngine means that this peer is tracked by the wireguard engine.
  258. // In theory, all of InNetworkMap and InMagicSock and InEngine should all be true.
  259. InEngine bool
  260. // Expired means that this peer's node key has expired, based on either
  261. // information from control or optimisically set on the client if the
  262. // expiration time has passed.
  263. Expired bool `json:",omitempty"`
  264. // KeyExpiry, if present, is the time at which the node key expired or
  265. // will expire.
  266. KeyExpiry *time.Time `json:",omitempty"`
  267. Location *tailcfg.Location `json:",omitempty"`
  268. }
  269. type TaildropTargetStatus int
  270. const (
  271. TaildropTargetUnknown TaildropTargetStatus = iota
  272. TaildropTargetAvailable
  273. TaildropTargetNoNetmapAvailable
  274. TaildropTargetIpnStateNotRunning
  275. TaildropTargetMissingCap
  276. TaildropTargetOffline
  277. TaildropTargetNoPeerInfo
  278. TaildropTargetUnsupportedOS
  279. TaildropTargetNoPeerAPI
  280. TaildropTargetOwnedByOtherUser
  281. )
  282. // HasCap reports whether ps has the given capability.
  283. func (ps *PeerStatus) HasCap(cap tailcfg.NodeCapability) bool {
  284. return ps.CapMap.Contains(cap)
  285. }
  286. // IsTagged reports whether ps is tagged.
  287. func (ps *PeerStatus) IsTagged() bool {
  288. return ps.Tags != nil && ps.Tags.Len() > 0
  289. }
  290. // StatusBuilder is a request to construct a Status. A new StatusBuilder is
  291. // passed to various subsystems which then call methods on it to populate state.
  292. // Call its Status method to return the final constructed Status.
  293. type StatusBuilder struct {
  294. WantPeers bool // whether caller wants peers
  295. locked bool
  296. st Status
  297. }
  298. // MutateStatus calls f with the status to mutate.
  299. //
  300. // It may not assume other fields of status are already populated, and
  301. // may not retain or write to the Status after f returns.
  302. func (sb *StatusBuilder) MutateStatus(f func(*Status)) {
  303. f(&sb.st)
  304. }
  305. // Status returns the status that has been built up so far from previous
  306. // calls to MutateStatus, MutateSelfStatus, AddPeer, etc.
  307. func (sb *StatusBuilder) Status() *Status {
  308. sb.locked = true
  309. return &sb.st
  310. }
  311. // MutateSelfStatus calls f with the PeerStatus of our own node to mutate.
  312. //
  313. // It may not assume other fields of status are already populated, and
  314. // may not retain or write to the Status after f returns.
  315. //
  316. // MutateStatus acquires a lock so f must not call back into sb.
  317. func (sb *StatusBuilder) MutateSelfStatus(f func(*PeerStatus)) {
  318. if sb.st.Self == nil {
  319. sb.st.Self = new(PeerStatus)
  320. }
  321. f(sb.st.Self)
  322. }
  323. // AddUser adds a user profile to the status.
  324. func (sb *StatusBuilder) AddUser(id tailcfg.UserID, up tailcfg.UserProfileView) {
  325. if sb.locked {
  326. log.Printf("[unexpected] ipnstate: AddUser after Locked")
  327. return
  328. }
  329. if sb.st.User == nil {
  330. sb.st.User = make(map[tailcfg.UserID]tailcfg.UserProfile)
  331. }
  332. sb.st.User[id] = *up.AsStruct()
  333. }
  334. // AddIP adds a Tailscale IP address to the status.
  335. func (sb *StatusBuilder) AddTailscaleIP(ip netip.Addr) {
  336. if sb.locked {
  337. log.Printf("[unexpected] ipnstate: AddIP after Locked")
  338. return
  339. }
  340. sb.st.TailscaleIPs = append(sb.st.TailscaleIPs, ip)
  341. }
  342. // AddPeer adds a peer node to the status.
  343. //
  344. // Its PeerStatus is mixed with any previous status already added.
  345. func (sb *StatusBuilder) AddPeer(peer key.NodePublic, st *PeerStatus) {
  346. if st == nil {
  347. panic("nil PeerStatus")
  348. }
  349. if sb.locked {
  350. log.Printf("[unexpected] ipnstate: AddPeer after Locked")
  351. return
  352. }
  353. if sb.st.Peer == nil {
  354. sb.st.Peer = make(map[key.NodePublic]*PeerStatus)
  355. }
  356. e, ok := sb.st.Peer[peer]
  357. if !ok {
  358. sb.st.Peer[peer] = st
  359. st.PublicKey = peer
  360. return
  361. }
  362. if v := st.ID; v != "" {
  363. e.ID = v
  364. }
  365. if v := st.HostName; v != "" {
  366. e.HostName = v
  367. }
  368. if v := st.DNSName; v != "" {
  369. e.DNSName = v
  370. }
  371. if v := st.Relay; v != "" {
  372. e.Relay = v
  373. }
  374. if v := st.PeerRelay; v != "" {
  375. e.PeerRelay = v
  376. }
  377. if v := st.UserID; v != 0 {
  378. e.UserID = v
  379. }
  380. if v := st.AltSharerUserID; v != 0 {
  381. e.AltSharerUserID = v
  382. }
  383. if v := st.TailscaleIPs; v != nil {
  384. e.TailscaleIPs = v
  385. }
  386. if v := st.PrimaryRoutes; v != nil && !v.IsNil() {
  387. e.PrimaryRoutes = v
  388. }
  389. if v := st.AllowedIPs; v != nil && !v.IsNil() {
  390. e.AllowedIPs = v
  391. }
  392. if v := st.Tags; v != nil && !v.IsNil() {
  393. e.Tags = v
  394. }
  395. if v := st.OS; v != "" {
  396. e.OS = st.OS
  397. }
  398. if v := st.SSH_HostKeys; v != nil {
  399. e.SSH_HostKeys = v
  400. }
  401. if v := st.Addrs; v != nil {
  402. e.Addrs = v
  403. }
  404. if v := st.CurAddr; v != "" {
  405. e.CurAddr = v
  406. }
  407. if v := st.RxBytes; v != 0 {
  408. e.RxBytes = v
  409. }
  410. if v := st.TxBytes; v != 0 {
  411. e.TxBytes = v
  412. }
  413. if v := st.LastHandshake; !v.IsZero() {
  414. e.LastHandshake = v
  415. }
  416. if v := st.Created; !v.IsZero() {
  417. e.Created = v
  418. }
  419. if v := st.LastSeen; !v.IsZero() {
  420. e.LastSeen = v
  421. }
  422. if v := st.LastWrite; !v.IsZero() {
  423. e.LastWrite = v
  424. }
  425. if st.Online {
  426. e.Online = true
  427. }
  428. if st.InNetworkMap {
  429. e.InNetworkMap = true
  430. }
  431. if st.InMagicSock {
  432. e.InMagicSock = true
  433. }
  434. if st.InEngine {
  435. e.InEngine = true
  436. }
  437. if st.ExitNode {
  438. e.ExitNode = true
  439. }
  440. if st.ExitNodeOption {
  441. e.ExitNodeOption = true
  442. }
  443. if st.ShareeNode {
  444. e.ShareeNode = true
  445. }
  446. if st.Active {
  447. e.Active = true
  448. }
  449. if st.PeerAPIURL != nil {
  450. e.PeerAPIURL = st.PeerAPIURL
  451. }
  452. if st.Expired {
  453. e.Expired = true
  454. }
  455. if t := st.KeyExpiry; t != nil {
  456. e.KeyExpiry = ptr.To(*t)
  457. }
  458. if v := st.CapMap; v != nil {
  459. e.CapMap = v
  460. }
  461. if v := st.Capabilities; v != nil {
  462. e.Capabilities = v
  463. }
  464. if v := st.TaildropTarget; v != TaildropTargetUnknown {
  465. e.TaildropTarget = v
  466. }
  467. e.Location = st.Location
  468. }
  469. type StatusUpdater interface {
  470. UpdateStatus(*StatusBuilder)
  471. }
  472. func (st *Status) WriteHTML(w io.Writer) {
  473. f := func(format string, args ...any) { fmt.Fprintf(w, format, args...) }
  474. f(`<!DOCTYPE html>
  475. <html lang="en">
  476. <head>
  477. <meta name="viewport" content="width=device-width,initial-scale=1">
  478. <title>Tailscale State</title>
  479. <style>
  480. body { font-family: monospace; }
  481. .owner { text-decoration: underline; }
  482. .tailaddr { font-style: italic; }
  483. .acenter { text-align: center; }
  484. .aright { text-align: right; }
  485. table, th, td { border: 1px solid black; border-spacing : 0; border-collapse : collapse; }
  486. thead { background-color: #FFA500; }
  487. th, td { padding: 5px; }
  488. td { vertical-align: top; }
  489. table tbody tr:nth-child(even) td { background-color: #f5f5f5; }
  490. </style>
  491. </head>
  492. <body>
  493. <h1>Tailscale State</h1>
  494. `)
  495. //f("<p><b>logid:</b> %s</p>\n", logid)
  496. //f("<p><b>opts:</b> <code>%s</code></p>\n", html.EscapeString(fmt.Sprintf("%+v", opts)))
  497. ips := make([]string, 0, len(st.TailscaleIPs))
  498. for _, ip := range st.TailscaleIPs {
  499. ips = append(ips, ip.String())
  500. }
  501. f("<p>Tailscale IP: %s", strings.Join(ips, ", "))
  502. f("<table>\n<thead>\n")
  503. f("<tr><th>Peer</th><th>OS</th><th>Node</th><th>Owner</th><th>Rx</th><th>Tx</th><th>Activity</th><th>Connection</th></tr>\n")
  504. f("</thead>\n<tbody>\n")
  505. now := time.Now()
  506. var peers []*PeerStatus
  507. for _, peer := range st.Peers() {
  508. ps := st.Peer[peer]
  509. if ps.ShareeNode {
  510. continue
  511. }
  512. peers = append(peers, ps)
  513. }
  514. SortPeers(peers)
  515. for _, ps := range peers {
  516. var actAgo string
  517. if !ps.LastWrite.IsZero() {
  518. ago := now.Sub(ps.LastWrite)
  519. actAgo = ago.Round(time.Second).String() + " ago"
  520. if ago < 5*time.Minute {
  521. actAgo = "<b>" + actAgo + "</b>"
  522. }
  523. }
  524. var owner string
  525. if up, ok := st.User[ps.UserID]; ok {
  526. owner = up.LoginName
  527. if i := strings.Index(owner, "@"); i != -1 {
  528. owner = owner[:i]
  529. }
  530. }
  531. hostName := dnsname.SanitizeHostname(ps.HostName)
  532. dnsName := dnsname.TrimSuffix(ps.DNSName, st.MagicDNSSuffix)
  533. if strings.EqualFold(dnsName, hostName) || ps.UserID != st.Self.UserID {
  534. hostName = ""
  535. }
  536. var hostNameHTML string
  537. if hostName != "" {
  538. hostNameHTML = "<br>" + html.EscapeString(hostName)
  539. }
  540. var tailAddr string
  541. if len(ps.TailscaleIPs) > 0 {
  542. tailAddr = ps.TailscaleIPs[0].String()
  543. }
  544. f("<tr><td>%s</td><td class=acenter>%s</td>"+
  545. "<td><b>%s</b>%s<div class=\"tailaddr\">%s</div></td><td class=\"acenter owner\">%s</td><td class=\"aright\">%v</td><td class=\"aright\">%v</td><td class=\"aright\">%v</td>",
  546. ps.PublicKey.ShortString(),
  547. osEmoji(ps.OS),
  548. html.EscapeString(dnsName),
  549. hostNameHTML,
  550. tailAddr,
  551. html.EscapeString(owner),
  552. ps.RxBytes,
  553. ps.TxBytes,
  554. actAgo,
  555. )
  556. f("<td>")
  557. if ps.Active {
  558. if ps.Relay != "" && ps.CurAddr == "" {
  559. f("relay <b>%s</b>", html.EscapeString(ps.Relay))
  560. } else if ps.CurAddr != "" {
  561. f("direct <b>%s</b>", html.EscapeString(ps.CurAddr))
  562. }
  563. }
  564. f("</td>") // end Addrs
  565. f("</tr>\n")
  566. }
  567. f("</tbody>\n</table>\n")
  568. f("</body>\n</html>\n")
  569. }
  570. func osEmoji(os string) string {
  571. switch os {
  572. case "linux":
  573. return "🐧"
  574. case "macOS":
  575. return "🍎"
  576. case "windows":
  577. return "🖥️"
  578. case "iOS":
  579. return "📱"
  580. case "tvOS":
  581. return "🍎📺"
  582. case "android":
  583. return "🤖"
  584. case "freebsd":
  585. return "👿"
  586. case "openbsd":
  587. return "🐡"
  588. case "illumos":
  589. return "☀️"
  590. case "solaris":
  591. return "🌤️"
  592. }
  593. return "👽"
  594. }
  595. // PingResult contains response information for the "tailscale ping" subcommand,
  596. // saying how Tailscale can reach a Tailscale IP or subnet-routed IP.
  597. // See tailcfg.PingResponse for a related response that is sent back to control
  598. // for remote diagnostic pings.
  599. type PingResult struct {
  600. IP string // ping destination
  601. NodeIP string // Tailscale IP of node handling IP (different for subnet routers)
  602. NodeName string // DNS name base or (possibly not unique) hostname
  603. Err string
  604. LatencySeconds float64
  605. // Endpoint is a string of the form "{ip}:{port}" if direct UDP was used. It
  606. // is not currently set for TSMP.
  607. Endpoint string
  608. // PeerRelay is a string of the form "{ip}:{port}:vni:{vni}" if a peer
  609. // relay was used. It is not currently set for TSMP. Note that this field
  610. // is not omitted during JSON encoding if it contains a zero value. This is
  611. // done for consistency with the Endpoint field; this structure is exposed
  612. // externally via localAPI, so we want to maintain the existing convention.
  613. PeerRelay string
  614. // DERPRegionID is non-zero DERP region ID if DERP was used.
  615. // It is not currently set for TSMP pings.
  616. DERPRegionID int
  617. // DERPRegionCode is the three-letter region code
  618. // corresponding to DERPRegionID.
  619. // It is not currently set for TSMP pings.
  620. DERPRegionCode string
  621. // PeerAPIPort is set by TSMP ping responses for peers that
  622. // are running a peerapi server. This is the port they're
  623. // running the server on.
  624. PeerAPIPort uint16 `json:",omitempty"`
  625. // PeerAPIURL is the URL that was hit for pings of type "peerapi" (tailcfg.PingPeerAPI).
  626. // It's of the form "http://ip:port" (or [ip]:port for IPv6).
  627. PeerAPIURL string `json:",omitempty"`
  628. // IsLocalIP is whether the ping request error is due to it being
  629. // a ping to the local node.
  630. IsLocalIP bool `json:",omitempty"`
  631. // TODO(bradfitz): details like whether port mapping was used on either side? (Once supported)
  632. }
  633. func (pr *PingResult) ToPingResponse(pingType tailcfg.PingType) *tailcfg.PingResponse {
  634. return &tailcfg.PingResponse{
  635. Type: pingType,
  636. IP: pr.IP,
  637. NodeIP: pr.NodeIP,
  638. NodeName: pr.NodeName,
  639. Err: pr.Err,
  640. LatencySeconds: pr.LatencySeconds,
  641. Endpoint: pr.Endpoint,
  642. PeerRelay: pr.PeerRelay,
  643. DERPRegionID: pr.DERPRegionID,
  644. DERPRegionCode: pr.DERPRegionCode,
  645. PeerAPIPort: pr.PeerAPIPort,
  646. IsLocalIP: pr.IsLocalIP,
  647. }
  648. }
  649. // SortPeers sorts peers by either their DNS name, hostname, Tailscale IP,
  650. // or ultimately their current public key.
  651. func SortPeers(peers []*PeerStatus) {
  652. slices.SortStableFunc(peers, (*PeerStatus).compare)
  653. }
  654. func (a *PeerStatus) compare(b *PeerStatus) int {
  655. if a.DNSName != "" || b.DNSName != "" {
  656. if v := strings.Compare(a.DNSName, b.DNSName); v != 0 {
  657. return v
  658. }
  659. }
  660. if a.HostName != "" || b.HostName != "" {
  661. if v := strings.Compare(a.HostName, b.HostName); v != 0 {
  662. return v
  663. }
  664. }
  665. if len(a.TailscaleIPs) > 0 && len(b.TailscaleIPs) > 0 {
  666. if v := a.TailscaleIPs[0].Compare(b.TailscaleIPs[0]); v != 0 {
  667. return v
  668. }
  669. }
  670. return a.PublicKey.Compare(b.PublicKey)
  671. }
  672. // DebugDERPRegionReport is the result of a "tailscale debug derp" command,
  673. // to let people debug a custom DERP setup.
  674. type DebugDERPRegionReport struct {
  675. Info []string
  676. Warnings []string
  677. Errors []string
  678. }
  679. type SelfUpdateStatus string
  680. const (
  681. UpdateFinished SelfUpdateStatus = "UpdateFinished"
  682. UpdateInProgress SelfUpdateStatus = "UpdateInProgress"
  683. UpdateFailed SelfUpdateStatus = "UpdateFailed"
  684. )
  685. type UpdateProgress struct {
  686. Status SelfUpdateStatus `json:"status,omitempty"`
  687. Message string `json:"message,omitempty"`
  688. Version string `json:"version,omitempty"`
  689. }
  690. func NewUpdateProgress(ps SelfUpdateStatus, msg string) UpdateProgress {
  691. return UpdateProgress{
  692. Status: ps,
  693. Message: msg,
  694. Version: version.Short(),
  695. }
  696. }