backend.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. // Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package ipn
  5. import (
  6. "fmt"
  7. "strings"
  8. "time"
  9. "tailscale.com/ipn/ipnstate"
  10. "tailscale.com/tailcfg"
  11. "tailscale.com/types/empty"
  12. "tailscale.com/types/key"
  13. "tailscale.com/types/netmap"
  14. "tailscale.com/types/structs"
  15. )
  16. type State int
  17. const (
  18. NoState State = 0
  19. InUseOtherUser State = 1
  20. NeedsLogin State = 2
  21. NeedsMachineAuth State = 3
  22. Stopped State = 4
  23. Starting State = 5
  24. Running State = 6
  25. )
  26. // GoogleIDToken Type is the tailcfg.Oauth2Token.TokenType for the Google
  27. // ID tokens used by the Android client.
  28. const GoogleIDTokenType = "ts_android_google_login"
  29. func (s State) String() string {
  30. return [...]string{
  31. "NoState",
  32. "InUseOtherUser",
  33. "NeedsLogin",
  34. "NeedsMachineAuth",
  35. "Stopped",
  36. "Starting",
  37. "Running"}[s]
  38. }
  39. // EngineStatus contains WireGuard engine stats.
  40. type EngineStatus struct {
  41. RBytes, WBytes int64
  42. NumLive int
  43. LiveDERPs int // number of active DERP connections
  44. LivePeers map[key.NodePublic]ipnstate.PeerStatusLite
  45. }
  46. // Notify is a communication from a backend (e.g. tailscaled) to a frontend
  47. // (cmd/tailscale, iOS, macOS, Win Tasktray).
  48. // In any given notification, any or all of these may be nil, meaning
  49. // that they have not changed.
  50. // They are JSON-encoded on the wire, despite the lack of struct tags.
  51. type Notify struct {
  52. _ structs.Incomparable
  53. Version string // version number of IPN backend
  54. // ErrMessage, if non-nil, contains a critical error message.
  55. // For State InUseOtherUser, ErrMessage is not critical and just contains the details.
  56. ErrMessage *string
  57. LoginFinished *empty.Message // non-nil when/if the login process succeeded
  58. State *State // if non-nil, the new or current IPN state
  59. Prefs *PrefsView // if non-nil && Valid, the new or current preferences
  60. NetMap *netmap.NetworkMap // if non-nil, the new or current netmap
  61. Engine *EngineStatus // if non-nil, the new or current wireguard stats
  62. BrowseToURL *string // if non-nil, UI should open a browser right now
  63. BackendLogID *string // if non-nil, the public logtail ID used by backend
  64. // FilesWaiting if non-nil means that files are buffered in
  65. // the Tailscale daemon and ready for local transfer to the
  66. // user's preferred storage location.
  67. FilesWaiting *empty.Message `json:",omitempty"`
  68. // IncomingFiles, if non-nil, specifies which files are in the
  69. // process of being received. A nil IncomingFiles means this
  70. // Notify should not update the state of file transfers. A non-nil
  71. // but empty IncomingFiles means that no files are in the middle
  72. // of being transferred.
  73. IncomingFiles []PartialFile `json:",omitempty"`
  74. // LocalTCPPort, if non-nil, informs the UI frontend which
  75. // (non-zero) localhost TCP port it's listening on.
  76. // This is currently only used by Tailscale when run in the
  77. // macOS Network Extension.
  78. LocalTCPPort *uint16 `json:",omitempty"`
  79. // type is mirrored in xcode/Shared/IPN.swift
  80. }
  81. func (n Notify) String() string {
  82. var sb strings.Builder
  83. sb.WriteString("Notify{")
  84. if n.ErrMessage != nil {
  85. fmt.Fprintf(&sb, "err=%q ", *n.ErrMessage)
  86. }
  87. if n.LoginFinished != nil {
  88. sb.WriteString("LoginFinished ")
  89. }
  90. if n.State != nil {
  91. fmt.Fprintf(&sb, "state=%v ", *n.State)
  92. }
  93. if n.Prefs != nil && n.Prefs.Valid() {
  94. fmt.Fprintf(&sb, "%v ", n.Prefs.Pretty())
  95. }
  96. if n.NetMap != nil {
  97. sb.WriteString("NetMap{...} ")
  98. }
  99. if n.Engine != nil {
  100. fmt.Fprintf(&sb, "wg=%v ", *n.Engine)
  101. }
  102. if n.BrowseToURL != nil {
  103. sb.WriteString("URL=<...> ")
  104. }
  105. if n.BackendLogID != nil {
  106. sb.WriteString("BackendLogID ")
  107. }
  108. if n.FilesWaiting != nil {
  109. sb.WriteString("FilesWaiting ")
  110. }
  111. if len(n.IncomingFiles) != 0 {
  112. sb.WriteString("IncomingFiles ")
  113. }
  114. if n.LocalTCPPort != nil {
  115. fmt.Fprintf(&sb, "tcpport=%v ", n.LocalTCPPort)
  116. }
  117. s := sb.String()
  118. return s[0:len(s)-1] + "}"
  119. }
  120. // PartialFile represents an in-progress file transfer.
  121. type PartialFile struct {
  122. Name string // e.g. "foo.jpg"
  123. Started time.Time // time transfer started
  124. DeclaredSize int64 // or -1 if unknown
  125. Received int64 // bytes copied thus far
  126. // PartialPath is set non-empty in "direct" file mode to the
  127. // in-progress '*.partial' file's path when the peerapi isn't
  128. // being used; see LocalBackend.SetDirectFileRoot.
  129. PartialPath string `json:",omitempty"`
  130. // Done is set in "direct" mode when the partial file has been
  131. // closed and is ready for the caller to rename away the
  132. // ".partial" suffix.
  133. Done bool `json:",omitempty"`
  134. }
  135. // StateKey is an opaque identifier for a set of LocalBackend state
  136. // (preferences, private keys, etc.). It is also used as a key for
  137. // the various LoginProfiles that the instance may be signed into.
  138. //
  139. // Additionally, the StateKey can be debug setting name:
  140. //
  141. // - "_debug_magicsock_until" with value being a unix timestamp stringified
  142. // - "_debug_<component>_until" with value being a unix timestamp stringified
  143. type StateKey string
  144. type Options struct {
  145. // FrontendLogID is the public logtail id used by the frontend.
  146. FrontendLogID string
  147. // LegacyMigrationPrefs are used to migrate preferences from the
  148. // frontend to the backend.
  149. // If non-nil, they are imported as a new profile.
  150. LegacyMigrationPrefs *Prefs `json:"Prefs"`
  151. // UpdatePrefs, if provided, overrides Options.Prefs *and* the Prefs
  152. // already stored in the backend state, *except* for the Persist
  153. // Persist member. If you just want to provide prefs, this is
  154. // probably what you want.
  155. //
  156. // UpdatePrefs.Persist is always ignored. Prefs.Persist will still
  157. // be used even if UpdatePrefs is provided. Other than Persist,
  158. // UpdatePrefs takes precedence over Prefs.
  159. //
  160. // This is intended as a purely temporary workaround for the
  161. // currently unexpected behaviour of Options.Prefs.
  162. //
  163. // TODO(apenwarr): Remove this, or rename Prefs to something else
  164. // and rename this to Prefs. Or, move Prefs.Persist elsewhere
  165. // entirely (as it always should have been), and then we wouldn't
  166. // need two separate fields at all. Or, move the fancy state
  167. // migration stuff out of Start().
  168. UpdatePrefs *Prefs
  169. // AuthKey is an optional node auth key used to authorize a
  170. // new node key without user interaction.
  171. AuthKey string
  172. }
  173. // Backend is the interface between Tailscale frontends
  174. // (e.g. cmd/tailscale, iOS/MacOS/Windows GUIs) and the tailscale
  175. // backend (e.g. cmd/tailscaled) running on the same machine.
  176. // (It has nothing to do with the interface between the backends
  177. // and the cloud control plane.)
  178. type Backend interface {
  179. // SetNotifyCallback sets the callback to be called on updates
  180. // from the backend to the client.
  181. SetNotifyCallback(func(Notify))
  182. // Start starts or restarts the backend, typically when a
  183. // frontend client connects.
  184. Start(Options) error
  185. // StartLoginInteractive requests to start a new interactive login
  186. // flow. This should trigger a new BrowseToURL notification
  187. // eventually.
  188. StartLoginInteractive()
  189. // Login logs in with an OAuth2 token.
  190. Login(token *tailcfg.Oauth2Token)
  191. // Logout terminates the current login session and stops the
  192. // wireguard engine.
  193. Logout()
  194. // SetPrefs installs a new set of user preferences, including
  195. // WantRunning. This may cause the wireguard engine to
  196. // reconfigure or stop.
  197. SetPrefs(*Prefs)
  198. // RequestEngineStatus polls for an update from the wireguard
  199. // engine. Only needed if you want to display byte
  200. // counts. Connection events are emitted automatically without
  201. // polling.
  202. RequestEngineStatus()
  203. }