clientupdate.go 40 KB

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