hostinfo.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package hostinfo answers questions about the host environment that Tailscale is
  4. // running on.
  5. package hostinfo
  6. import (
  7. "bufio"
  8. "io"
  9. "os"
  10. "runtime"
  11. "runtime/debug"
  12. "strings"
  13. "sync"
  14. "sync/atomic"
  15. "time"
  16. "go4.org/mem"
  17. "tailscale.com/envknob"
  18. "tailscale.com/tailcfg"
  19. "tailscale.com/types/opt"
  20. "tailscale.com/types/ptr"
  21. "tailscale.com/util/cloudenv"
  22. "tailscale.com/util/dnsname"
  23. "tailscale.com/util/lineread"
  24. "tailscale.com/version"
  25. )
  26. var started = time.Now()
  27. // New returns a partially populated Hostinfo for the current host.
  28. func New() *tailcfg.Hostinfo {
  29. hostname, _ := os.Hostname()
  30. hostname = dnsname.FirstLabel(hostname)
  31. return &tailcfg.Hostinfo{
  32. IPNVersion: version.Long(),
  33. Hostname: hostname,
  34. App: appTypeCached(),
  35. OS: version.OS(),
  36. OSVersion: GetOSVersion(),
  37. Container: lazyInContainer.Get(),
  38. Distro: condCall(distroName),
  39. DistroVersion: condCall(distroVersion),
  40. DistroCodeName: condCall(distroCodeName),
  41. Env: string(GetEnvType()),
  42. Desktop: desktop(),
  43. Package: packageTypeCached(),
  44. GoArch: runtime.GOARCH,
  45. GoArchVar: lazyGoArchVar.Get(),
  46. GoVersion: runtime.Version(),
  47. Machine: condCall(unameMachine),
  48. DeviceModel: deviceModel(),
  49. PushDeviceToken: pushDeviceToken(),
  50. Cloud: string(cloudenv.Get()),
  51. NoLogsNoSupport: envknob.NoLogsNoSupport(),
  52. AllowsUpdate: envknob.AllowsRemoteUpdate(),
  53. }
  54. }
  55. // non-nil on some platforms
  56. var (
  57. osVersion func() string
  58. packageType func() string
  59. distroName func() string
  60. distroVersion func() string
  61. distroCodeName func() string
  62. unameMachine func() string
  63. )
  64. func condCall[T any](fn func() T) T {
  65. var zero T
  66. if fn == nil {
  67. return zero
  68. }
  69. return fn()
  70. }
  71. var (
  72. lazyInContainer = &lazyAtomicValue[opt.Bool]{f: ptr.To(inContainer)}
  73. lazyGoArchVar = &lazyAtomicValue[string]{f: ptr.To(goArchVar)}
  74. )
  75. type lazyAtomicValue[T any] struct {
  76. // f is a pointer to a fill function. If it's nil or points
  77. // to nil, then Get returns the zero value for T.
  78. f *func() T
  79. once sync.Once
  80. v T
  81. }
  82. func (v *lazyAtomicValue[T]) Get() T {
  83. v.once.Do(v.fill)
  84. return v.v
  85. }
  86. func (v *lazyAtomicValue[T]) fill() {
  87. if v.f == nil || *v.f == nil {
  88. return
  89. }
  90. v.v = (*v.f)()
  91. }
  92. // GetOSVersion returns the OSVersion of current host if available.
  93. func GetOSVersion() string {
  94. if s, _ := osVersionAtomic.Load().(string); s != "" {
  95. return s
  96. }
  97. if osVersion != nil {
  98. return osVersion()
  99. }
  100. return ""
  101. }
  102. func appTypeCached() string {
  103. if v, ok := appType.Load().(string); ok {
  104. return v
  105. }
  106. return ""
  107. }
  108. func packageTypeCached() string {
  109. if v, _ := packagingType.Load().(string); v != "" {
  110. return v
  111. }
  112. if packageType == nil {
  113. return ""
  114. }
  115. v := packageType()
  116. if v != "" {
  117. SetPackage(v)
  118. }
  119. return v
  120. }
  121. // EnvType represents a known environment type.
  122. // The empty string, the default, means unknown.
  123. type EnvType string
  124. const (
  125. KNative = EnvType("kn")
  126. AWSLambda = EnvType("lm")
  127. Heroku = EnvType("hr")
  128. AzureAppService = EnvType("az")
  129. AWSFargate = EnvType("fg")
  130. FlyDotIo = EnvType("fly")
  131. Kubernetes = EnvType("k8s")
  132. DockerDesktop = EnvType("dde")
  133. Replit = EnvType("repl")
  134. )
  135. var envType atomic.Value // of EnvType
  136. func GetEnvType() EnvType {
  137. if e, ok := envType.Load().(EnvType); ok {
  138. return e
  139. }
  140. e := getEnvType()
  141. envType.Store(e)
  142. return e
  143. }
  144. var (
  145. pushDeviceTokenAtomic atomic.Value // of string
  146. deviceModelAtomic atomic.Value // of string
  147. osVersionAtomic atomic.Value // of string
  148. desktopAtomic atomic.Value // of opt.Bool
  149. packagingType atomic.Value // of string
  150. appType atomic.Value // of string
  151. )
  152. // SetPushDeviceToken sets the device token for use in Hostinfo updates.
  153. func SetPushDeviceToken(token string) { pushDeviceTokenAtomic.Store(token) }
  154. // SetDeviceModel sets the device model for use in Hostinfo updates.
  155. func SetDeviceModel(model string) { deviceModelAtomic.Store(model) }
  156. // SetOSVersion sets the OS version.
  157. func SetOSVersion(v string) { osVersionAtomic.Store(v) }
  158. // SetPackage sets the packaging type for the app.
  159. //
  160. // As of 2022-03-25, this is used by Android ("nogoogle" for the
  161. // F-Droid build) and tsnet (set to "tsnet").
  162. func SetPackage(v string) { packagingType.Store(v) }
  163. // SetApp sets the app type for the app.
  164. // It is used by tsnet to specify what app is using it such as "golinks"
  165. // and "k8s-operator".
  166. func SetApp(v string) { appType.Store(v) }
  167. func deviceModel() string {
  168. s, _ := deviceModelAtomic.Load().(string)
  169. return s
  170. }
  171. func pushDeviceToken() string {
  172. s, _ := pushDeviceTokenAtomic.Load().(string)
  173. return s
  174. }
  175. func desktop() (ret opt.Bool) {
  176. if runtime.GOOS != "linux" {
  177. return opt.Bool("")
  178. }
  179. if v := desktopAtomic.Load(); v != nil {
  180. v, _ := v.(opt.Bool)
  181. return v
  182. }
  183. seenDesktop := false
  184. lineread.File("/proc/net/unix", func(line []byte) error {
  185. seenDesktop = seenDesktop || mem.Contains(mem.B(line), mem.S(" @/tmp/dbus-"))
  186. seenDesktop = seenDesktop || mem.Contains(mem.B(line), mem.S(".X11-unix"))
  187. seenDesktop = seenDesktop || mem.Contains(mem.B(line), mem.S("/wayland-1"))
  188. return nil
  189. })
  190. ret.Set(seenDesktop)
  191. // Only cache after a minute - compositors might not have started yet.
  192. if time.Since(started) > time.Minute {
  193. desktopAtomic.Store(ret)
  194. }
  195. return ret
  196. }
  197. func getEnvType() EnvType {
  198. if inKnative() {
  199. return KNative
  200. }
  201. if inAWSLambda() {
  202. return AWSLambda
  203. }
  204. if inHerokuDyno() {
  205. return Heroku
  206. }
  207. if inAzureAppService() {
  208. return AzureAppService
  209. }
  210. if inAWSFargate() {
  211. return AWSFargate
  212. }
  213. if inFlyDotIo() {
  214. return FlyDotIo
  215. }
  216. if inKubernetes() {
  217. return Kubernetes
  218. }
  219. if inDockerDesktop() {
  220. return DockerDesktop
  221. }
  222. if inReplit() {
  223. return Replit
  224. }
  225. return ""
  226. }
  227. // inContainer reports whether we're running in a container.
  228. func inContainer() opt.Bool {
  229. if runtime.GOOS != "linux" {
  230. return ""
  231. }
  232. var ret opt.Bool
  233. ret.Set(false)
  234. if _, err := os.Stat("/.dockerenv"); err == nil {
  235. ret.Set(true)
  236. return ret
  237. }
  238. if _, err := os.Stat("/run/.containerenv"); err == nil {
  239. // See https://github.com/cri-o/cri-o/issues/5461
  240. ret.Set(true)
  241. return ret
  242. }
  243. lineread.File("/proc/1/cgroup", func(line []byte) error {
  244. if mem.Contains(mem.B(line), mem.S("/docker/")) ||
  245. mem.Contains(mem.B(line), mem.S("/lxc/")) {
  246. ret.Set(true)
  247. return io.EOF // arbitrary non-nil error to stop loop
  248. }
  249. return nil
  250. })
  251. lineread.File("/proc/mounts", func(line []byte) error {
  252. if mem.Contains(mem.B(line), mem.S("fuse.lxcfs")) {
  253. ret.Set(true)
  254. return io.EOF
  255. }
  256. return nil
  257. })
  258. return ret
  259. }
  260. func inKnative() bool {
  261. // https://cloud.google.com/run/docs/reference/container-contract#env-vars
  262. if os.Getenv("K_REVISION") != "" && os.Getenv("K_CONFIGURATION") != "" &&
  263. os.Getenv("K_SERVICE") != "" && os.Getenv("PORT") != "" {
  264. return true
  265. }
  266. return false
  267. }
  268. func inAWSLambda() bool {
  269. // https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html
  270. if os.Getenv("AWS_LAMBDA_FUNCTION_NAME") != "" &&
  271. os.Getenv("AWS_LAMBDA_FUNCTION_VERSION") != "" &&
  272. os.Getenv("AWS_LAMBDA_INITIALIZATION_TYPE") != "" &&
  273. os.Getenv("AWS_LAMBDA_RUNTIME_API") != "" {
  274. return true
  275. }
  276. return false
  277. }
  278. func inHerokuDyno() bool {
  279. // https://devcenter.heroku.com/articles/dynos#local-environment-variables
  280. if os.Getenv("PORT") != "" && os.Getenv("DYNO") != "" {
  281. return true
  282. }
  283. return false
  284. }
  285. func inAzureAppService() bool {
  286. if os.Getenv("APPSVC_RUN_ZIP") != "" && os.Getenv("WEBSITE_STACK") != "" &&
  287. os.Getenv("WEBSITE_AUTH_AUTO_AAD") != "" {
  288. return true
  289. }
  290. return false
  291. }
  292. func inAWSFargate() bool {
  293. if os.Getenv("AWS_EXECUTION_ENV") == "AWS_ECS_FARGATE" {
  294. return true
  295. }
  296. return false
  297. }
  298. func inFlyDotIo() bool {
  299. if os.Getenv("FLY_APP_NAME") != "" && os.Getenv("FLY_REGION") != "" {
  300. return true
  301. }
  302. return false
  303. }
  304. func inReplit() bool {
  305. // https://docs.replit.com/programming-ide/getting-repl-metadata
  306. if os.Getenv("REPL_OWNER") != "" && os.Getenv("REPL_SLUG") != "" {
  307. return true
  308. }
  309. return false
  310. }
  311. func inKubernetes() bool {
  312. if os.Getenv("KUBERNETES_SERVICE_HOST") != "" && os.Getenv("KUBERNETES_SERVICE_PORT") != "" {
  313. return true
  314. }
  315. return false
  316. }
  317. func inDockerDesktop() bool {
  318. if os.Getenv("TS_HOST_ENV") == "dde" {
  319. return true
  320. }
  321. return false
  322. }
  323. // goArchVar returns the GOARM or GOAMD64 etc value that the binary was built
  324. // with.
  325. func goArchVar() string {
  326. bi, ok := debug.ReadBuildInfo()
  327. if !ok {
  328. return ""
  329. }
  330. // Look for GOARM, GOAMD64, GO386, etc. Note that the little-endian
  331. // "le"-suffixed GOARCH values don't have their own environment variable.
  332. //
  333. // See https://pkg.go.dev/cmd/go#hdr-Environment_variables and the
  334. // "Architecture-specific environment variables" section:
  335. wantKey := "GO" + strings.ToUpper(strings.TrimSuffix(runtime.GOARCH, "le"))
  336. for _, s := range bi.Settings {
  337. if s.Key == wantKey {
  338. return s.Value
  339. }
  340. }
  341. return ""
  342. }
  343. type etcAptSrcResult struct {
  344. mod time.Time
  345. disabled bool
  346. }
  347. var etcAptSrcCache atomic.Value // of etcAptSrcResult
  348. // DisabledEtcAptSource reports whether Ubuntu (or similar) has disabled
  349. // the /etc/apt/sources.list.d/tailscale.list file contents upon upgrade
  350. // to a new release of the distro.
  351. //
  352. // See https://github.com/tailscale/tailscale/issues/3177
  353. func DisabledEtcAptSource() bool {
  354. if runtime.GOOS != "linux" {
  355. return false
  356. }
  357. const path = "/etc/apt/sources.list.d/tailscale.list"
  358. fi, err := os.Stat(path)
  359. if err != nil || !fi.Mode().IsRegular() {
  360. return false
  361. }
  362. mod := fi.ModTime()
  363. if c, ok := etcAptSrcCache.Load().(etcAptSrcResult); ok && c.mod.Equal(mod) {
  364. return c.disabled
  365. }
  366. f, err := os.Open(path)
  367. if err != nil {
  368. return false
  369. }
  370. defer f.Close()
  371. v := etcAptSourceFileIsDisabled(f)
  372. etcAptSrcCache.Store(etcAptSrcResult{mod: mod, disabled: v})
  373. return v
  374. }
  375. func etcAptSourceFileIsDisabled(r io.Reader) bool {
  376. bs := bufio.NewScanner(r)
  377. disabled := false // did we find the "disabled on upgrade" comment?
  378. for bs.Scan() {
  379. line := strings.TrimSpace(bs.Text())
  380. if strings.Contains(line, "# disabled on upgrade") {
  381. disabled = true
  382. }
  383. if line == "" || line[0] == '#' {
  384. continue
  385. }
  386. // Well, it has some contents in it at least.
  387. return false
  388. }
  389. return disabled
  390. }