clientupdate.go 37 KB

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