clientupdate.go 39 KB

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