clientupdate.go 42 KB

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