clientupdate.go 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package clientupdate implements tailscale client update for all supported
  4. // platforms. This package can be used from both tailscaled and tailscale
  5. // binaries.
  6. package clientupdate
  7. import (
  8. "archive/tar"
  9. "bufio"
  10. "bytes"
  11. "compress/gzip"
  12. "context"
  13. "encoding/json"
  14. "errors"
  15. "fmt"
  16. "io"
  17. "maps"
  18. "net/http"
  19. "os"
  20. "os/exec"
  21. "path"
  22. "path/filepath"
  23. "regexp"
  24. "runtime"
  25. "strconv"
  26. "strings"
  27. "tailscale.com/hostinfo"
  28. "tailscale.com/types/lazy"
  29. "tailscale.com/types/logger"
  30. "tailscale.com/util/cmpver"
  31. "tailscale.com/version"
  32. "tailscale.com/version/distro"
  33. )
  34. const (
  35. StableTrack = "stable"
  36. UnstableTrack = "unstable"
  37. )
  38. var CurrentTrack = func() string {
  39. if version.IsUnstableBuild() {
  40. return UnstableTrack
  41. } else {
  42. return StableTrack
  43. }
  44. }()
  45. func versionToTrack(v string) (string, error) {
  46. _, rest, ok := strings.Cut(v, ".")
  47. if !ok {
  48. return "", fmt.Errorf("malformed version %q", v)
  49. }
  50. minorStr, _, ok := strings.Cut(rest, ".")
  51. if !ok {
  52. return "", fmt.Errorf("malformed version %q", v)
  53. }
  54. minor, err := strconv.Atoi(minorStr)
  55. if err != nil {
  56. return "", fmt.Errorf("malformed version %q", v)
  57. }
  58. if minor%2 == 0 {
  59. return "stable", nil
  60. }
  61. return "unstable", nil
  62. }
  63. // Arguments contains arguments needed to run an update.
  64. type Arguments struct {
  65. // Version is the specific version to install.
  66. // Mutually exclusive with Track.
  67. Version string
  68. // Track is the release track to use:
  69. //
  70. // - CurrentTrack will use the latest version from the same track as the
  71. // running binary
  72. // - StableTrack and UnstableTrack will use the latest versions of the
  73. // corresponding tracks
  74. //
  75. // Leaving this empty will use Version or fall back to CurrentTrack if both
  76. // Track and Version are empty.
  77. Track string
  78. // Logf is a logger for update progress messages.
  79. Logf logger.Logf
  80. // Stdout and Stderr should be used for output instead of os.Stdout and
  81. // os.Stderr.
  82. Stdout io.Writer
  83. Stderr io.Writer
  84. // Confirm is called when a new version is available and should return true
  85. // if this new version should be installed. When Confirm returns false, the
  86. // update is aborted.
  87. Confirm func(newVer string) bool
  88. // PkgsAddr is the address of the pkgs server to fetch updates from.
  89. // Defaults to "https://pkgs.tailscale.com".
  90. PkgsAddr string
  91. // ForAutoUpdate should be true when Updater is created in auto-update
  92. // context. When true, NewUpdater returns an error if it cannot be used for
  93. // auto-updates (even if Updater.Update field is non-nil).
  94. ForAutoUpdate bool
  95. }
  96. func (args Arguments) validate() error {
  97. if args.Confirm == nil {
  98. return errors.New("missing Confirm callback in Arguments")
  99. }
  100. if args.Logf == nil {
  101. return errors.New("missing Logf callback in Arguments")
  102. }
  103. if args.Version != "" && args.Track != "" {
  104. return fmt.Errorf("only one of Version(%q) or Track(%q) can be set", args.Version, args.Track)
  105. }
  106. switch args.Track {
  107. case StableTrack, UnstableTrack, "":
  108. // All valid values.
  109. default:
  110. return fmt.Errorf("unsupported track %q", args.Track)
  111. }
  112. return nil
  113. }
  114. type Updater struct {
  115. Arguments
  116. // Update is a platform-specific method that updates the installation. May be
  117. // nil (not all platforms support updates from within Tailscale).
  118. Update func() error
  119. // currentVersion is the short form of the current client version as
  120. // returned by version.Short(), typically "x.y.z". Used for tests to
  121. // override the actual current version.
  122. currentVersion string
  123. }
  124. func NewUpdater(args Arguments) (*Updater, error) {
  125. up := Updater{
  126. Arguments: args,
  127. currentVersion: version.Short(),
  128. }
  129. if up.Stdout == nil {
  130. up.Stdout = os.Stdout
  131. }
  132. if up.Stderr == nil {
  133. up.Stderr = os.Stderr
  134. }
  135. var canAutoUpdate bool
  136. up.Update, canAutoUpdate = up.getUpdateFunction()
  137. if up.Update == nil {
  138. return nil, errors.ErrUnsupported
  139. }
  140. if args.ForAutoUpdate && !canAutoUpdate {
  141. return nil, errors.ErrUnsupported
  142. }
  143. if up.Track == "" {
  144. if up.Version != "" {
  145. var err error
  146. up.Track, err = versionToTrack(args.Version)
  147. if err != nil {
  148. return nil, err
  149. }
  150. } else {
  151. up.Track = CurrentTrack
  152. }
  153. }
  154. if up.Arguments.PkgsAddr == "" {
  155. up.Arguments.PkgsAddr = "https://pkgs.tailscale.com"
  156. }
  157. return &up, nil
  158. }
  159. type updateFunction func() error
  160. func (up *Updater) getUpdateFunction() (fn updateFunction, canAutoUpdate bool) {
  161. hi := hostinfo.New()
  162. // We don't know how to update custom tsnet binaries, it's up to the user.
  163. if hi.Package == "tsnet" {
  164. return nil, false
  165. }
  166. switch runtime.GOOS {
  167. case "windows":
  168. return up.updateWindows, true
  169. case "linux":
  170. switch distro.Get() {
  171. case distro.NixOS:
  172. // NixOS packages are immutable and managed with a system-wide
  173. // configuration.
  174. return up.updateNixos, false
  175. case distro.Synology:
  176. // Synology updates use our own pkgs.tailscale.com instead of the
  177. // Synology Package Center. We should eventually get to a regular
  178. // release cadence with Synology Package Center and use their
  179. // auto-update mechanism.
  180. return up.updateSynology, false
  181. case distro.Debian: // includes Ubuntu
  182. return up.updateDebLike, true
  183. case distro.Arch:
  184. if up.archPackageInstalled() {
  185. // Arch update func just prints a message about how to update,
  186. // it doesn't support auto-updates.
  187. return up.updateArchLike, false
  188. }
  189. return up.updateLinuxBinary, true
  190. case distro.Alpine:
  191. return up.updateAlpineLike, true
  192. case distro.Unraid:
  193. return up.updateUnraid, true
  194. case distro.QNAP:
  195. return up.updateQNAP, true
  196. }
  197. switch {
  198. case haveExecutable("pacman"):
  199. if up.archPackageInstalled() {
  200. // Arch update func just prints a message about how to update,
  201. // it doesn't support auto-updates.
  202. return up.updateArchLike, false
  203. }
  204. return up.updateLinuxBinary, true
  205. case haveExecutable("apt-get"): // TODO(awly): add support for "apt"
  206. // The distro.Debian switch case above should catch most apt-based
  207. // systems, but add this fallback just in case.
  208. return up.updateDebLike, true
  209. case haveExecutable("dnf"):
  210. return up.updateFedoraLike("dnf"), true
  211. case haveExecutable("yum"):
  212. return up.updateFedoraLike("yum"), true
  213. case haveExecutable("apk"):
  214. return up.updateAlpineLike, true
  215. }
  216. // If nothing matched, fall back to tarball updates.
  217. if up.Update == nil {
  218. return up.updateLinuxBinary, true
  219. }
  220. case "darwin":
  221. switch {
  222. case version.IsMacAppStore():
  223. // App store update func just opens the store page, it doesn't
  224. // support auto-updates.
  225. return up.updateMacAppStore, false
  226. case version.IsMacSysExt():
  227. // Macsys update func kicks off Sparkle. Auto-updates are done by
  228. // Sparkle.
  229. return up.updateMacSys, false
  230. default:
  231. return nil, false
  232. }
  233. case "freebsd":
  234. return up.updateFreeBSD, true
  235. }
  236. return nil, false
  237. }
  238. var canAutoUpdateCache lazy.SyncValue[bool]
  239. // CanAutoUpdate reports whether auto-updating via the clientupdate package
  240. // is supported for the current os/distro.
  241. func CanAutoUpdate() bool { return canAutoUpdateCache.Get(canAutoUpdateUncached) }
  242. func canAutoUpdateUncached() bool {
  243. if version.IsMacSysExt() {
  244. // Macsys uses Sparkle for auto-updates, which doesn't have an update
  245. // function in this package.
  246. return true
  247. }
  248. _, canAutoUpdate := (&Updater{}).getUpdateFunction()
  249. return canAutoUpdate
  250. }
  251. // Update runs a single update attempt using the platform-specific mechanism.
  252. //
  253. // On Windows, this copies the calling binary and re-executes it to apply the
  254. // update. The calling binary should handle an "update" subcommand and call
  255. // this function again for the re-executed binary to proceed.
  256. func Update(args Arguments) error {
  257. if err := args.validate(); err != nil {
  258. return err
  259. }
  260. up, err := NewUpdater(args)
  261. if err != nil {
  262. return err
  263. }
  264. return up.Update()
  265. }
  266. func (up *Updater) confirm(ver string) bool {
  267. // Only check version when we're not switching tracks.
  268. if up.Track == "" || up.Track == CurrentTrack {
  269. switch c := cmpver.Compare(up.currentVersion, ver); {
  270. case c == 0:
  271. up.Logf("already running %v version %v; no update needed", up.Track, ver)
  272. return false
  273. case c > 0:
  274. up.Logf("installed %v version %v is newer than the latest available version %v; no update needed", up.Track, up.currentVersion, ver)
  275. return false
  276. }
  277. }
  278. if up.Confirm != nil {
  279. return up.Confirm(ver)
  280. }
  281. return true
  282. }
  283. const synoinfoConfPath = "/etc/synoinfo.conf"
  284. func (up *Updater) updateSynology() error {
  285. if up.Version != "" {
  286. return errors.New("installing a specific version on Synology is not supported")
  287. }
  288. if err := requireRoot(); err != nil {
  289. return err
  290. }
  291. // Get the latest version and list of SPKs from pkgs.tailscale.com.
  292. dsmVersion := distro.DSMVersion()
  293. osName := fmt.Sprintf("dsm%d", dsmVersion)
  294. arch, err := synoArch(runtime.GOARCH, synoinfoConfPath)
  295. if err != nil {
  296. return err
  297. }
  298. latest, err := latestPackages(up.Track)
  299. if err != nil {
  300. return err
  301. }
  302. spkName := latest.SPKs[osName][arch]
  303. if spkName == "" {
  304. return fmt.Errorf("cannot find Synology package for os=%s arch=%s, please report a bug with your device model", osName, arch)
  305. }
  306. if !up.confirm(latest.SPKsVersion) {
  307. return nil
  308. }
  309. up.cleanupOldDownloads(filepath.Join(os.TempDir(), "tailscale-update*", "*.spk"))
  310. // Download the SPK into a temporary directory.
  311. spkDir, err := os.MkdirTemp("", "tailscale-update")
  312. if err != nil {
  313. return err
  314. }
  315. pkgsPath := fmt.Sprintf("%s/%s", up.Track, spkName)
  316. spkPath := filepath.Join(spkDir, path.Base(pkgsPath))
  317. if err := up.downloadURLToFile(pkgsPath, spkPath); err != nil {
  318. return err
  319. }
  320. // Install the SPK. Run via nohup to allow install to succeed when we're
  321. // connected over tailscale ssh and this parent process dies. Otherwise, if
  322. // you abort synopkg install mid-way, tailscaled is not restarted.
  323. cmd := exec.Command("nohup", "synopkg", "install", spkPath)
  324. // Don't attach cmd.Stdout to Stdout because nohup will redirect that into
  325. // nohup.out file. synopkg doesn't have any progress output anyway, it just
  326. // spits out a JSON result when done.
  327. out, err := cmd.CombinedOutput()
  328. if err != nil {
  329. if dsmVersion == 6 && bytes.Contains(out, []byte("error = [290]")) {
  330. return fmt.Errorf("synopkg install failed: %w\noutput:\n%s\nplease make sure that packages from 'Any publisher' are allowed in the Package Center (Package Center -> Settings -> Trust Level -> Any publisher)", err, out)
  331. }
  332. return fmt.Errorf("synopkg install failed: %w\noutput:\n%s", err, out)
  333. }
  334. if dsmVersion == 6 {
  335. // DSM6 does not automatically restart the package on install. Do it
  336. // manually.
  337. cmd := exec.Command("nohup", "synopkg", "start", "Tailscale")
  338. out, err := cmd.CombinedOutput()
  339. if err != nil {
  340. return fmt.Errorf("synopkg start failed: %w\noutput:\n%s", err, out)
  341. }
  342. }
  343. return nil
  344. }
  345. // synoArch returns the Synology CPU architecture matching one of the SPK
  346. // architectures served from pkgs.tailscale.com.
  347. func synoArch(goArch, synoinfoPath string) (string, error) {
  348. // Most Synology boxes just use a different arch name from GOARCH.
  349. arch := map[string]string{
  350. "amd64": "x86_64",
  351. "386": "i686",
  352. "arm64": "armv8",
  353. }[goArch]
  354. if arch == "" {
  355. // Here's the fun part, some older ARM boxes require you to use SPKs
  356. // specifically for their CPU. See
  357. // https://github.com/SynoCommunity/spksrc/wiki/Synology-and-SynoCommunity-Package-Architectures
  358. // for a complete list.
  359. //
  360. // Some CPUs will map to neither this list nor the goArch map above, and we
  361. // don't have SPKs for them.
  362. cpu, err := parseSynoinfo(synoinfoPath)
  363. if err != nil {
  364. return "", fmt.Errorf("failed to get CPU architecture: %w", err)
  365. }
  366. switch cpu {
  367. case "88f6281", "88f6282", "hi3535", "alpine", "armada370",
  368. "armada375", "armada38x", "armadaxp", "comcerto2k", "monaco":
  369. arch = cpu
  370. default:
  371. return "", fmt.Errorf("unsupported Synology CPU architecture %q (Go arch %q), please report a bug at https://github.com/tailscale/tailscale/issues/new/choose", cpu, goArch)
  372. }
  373. }
  374. return arch, nil
  375. }
  376. func parseSynoinfo(path string) (string, error) {
  377. f, err := os.Open(path)
  378. if err != nil {
  379. return "", err
  380. }
  381. defer f.Close()
  382. // Look for a line like:
  383. // unique="synology_88f6282_413j"
  384. // Extract the CPU in the middle (88f6282 in the above example).
  385. s := bufio.NewScanner(f)
  386. for s.Scan() {
  387. l := s.Text()
  388. if !strings.HasPrefix(l, "unique=") {
  389. continue
  390. }
  391. parts := strings.SplitN(l, "_", 3)
  392. if len(parts) != 3 {
  393. return "", fmt.Errorf(`malformed %q: found %q, expected format like 'unique="synology_$cpu_$model'`, path, l)
  394. }
  395. return parts[1], nil
  396. }
  397. return "", fmt.Errorf(`missing "unique=" field in %q`, path)
  398. }
  399. func (up *Updater) updateDebLike() error {
  400. if err := requireRoot(); err != nil {
  401. return err
  402. }
  403. if err := exec.Command("dpkg", "--status", "tailscale").Run(); err != nil && isExitError(err) {
  404. // Tailscale was not installed via apt, update via tarball download
  405. // instead.
  406. return up.updateLinuxBinary()
  407. }
  408. ver, err := requestedTailscaleVersion(up.Version, up.Track)
  409. if err != nil {
  410. return err
  411. }
  412. if !up.confirm(ver) {
  413. return nil
  414. }
  415. if updated, err := updateDebianAptSourcesList(up.Track); err != nil {
  416. return err
  417. } else if updated {
  418. up.Logf("Updated %s to use the %s track", aptSourcesFile, up.Track)
  419. }
  420. cmd := exec.Command("apt-get", "update",
  421. // Only update the tailscale repo, not the other ones, treating
  422. // the tailscale.list file as the main "sources.list" file.
  423. "-o", "Dir::Etc::SourceList=sources.list.d/tailscale.list",
  424. // Disable the "sources.list.d" directory:
  425. "-o", "Dir::Etc::SourceParts=-",
  426. // Don't forget about packages in the other repos just because
  427. // we're not updating them:
  428. "-o", "APT::Get::List-Cleanup=0",
  429. )
  430. if out, err := cmd.CombinedOutput(); err != nil {
  431. return fmt.Errorf("apt-get update failed: %w; output:\n%s", err, out)
  432. }
  433. for range 2 {
  434. out, err := exec.Command("apt-get", "install", "--yes", "--allow-downgrades", "tailscale="+ver).CombinedOutput()
  435. if err != nil {
  436. if !bytes.Contains(out, []byte(`dpkg was interrupted`)) {
  437. return fmt.Errorf("apt-get install failed: %w; output:\n%s", err, out)
  438. }
  439. up.Logf("apt-get install failed: %s; output:\n%s", err, out)
  440. up.Logf("running dpkg --configure tailscale")
  441. out, err = exec.Command("dpkg", "--force-confdef,downgrade", "--configure", "tailscale").CombinedOutput()
  442. if err != nil {
  443. return fmt.Errorf("dpkg --configure tailscale failed: %w; output:\n%s", err, out)
  444. }
  445. continue
  446. }
  447. break
  448. }
  449. return nil
  450. }
  451. const aptSourcesFile = "/etc/apt/sources.list.d/tailscale.list"
  452. // updateDebianAptSourcesList updates the /etc/apt/sources.list.d/tailscale.list
  453. // file to make sure it has the provided track (stable or unstable) in it.
  454. //
  455. // If it already has the right track (including containing both stable and
  456. // unstable), it does nothing.
  457. func updateDebianAptSourcesList(dstTrack string) (rewrote bool, err error) {
  458. was, err := os.ReadFile(aptSourcesFile)
  459. if err != nil {
  460. return false, err
  461. }
  462. newContent, err := updateDebianAptSourcesListBytes(was, dstTrack)
  463. if err != nil {
  464. return false, err
  465. }
  466. if bytes.Equal(was, newContent) {
  467. return false, nil
  468. }
  469. return true, os.WriteFile(aptSourcesFile, newContent, 0644)
  470. }
  471. func updateDebianAptSourcesListBytes(was []byte, dstTrack string) (newContent []byte, err error) {
  472. trackURLPrefix := []byte("https://pkgs.tailscale.com/" + dstTrack + "/")
  473. var buf bytes.Buffer
  474. var changes int
  475. bs := bufio.NewScanner(bytes.NewReader(was))
  476. hadCorrect := false
  477. commentLine := regexp.MustCompile(`^\s*\#`)
  478. pkgsURL := regexp.MustCompile(`\bhttps://pkgs\.tailscale\.com/((un)?stable)/`)
  479. for bs.Scan() {
  480. line := bs.Bytes()
  481. if !commentLine.Match(line) {
  482. line = pkgsURL.ReplaceAllFunc(line, func(m []byte) []byte {
  483. if bytes.Equal(m, trackURLPrefix) {
  484. hadCorrect = true
  485. } else {
  486. changes++
  487. }
  488. return trackURLPrefix
  489. })
  490. }
  491. buf.Write(line)
  492. buf.WriteByte('\n')
  493. }
  494. if hadCorrect || (changes == 1 && bytes.Equal(bytes.TrimSpace(was), bytes.TrimSpace(buf.Bytes()))) {
  495. // Unchanged or close enough.
  496. return was, nil
  497. }
  498. if changes != 1 {
  499. // No changes, or an unexpected number of changes (what?). Bail.
  500. // They probably editted it by hand and we don't know what to do.
  501. return nil, fmt.Errorf("unexpected/unsupported %s contents", aptSourcesFile)
  502. }
  503. return buf.Bytes(), nil
  504. }
  505. func (up *Updater) archPackageInstalled() bool {
  506. err := exec.Command("pacman", "--query", "tailscale").Run()
  507. return err == nil
  508. }
  509. func (up *Updater) updateArchLike() error {
  510. // Arch maintainer asked us not to implement "tailscale update" or
  511. // auto-updates on Arch-based distros:
  512. // https://github.com/tailscale/tailscale/issues/6995#issuecomment-1687080106
  513. return errors.New(`individual package updates are not supported on Arch-based distros, only full-system updates are: https://wiki.archlinux.org/title/System_maintenance#Partial_upgrades_are_unsupported.
  514. you can use "pacman --sync --refresh --sysupgrade" or "pacman -Syu" to upgrade the system, including Tailscale.`)
  515. }
  516. func (up *Updater) updateNixos() error {
  517. // NixOS package updates are managed on a system level and not individually.
  518. // Direct users to update their nix channel or nixpkgs flake input to
  519. // receive the latest version.
  520. return errors.New(`individual package updates are not supported on NixOS installations. Update your system channel or flake inputs to get the latest Tailscale version from nixpkgs.`)
  521. }
  522. const yumRepoConfigFile = "/etc/yum.repos.d/tailscale.repo"
  523. // updateFedoraLike updates tailscale on any distros in the Fedora family,
  524. // specifically anything that uses "dnf" or "yum" package managers. The actual
  525. // package manager is passed via packageManager.
  526. func (up *Updater) updateFedoraLike(packageManager string) func() error {
  527. return func() (err error) {
  528. if err := requireRoot(); err != nil {
  529. return err
  530. }
  531. if err := exec.Command(packageManager, "info", "--installed", "tailscale").Run(); err != nil && isExitError(err) {
  532. // Tailscale was not installed via yum/dnf, update via tarball
  533. // download instead.
  534. return up.updateLinuxBinary()
  535. }
  536. defer func() {
  537. if err != nil {
  538. err = fmt.Errorf(`%w; you can try updating using "%s upgrade tailscale"`, err, packageManager)
  539. }
  540. }()
  541. ver, err := requestedTailscaleVersion(up.Version, up.Track)
  542. if err != nil {
  543. return err
  544. }
  545. if !up.confirm(ver) {
  546. return nil
  547. }
  548. if updated, err := updateYUMRepoTrack(yumRepoConfigFile, up.Track); err != nil {
  549. return err
  550. } else if updated {
  551. up.Logf("Updated %s to use the %s track", yumRepoConfigFile, up.Track)
  552. }
  553. cmd := exec.Command(packageManager, "install", "--assumeyes", fmt.Sprintf("tailscale-%s-1", ver))
  554. cmd.Stdout = up.Stdout
  555. cmd.Stderr = up.Stderr
  556. if err := cmd.Run(); err != nil {
  557. return err
  558. }
  559. return nil
  560. }
  561. }
  562. // updateYUMRepoTrack updates the repoFile file to make sure it has the
  563. // provided track (stable or unstable) in it.
  564. func updateYUMRepoTrack(repoFile, dstTrack string) (rewrote bool, err error) {
  565. was, err := os.ReadFile(repoFile)
  566. if err != nil {
  567. return false, err
  568. }
  569. urlRe := regexp.MustCompile(`^(baseurl|gpgkey)=https://pkgs\.tailscale\.com/(un)?stable/`)
  570. urlReplacement := fmt.Sprintf("$1=https://pkgs.tailscale.com/%s/", dstTrack)
  571. s := bufio.NewScanner(bytes.NewReader(was))
  572. newContent := bytes.NewBuffer(make([]byte, 0, len(was)))
  573. for s.Scan() {
  574. line := s.Text()
  575. // Handle repo section name, like "[tailscale-stable]".
  576. if len(line) > 0 && line[0] == '[' {
  577. if !strings.HasPrefix(line, "[tailscale-") {
  578. return false, fmt.Errorf("%q does not look like a tailscale repo file, it contains an unexpected %q section", repoFile, line)
  579. }
  580. fmt.Fprintf(newContent, "[tailscale-%s]\n", dstTrack)
  581. continue
  582. }
  583. // Update the track mentioned in repo name.
  584. if strings.HasPrefix(line, "name=") {
  585. fmt.Fprintf(newContent, "name=Tailscale %s\n", dstTrack)
  586. continue
  587. }
  588. // Update the actual repo URLs.
  589. if strings.HasPrefix(line, "baseurl=") || strings.HasPrefix(line, "gpgkey=") {
  590. fmt.Fprintln(newContent, urlRe.ReplaceAllString(line, urlReplacement))
  591. continue
  592. }
  593. fmt.Fprintln(newContent, line)
  594. }
  595. if bytes.Equal(was, newContent.Bytes()) {
  596. return false, nil
  597. }
  598. return true, os.WriteFile(repoFile, newContent.Bytes(), 0644)
  599. }
  600. func (up *Updater) updateAlpineLike() (err error) {
  601. if up.Version != "" {
  602. return errors.New("installing a specific version on Alpine-based distros is not supported")
  603. }
  604. if err := requireRoot(); err != nil {
  605. return err
  606. }
  607. if err := exec.Command("apk", "info", "--installed", "tailscale").Run(); err != nil && isExitError(err) {
  608. // Tailscale was not installed via apk, update via tarball download
  609. // instead.
  610. return up.updateLinuxBinary()
  611. }
  612. defer func() {
  613. if err != nil {
  614. err = fmt.Errorf(`%w; you can try updating using "apk upgrade tailscale"`, err)
  615. }
  616. }()
  617. out, err := exec.Command("apk", "update").CombinedOutput()
  618. if err != nil {
  619. return fmt.Errorf("failed refresh apk repository indexes: %w, output:\n%s", err, out)
  620. }
  621. out, err = exec.Command("apk", "info", "tailscale").CombinedOutput()
  622. if err != nil {
  623. return fmt.Errorf("failed checking apk for latest tailscale version: %w, output:\n%s", err, out)
  624. }
  625. ver, err := parseAlpinePackageVersion(out)
  626. if err != nil {
  627. return fmt.Errorf(`failed to parse latest version from "apk info tailscale": %w`, err)
  628. }
  629. if !up.confirm(ver) {
  630. if err := checkOutdatedAlpineRepo(up.Logf, ver, up.Track); err != nil {
  631. up.Logf("failed to check whether Alpine release is outdated: %v", err)
  632. }
  633. return nil
  634. }
  635. cmd := exec.Command("apk", "upgrade", "tailscale")
  636. cmd.Stdout = up.Stdout
  637. cmd.Stderr = up.Stderr
  638. if err := cmd.Run(); err != nil {
  639. return fmt.Errorf("failed tailscale update using apk: %w", err)
  640. }
  641. return nil
  642. }
  643. func parseAlpinePackageVersion(out []byte) (string, error) {
  644. s := bufio.NewScanner(bytes.NewReader(out))
  645. var maxVer string
  646. for s.Scan() {
  647. // The line should look like this:
  648. // tailscale-1.44.2-r0 description:
  649. line := strings.TrimSpace(s.Text())
  650. if !strings.HasPrefix(line, "tailscale-") {
  651. continue
  652. }
  653. parts := strings.SplitN(line, "-", 3)
  654. if len(parts) < 3 {
  655. return "", fmt.Errorf("malformed info line: %q", line)
  656. }
  657. ver := parts[1]
  658. if cmpver.Compare(ver, maxVer) > 0 {
  659. maxVer = ver
  660. }
  661. }
  662. if maxVer != "" {
  663. return maxVer, nil
  664. }
  665. return "", errors.New("tailscale version not found in output")
  666. }
  667. var apkRepoVersionRE = regexp.MustCompile(`v[0-9]+\.[0-9]+`)
  668. func checkOutdatedAlpineRepo(logf logger.Logf, apkVer, track string) error {
  669. latest, err := LatestTailscaleVersion(track)
  670. if err != nil {
  671. return err
  672. }
  673. if latest == apkVer {
  674. // Actually on latest release.
  675. return nil
  676. }
  677. f, err := os.Open("/etc/apk/repositories")
  678. if err != nil {
  679. return err
  680. }
  681. defer f.Close()
  682. // Read the first repo line. Typically, there are multiple repos that all
  683. // contain the same version in the path, like:
  684. // https://dl-cdn.alpinelinux.org/alpine/v3.20/main
  685. // https://dl-cdn.alpinelinux.org/alpine/v3.20/community
  686. s := bufio.NewScanner(f)
  687. if !s.Scan() {
  688. return s.Err()
  689. }
  690. alpineVer := apkRepoVersionRE.FindString(s.Text())
  691. if alpineVer != "" {
  692. logf("The latest Tailscale release for Linux is %q, but your apk repository only provides %q.\nYour Alpine version is %q, you may need to upgrade the system to get the latest Tailscale version: https://wiki.alpinelinux.org/wiki/Upgrading_Alpine", latest, apkVer, alpineVer)
  693. }
  694. return nil
  695. }
  696. func (up *Updater) updateMacSys() error {
  697. return errors.New("NOTREACHED: On MacSys builds, `tailscale update` is handled in Swift to launch the GUI updater")
  698. }
  699. func (up *Updater) updateMacAppStore() error {
  700. // We can't trigger the update via App Store from the sandboxed app. At
  701. // most, we can open the App Store page for them.
  702. up.Logf("Please use the App Store to update Tailscale.\nConsider enabling Automatic Updates in the App Store Settings, if you haven't already.\nOpening the Tailscale app page...")
  703. out, err := exec.Command("open", "https://apps.apple.com/us/app/tailscale/id1475387142").CombinedOutput()
  704. if err != nil {
  705. return fmt.Errorf("can't open the Tailscale page in App Store: %w, output:\n%s", err, string(out))
  706. }
  707. return nil
  708. }
  709. // cleanupOldDownloads removes all files matching glob (see filepath.Glob).
  710. // Only regular files are removed, so the glob must match specific files and
  711. // not directories.
  712. func (up *Updater) cleanupOldDownloads(glob string) {
  713. matches, err := filepath.Glob(glob)
  714. if err != nil {
  715. up.Logf("cleaning up old downloads: %v", err)
  716. return
  717. }
  718. for _, m := range matches {
  719. s, err := os.Lstat(m)
  720. if err != nil {
  721. up.Logf("cleaning up old downloads: %v", err)
  722. continue
  723. }
  724. if !s.Mode().IsRegular() {
  725. continue
  726. }
  727. if err := os.Remove(m); err != nil {
  728. up.Logf("cleaning up old downloads: %v", err)
  729. }
  730. }
  731. }
  732. func (up *Updater) updateFreeBSD() (err error) {
  733. if up.Version != "" {
  734. return errors.New("installing a specific version on FreeBSD is not supported")
  735. }
  736. if err := requireRoot(); err != nil {
  737. return err
  738. }
  739. if err := exec.Command("pkg", "query", "%n", "tailscale").Run(); err != nil && isExitError(err) {
  740. // Tailscale was not installed via pkg and we don't pre-compile
  741. // binaries for it.
  742. return errors.New("Tailscale was not installed via pkg, binary updates on FreeBSD are not supported; please reinstall Tailscale using pkg or update manually")
  743. }
  744. defer func() {
  745. if err != nil {
  746. err = fmt.Errorf(`%w; you can try updating using "pkg upgrade tailscale"`, err)
  747. }
  748. }()
  749. out, err := exec.Command("pkg", "update").CombinedOutput()
  750. if err != nil {
  751. return fmt.Errorf("failed refresh pkg repository indexes: %w, output:\n%s", err, out)
  752. }
  753. out, err = exec.Command("pkg", "rquery", "%v", "tailscale").CombinedOutput()
  754. if err != nil {
  755. return fmt.Errorf("failed checking pkg for latest tailscale version: %w, output:\n%s", err, out)
  756. }
  757. ver := string(bytes.TrimSpace(out))
  758. if !up.confirm(ver) {
  759. return nil
  760. }
  761. cmd := exec.Command("pkg", "upgrade", "-y", "tailscale")
  762. cmd.Stdout = up.Stdout
  763. cmd.Stderr = up.Stderr
  764. if err := cmd.Run(); err != nil {
  765. return fmt.Errorf("failed tailscale update using pkg: %w", err)
  766. }
  767. // pkg does not automatically restart services after upgrade.
  768. out, err = exec.Command("service", "tailscaled", "restart").CombinedOutput()
  769. if err != nil {
  770. return fmt.Errorf("failed to restart tailscaled after update: %w, output:\n%s", err, out)
  771. }
  772. return nil
  773. }
  774. func (up *Updater) updateLinuxBinary() error {
  775. // Root is needed to overwrite binaries and restart systemd unit.
  776. if err := requireRoot(); err != nil {
  777. return err
  778. }
  779. ver, err := requestedTailscaleVersion(up.Version, up.Track)
  780. if err != nil {
  781. return err
  782. }
  783. if !up.confirm(ver) {
  784. return nil
  785. }
  786. dlPath, err := up.downloadLinuxTarball(ver)
  787. if err != nil {
  788. return err
  789. }
  790. up.Logf("Extracting %q", dlPath)
  791. if err := up.unpackLinuxTarball(dlPath); err != nil {
  792. return err
  793. }
  794. if err := os.Remove(dlPath); err != nil {
  795. up.Logf("failed to clean up %q: %v", dlPath, err)
  796. }
  797. if err := restartSystemdUnit(context.Background()); err != nil {
  798. if errors.Is(err, errors.ErrUnsupported) {
  799. up.Logf("Tailscale binaries updated successfully.\nPlease restart tailscaled to finish the update.")
  800. } else {
  801. up.Logf("Tailscale binaries updated successfully, but failed to restart tailscaled: %s.\nPlease restart tailscaled to finish the update.", err)
  802. }
  803. } else {
  804. up.Logf("Success")
  805. }
  806. return nil
  807. }
  808. func restartSystemdUnit(ctx context.Context) error {
  809. if _, err := exec.LookPath("systemctl"); err != nil {
  810. // Likely not a systemd-managed distro.
  811. return errors.ErrUnsupported
  812. }
  813. if out, err := exec.Command("systemctl", "daemon-reload").CombinedOutput(); err != nil {
  814. return fmt.Errorf("systemctl daemon-reload failed: %w\noutput: %s", err, out)
  815. }
  816. if out, err := exec.Command("systemctl", "restart", "tailscaled.service").CombinedOutput(); err != nil {
  817. return fmt.Errorf("systemctl restart failed: %w\noutput: %s", err, out)
  818. }
  819. return nil
  820. }
  821. func (up *Updater) downloadLinuxTarball(ver string) (string, error) {
  822. dlDir, err := os.UserCacheDir()
  823. if err != nil {
  824. dlDir = os.TempDir()
  825. }
  826. dlDir = filepath.Join(dlDir, "tailscale-update")
  827. if err := os.MkdirAll(dlDir, 0700); err != nil {
  828. return "", err
  829. }
  830. pkgsPath := fmt.Sprintf("%s/tailscale_%s_%s.tgz", up.Track, ver, runtime.GOARCH)
  831. dlPath := filepath.Join(dlDir, path.Base(pkgsPath))
  832. if err := up.downloadURLToFile(pkgsPath, dlPath); err != nil {
  833. return "", err
  834. }
  835. return dlPath, nil
  836. }
  837. func (up *Updater) unpackLinuxTarball(path string) error {
  838. tailscale, tailscaled, err := binaryPaths()
  839. if err != nil {
  840. return err
  841. }
  842. f, err := os.Open(path)
  843. if err != nil {
  844. return err
  845. }
  846. defer f.Close()
  847. gr, err := gzip.NewReader(f)
  848. if err != nil {
  849. return err
  850. }
  851. defer gr.Close()
  852. tr := tar.NewReader(gr)
  853. files := make(map[string]int)
  854. wantFiles := map[string]int{
  855. "tailscale": 1,
  856. "tailscaled": 1,
  857. }
  858. for {
  859. th, err := tr.Next()
  860. if err == io.EOF {
  861. break
  862. }
  863. if err != nil {
  864. return fmt.Errorf("failed extracting %q: %w", path, err)
  865. }
  866. // TODO(awly): try to also extract tailscaled.service. The tricky part
  867. // is fixing up binary paths in that file if they differ from where
  868. // local tailscale/tailscaled are installed. Also, this may not be a
  869. // systemd distro.
  870. switch filepath.Base(th.Name) {
  871. case "tailscale":
  872. files["tailscale"]++
  873. if err := writeFile(tr, tailscale+".new", 0755); err != nil {
  874. return fmt.Errorf("failed extracting the new tailscale binary from %q: %w", path, err)
  875. }
  876. case "tailscaled":
  877. files["tailscaled"]++
  878. if err := writeFile(tr, tailscaled+".new", 0755); err != nil {
  879. return fmt.Errorf("failed extracting the new tailscaled binary from %q: %w", path, err)
  880. }
  881. }
  882. }
  883. if !maps.Equal(files, wantFiles) {
  884. return fmt.Errorf("%q has missing or duplicate files: got %v, want %v", path, files, wantFiles)
  885. }
  886. // Only place the files in final locations after everything extracted correctly.
  887. if err := os.Rename(tailscale+".new", tailscale); err != nil {
  888. return err
  889. }
  890. up.Logf("Updated %s", tailscale)
  891. if err := os.Rename(tailscaled+".new", tailscaled); err != nil {
  892. return err
  893. }
  894. up.Logf("Updated %s", tailscaled)
  895. return nil
  896. }
  897. func (up *Updater) updateQNAP() (err error) {
  898. if up.Version != "" {
  899. return errors.New("installing a specific version on QNAP is not supported")
  900. }
  901. if err := requireRoot(); err != nil {
  902. return err
  903. }
  904. defer func() {
  905. if err != nil {
  906. err = fmt.Errorf(`%w; you can try updating using "qpkg_cli --add Tailscale"`, err)
  907. }
  908. }()
  909. out, err := exec.Command("qpkg_cli", "--upgradable", "Tailscale").CombinedOutput()
  910. if err != nil {
  911. return fmt.Errorf("failed to check if Tailscale is upgradable using qpkg_cli: %w, output: %q", err, out)
  912. }
  913. // Output should look like this:
  914. //
  915. // $ qpkg_cli -G Tailscale
  916. // [Tailscale]
  917. // upgradeStatus = 1
  918. statusRe := regexp.MustCompile(`upgradeStatus = (\d)`)
  919. m := statusRe.FindStringSubmatch(string(out))
  920. if len(m) < 2 {
  921. return fmt.Errorf("failed to check if Tailscale is upgradable using qpkg_cli, output: %q", out)
  922. }
  923. status, err := strconv.Atoi(m[1])
  924. if err != nil {
  925. return fmt.Errorf("cannot parse upgradeStatus from qpkg_cli output %q: %w", out, err)
  926. }
  927. // Possible status values:
  928. // 0:can upgrade
  929. // 1:can not upgrade
  930. // 2:error
  931. // 3:can not get rss information
  932. // 4:qpkg not found
  933. // 5:qpkg not installed
  934. //
  935. // We want status 0.
  936. switch status {
  937. case 0: // proceed with upgrade
  938. case 1:
  939. up.Logf("no update available")
  940. return nil
  941. case 2, 3, 4:
  942. return fmt.Errorf("failed to check update status with qpkg_cli (upgradeStatus = %d)", status)
  943. case 5:
  944. return errors.New("Tailscale was not found in the QNAP App Center")
  945. default:
  946. return fmt.Errorf("failed to check update status with qpkg_cli (upgradeStatus = %d)", status)
  947. }
  948. // There doesn't seem to be a way to fetch what the available upgrade
  949. // version is. Use the generic "latest" version in confirmation prompt.
  950. if up.Confirm != nil && !up.Confirm("latest") {
  951. return nil
  952. }
  953. up.Logf("c2n: running qpkg_cli --add Tailscale")
  954. cmd := exec.Command("qpkg_cli", "--add", "Tailscale")
  955. cmd.Stdout = up.Stdout
  956. cmd.Stderr = up.Stderr
  957. if err := cmd.Run(); err != nil {
  958. return fmt.Errorf("failed tailscale update using qpkg_cli: %w", err)
  959. }
  960. return nil
  961. }
  962. func (up *Updater) updateUnraid() (err error) {
  963. if up.Version != "" {
  964. return errors.New("installing a specific version on Unraid is not supported")
  965. }
  966. if err := requireRoot(); err != nil {
  967. return err
  968. }
  969. defer func() {
  970. if err != nil {
  971. err = fmt.Errorf(`%w; you can try updating using "plugin check tailscale.plg && plugin update tailscale.plg"`, err)
  972. }
  973. }()
  974. // We need to run `plugin check` for the latest tailscale.plg to get
  975. // downloaded. Unfortunately, the output of this command does not contain
  976. // the latest tailscale version available. So we'll parse the downloaded
  977. // tailscale.plg file manually below.
  978. out, err := exec.Command("plugin", "check", "tailscale.plg").CombinedOutput()
  979. if err != nil {
  980. return fmt.Errorf("failed to check if Tailscale plugin is upgradable: %w, output: %q", err, out)
  981. }
  982. // Note: 'plugin check' downloads plugins to /tmp/plugins.
  983. // The installed .plg files are in /boot/config/plugins/, but the pending
  984. // ones are in /tmp/plugins. We should parse the pending file downloaded by
  985. // 'plugin check'.
  986. latest, err := parseUnraidPluginVersion("/tmp/plugins/tailscale.plg")
  987. if err != nil {
  988. return fmt.Errorf("failed to find latest Tailscale version in /boot/config/plugins/tailscale.plg: %w", err)
  989. }
  990. if !up.confirm(latest) {
  991. return nil
  992. }
  993. up.Logf("c2n: running 'plugin update tailscale.plg'")
  994. cmd := exec.Command("plugin", "update", "tailscale.plg")
  995. cmd.Stdout = up.Stdout
  996. cmd.Stderr = up.Stderr
  997. if err := cmd.Run(); err != nil {
  998. return fmt.Errorf("failed tailscale plugin update: %w", err)
  999. }
  1000. return nil
  1001. }
  1002. func parseUnraidPluginVersion(plgPath string) (string, error) {
  1003. plg, err := os.ReadFile(plgPath)
  1004. if err != nil {
  1005. return "", err
  1006. }
  1007. re := regexp.MustCompile(`<FILE Name="/boot/config/plugins/tailscale/tailscale_(\d+\.\d+\.\d+)_[a-z0-9]+.tgz">`)
  1008. match := re.FindStringSubmatch(string(plg))
  1009. if len(match) < 2 {
  1010. return "", errors.New("version not found in plg file")
  1011. }
  1012. return match[1], nil
  1013. }
  1014. func writeFile(r io.Reader, path string, perm os.FileMode) error {
  1015. if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
  1016. return fmt.Errorf("failed to remove existing file at %q: %w", path, err)
  1017. }
  1018. f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
  1019. if err != nil {
  1020. return err
  1021. }
  1022. defer f.Close()
  1023. if _, err := io.Copy(f, r); err != nil {
  1024. return err
  1025. }
  1026. return f.Close()
  1027. }
  1028. // Var allows overriding this in tests.
  1029. var binaryPaths = func() (tailscale, tailscaled string, err error) {
  1030. // This can be either tailscale or tailscaled.
  1031. this, err := os.Executable()
  1032. if err != nil {
  1033. return "", "", err
  1034. }
  1035. otherName := "tailscaled"
  1036. if filepath.Base(this) == "tailscaled" {
  1037. otherName = "tailscale"
  1038. }
  1039. // Try to find the other binary in the same directory.
  1040. other := filepath.Join(filepath.Dir(this), otherName)
  1041. _, err = os.Stat(other)
  1042. if os.IsNotExist(err) {
  1043. // If it's not in the same directory, try to find it in $PATH.
  1044. other, err = exec.LookPath(otherName)
  1045. }
  1046. if err != nil {
  1047. return "", "", fmt.Errorf("cannot find %q in neither %q nor $PATH: %w", otherName, filepath.Dir(this), err)
  1048. }
  1049. if otherName == "tailscaled" {
  1050. return this, other, nil
  1051. } else {
  1052. return other, this, nil
  1053. }
  1054. }
  1055. func haveExecutable(name string) bool {
  1056. path, err := exec.LookPath(name)
  1057. return err == nil && path != ""
  1058. }
  1059. func requestedTailscaleVersion(ver, track string) (string, error) {
  1060. if ver != "" {
  1061. return ver, nil
  1062. }
  1063. return LatestTailscaleVersion(track)
  1064. }
  1065. // LatestTailscaleVersion returns the latest released version for the given
  1066. // track from pkgs.tailscale.com.
  1067. func LatestTailscaleVersion(track string) (string, error) {
  1068. if track == "" {
  1069. track = CurrentTrack
  1070. }
  1071. latest, err := latestPackages(track)
  1072. if err != nil {
  1073. return "", err
  1074. }
  1075. ver := latest.Version
  1076. switch runtime.GOOS {
  1077. case "windows":
  1078. ver = latest.MSIsVersion
  1079. case "darwin":
  1080. ver = latest.MacZipsVersion
  1081. case "linux":
  1082. ver = latest.TarballsVersion
  1083. if distro.Get() == distro.Synology {
  1084. ver = latest.SPKsVersion
  1085. }
  1086. }
  1087. if ver == "" {
  1088. return "", fmt.Errorf("no latest version found for OS %q on %q track", runtime.GOOS, track)
  1089. }
  1090. return ver, nil
  1091. }
  1092. type trackPackages struct {
  1093. Version string
  1094. Tarballs map[string]string
  1095. TarballsVersion string
  1096. Exes []string
  1097. ExesVersion string
  1098. MSIs map[string]string
  1099. MSIsVersion string
  1100. MacZips map[string]string
  1101. MacZipsVersion string
  1102. SPKs map[string]map[string]string
  1103. SPKsVersion string
  1104. }
  1105. func latestPackages(track string) (*trackPackages, error) {
  1106. url := fmt.Sprintf("https://pkgs.tailscale.com/%s/?mode=json&os=%s", track, runtime.GOOS)
  1107. res, err := http.Get(url)
  1108. if err != nil {
  1109. return nil, fmt.Errorf("fetching latest tailscale version: %w", err)
  1110. }
  1111. defer res.Body.Close()
  1112. var latest trackPackages
  1113. if err := json.NewDecoder(res.Body).Decode(&latest); err != nil {
  1114. return nil, fmt.Errorf("decoding JSON: %v: %w", res.Status, err)
  1115. }
  1116. return &latest, nil
  1117. }
  1118. func requireRoot() error {
  1119. if os.Geteuid() == 0 {
  1120. return nil
  1121. }
  1122. switch runtime.GOOS {
  1123. case "linux":
  1124. return errors.New("must be root; use sudo")
  1125. case "freebsd", "openbsd":
  1126. return errors.New("must be root; use doas")
  1127. default:
  1128. return errors.New("must be root")
  1129. }
  1130. }
  1131. func isExitError(err error) bool {
  1132. var exitErr *exec.ExitError
  1133. return errors.As(err, &exitErr)
  1134. }