clientupdate.go 43 KB

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