panel.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. package panel
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "regexp"
  12. "runtime"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "syscall"
  17. "time"
  18. "github.com/mhsanaei/3x-ui/v3/internal/config"
  19. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  20. "github.com/mhsanaei/3x-ui/v3/internal/web/global"
  21. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  22. )
  23. // PanelService provides business logic for panel management operations.
  24. // It handles panel restart, updates, and system-level panel controls.
  25. type PanelService struct{}
  26. // PanelUpdateInfo contains the current and latest available panel versions.
  27. // On the dev channel the version fields carry a "dev+<sha>" label and the commit
  28. // fields hold the short SHAs that drive the update-available decision.
  29. type PanelUpdateInfo struct {
  30. Channel string `json:"channel"`
  31. CurrentVersion string `json:"currentVersion"`
  32. LatestVersion string `json:"latestVersion"`
  33. CurrentCommit string `json:"currentCommit,omitempty"`
  34. LatestCommit string `json:"latestCommit,omitempty"`
  35. UpdateAvailable bool `json:"updateAvailable"`
  36. }
  37. const (
  38. panelUpdaterURL = "https://raw.githubusercontent.com/MHSanaei/3x-ui/main/update.sh"
  39. maxPanelUpdaterBytes = 2 << 20
  40. // devReleaseTag is the fixed-tag rolling pre-release the CI force-moves to the
  41. // newest main commit; the dev update channel installs from it.
  42. devReleaseTag = "dev-latest"
  43. updateStatePending = "pending"
  44. updateStateSuccess = "success"
  45. updateStateFailed = "failed"
  46. )
  47. // PanelUpdateStatus reports the outcome of the most recently launched panel
  48. // self-update. RunID lets the caller confirm this status belongs to the
  49. // update it started rather than a stale result left over from an earlier
  50. // run; State is one of "pending", "success", or "failed". RunID is a decimal
  51. // string, not a JSON number: it's a formatted UnixNano timestamp, and
  52. // JavaScript's number type can't represent that precisely (it exceeds
  53. // Number.MAX_SAFE_INTEGER), which would let two different runs round to the
  54. // same value on the wire and defeat the whole point of this field.
  55. type PanelUpdateStatus struct {
  56. RunID string `json:"runId" example:"1735689600123456789"`
  57. State string `json:"state" example:"success"`
  58. ExitCode int `json:"exitCode" example:"0"`
  59. FinishedAt int64 `json:"finishedAt" example:"1735689612"`
  60. }
  61. var releaseCommitRegex = regexp.MustCompile(`(?i)commit=([0-9a-f]{7,40})`)
  62. // updateMu guards updateRunning/updateStarted/updateRunID/updatePID, which
  63. // stop a second self-update from launching while one is still in flight (two
  64. // concurrent update.sh runs would race each other extracting the release
  65. // tarball and swapping the service unit). A slot is released as soon as the
  66. // in-flight run's own status file reports success or failure -- checked
  67. // against updateRunID so a stale file from an even earlier run can't be
  68. // mistaken for this one finishing -- so a fast failure doesn't lock out a
  69. // retry.
  70. //
  71. // For a run that never reaches a terminal state at all, staleness is judged
  72. // primarily by whether the process we actually launched is still alive
  73. // (updatePID, via processAlive), not by wall-clock time alone: update.sh
  74. // runs install_base() (a package-manager update+install) before anything
  75. // else, plus several downloads, which can legitimately run past a short
  76. // fixed timeout on a slow or throttled host without anything being wrong.
  77. // updateStaleAfter/updatePID together are only a fallback for the systemd-run
  78. // launch path, where the process we can observe (systemd-run itself) has
  79. // already exited by the time startUpdate returns and the actual update.sh
  80. // unit's PID is never recorded -- for that path this is still a pure
  81. // wall-clock heuristic. updateHardCeiling is an absolute backstop so a
  82. // genuinely wedged run (alive but hung forever) can never lock out retries
  83. // permanently, even on the PID-tracked path.
  84. var (
  85. updateMu sync.Mutex
  86. updateRunning bool
  87. updateStarted time.Time
  88. updateRunID int64
  89. updatePID int
  90. )
  91. const (
  92. updateStaleAfter = 20 * time.Minute
  93. updateHardCeiling = 2 * time.Hour
  94. )
  95. func (s *PanelService) RestartPanel(delay time.Duration) error {
  96. go func() {
  97. time.Sleep(delay)
  98. if global.TriggerRestart() {
  99. return
  100. }
  101. if runtime.GOOS == "windows" {
  102. logger.Error("panel restart: no restart hook registered (SIGHUP unsupported on Windows)")
  103. return
  104. }
  105. p, err := os.FindProcess(syscall.Getpid())
  106. if err != nil {
  107. logger.Error("panel restart: FindProcess failed:", err)
  108. return
  109. }
  110. if err := p.Signal(syscall.SIGHUP); err != nil {
  111. logger.Error("failed to send SIGHUP signal:", err)
  112. }
  113. }()
  114. return nil
  115. }
  116. // GetUpdateInfo checks GitHub for the latest 3x-ui release. When the dev channel
  117. // is enabled on a dev build it compares commits against the rolling dev release;
  118. // otherwise it compares versions against the latest stable tag.
  119. func (s *PanelService) GetUpdateInfo() (*PanelUpdateInfo, error) {
  120. if devChannelActive() {
  121. return getDevUpdateInfo()
  122. }
  123. latest, err := fetchLatestPanelVersion()
  124. if err != nil {
  125. return nil, err
  126. }
  127. current := config.GetBaseVersion()
  128. return &PanelUpdateInfo{
  129. Channel: "stable",
  130. CurrentVersion: current,
  131. LatestVersion: latest,
  132. UpdateAvailable: isNewerVersion(latest, current),
  133. }, nil
  134. }
  135. // devChannelActive reports whether self-update should track the rolling dev
  136. // release. It is driven solely by the opt-in setting so the panel can
  137. // cross-grade a stable build onto the dev channel once the user enables it;
  138. // nothing updates without an explicit user action, so an unattended stable
  139. // binary with the toggle off stays on the stable channel.
  140. func devChannelActive() bool {
  141. enabled, err := (&service.SettingService{}).GetDevChannelEnable()
  142. return err == nil && enabled
  143. }
  144. // getDevUpdateInfo compares the running commit against the commit recorded in the
  145. // rolling dev release.
  146. func getDevUpdateInfo() (*PanelUpdateInfo, error) {
  147. release, err := fetchPanelRelease(devReleaseTag)
  148. if err != nil {
  149. return nil, err
  150. }
  151. latestCommit := extractReleaseCommit(release)
  152. if latestCommit == "" {
  153. return nil, fmt.Errorf("dev release commit is unknown")
  154. }
  155. currentCommit := config.GetBuildCommit()
  156. return &PanelUpdateInfo{
  157. Channel: "dev",
  158. CurrentVersion: config.GetPanelVersion(),
  159. CurrentCommit: shortCommit(currentCommit),
  160. LatestCommit: shortCommit(latestCommit),
  161. LatestVersion: "dev+" + shortCommit(latestCommit),
  162. UpdateAvailable: !commitsEqual(currentCommit, latestCommit),
  163. }, nil
  164. }
  165. // StartUpdate starts the official updater using this panel's own channel
  166. // setting. Returns the run ID to pass to GetUpdateStatus so the caller can
  167. // tell this run's result apart from a stale one.
  168. func (s *PanelService) StartUpdate() (int64, error) {
  169. return s.startUpdate(devChannelActive())
  170. }
  171. // StartUpdateChannel runs the updater against an explicitly chosen channel,
  172. // overriding the local dev-channel setting. Used by the master node updater so
  173. // a node can be moved to the dev channel from the central panel.
  174. func (s *PanelService) StartUpdateChannel(dev bool) (int64, error) {
  175. return s.startUpdate(dev)
  176. }
  177. // GetUpdateStatus reports the outcome of the most recently launched panel
  178. // self-update, as recorded by update.sh's EXIT trap (see the script for why
  179. // that covers every exit path, not just the happy one). This is a best-effort
  180. // side channel: a missing or unreadable status file reads as "pending"
  181. // rather than an error, since the update itself is what matters, not this
  182. // status file.
  183. func (s *PanelService) GetUpdateStatus() *PanelUpdateStatus {
  184. data, err := os.ReadFile(config.GetUpdateStatusFilePath())
  185. if err != nil {
  186. return &PanelUpdateStatus{State: updateStatePending}
  187. }
  188. var status PanelUpdateStatus
  189. if err := json.Unmarshal(data, &status); err != nil {
  190. return &PanelUpdateStatus{State: updateStatePending}
  191. }
  192. if status.State != updateStateSuccess && status.State != updateStateFailed {
  193. status.State = updateStatePending
  194. }
  195. return &status
  196. }
  197. func (s *PanelService) startUpdate(useDev bool) (int64, error) {
  198. runID := time.Now().UnixNano()
  199. if !acquireUpdateSlot(runID) {
  200. return 0, fmt.Errorf("a panel update is already in progress")
  201. }
  202. launched := false
  203. defer func() {
  204. if !launched {
  205. releaseUpdateSlot()
  206. }
  207. }()
  208. if runtime.GOOS != "linux" {
  209. return 0, fmt.Errorf("panel web update is supported only on Linux installations")
  210. }
  211. bash, err := exec.LookPath("bash")
  212. if err != nil {
  213. return 0, fmt.Errorf("bash is required to run the panel updater: %w", err)
  214. }
  215. scriptPath, err := downloadPanelUpdater()
  216. if err != nil {
  217. return 0, err
  218. }
  219. statusFile := config.GetUpdateStatusFilePath()
  220. mainFolder, serviceFolder := resolveUpdateFolders()
  221. updateTag := ""
  222. if useDev {
  223. updateTag = devReleaseTag
  224. }
  225. updateScript := fmt.Sprintf("set -e; trap 'rm -f %s' EXIT; %s %s", shellQuote(scriptPath), shellQuote(bash), shellQuote(scriptPath))
  226. runIDEnv := "XUI_UPDATE_RUN_ID=" + strconv.FormatInt(runID, 10)
  227. statusFileEnv := "XUI_UPDATE_STATUS_FILE=" + statusFile
  228. if systemdRun, err := exec.LookPath("systemd-run"); err == nil {
  229. unitName := fmt.Sprintf("x-ui-web-update-%d", time.Now().Unix())
  230. cmd := exec.CommandContext(context.Background(), systemdRun,
  231. "--unit", unitName,
  232. "--setenv", "XUI_MAIN_FOLDER="+mainFolder,
  233. "--setenv", "XUI_SERVICE="+serviceFolder,
  234. "--setenv", "XUI_UPDATE_TAG="+updateTag,
  235. "--setenv", runIDEnv,
  236. "--setenv", statusFileEnv,
  237. bash, "-lc", updateScript,
  238. )
  239. out, err := cmd.CombinedOutput()
  240. if err != nil {
  241. output := strings.TrimSpace(string(out))
  242. if !strings.Contains(output, "System has not been booted with systemd") &&
  243. !strings.Contains(output, "Failed to connect to bus") {
  244. _ = os.Remove(scriptPath)
  245. return 0, fmt.Errorf("failed to start panel update job: %w: %s", err, output)
  246. }
  247. logger.Warning("systemd-run is unavailable, falling back to detached update process:", output)
  248. } else {
  249. logger.Infof("started panel update job via systemd-run unit %s", unitName)
  250. launched = true
  251. return runID, nil
  252. }
  253. }
  254. cmd := exec.CommandContext(context.Background(), bash, "-lc", updateScript)
  255. cmd.Env = append(os.Environ(),
  256. "XUI_MAIN_FOLDER="+mainFolder,
  257. "XUI_SERVICE="+serviceFolder,
  258. "XUI_UPDATE_TAG="+updateTag,
  259. runIDEnv,
  260. statusFileEnv,
  261. )
  262. setDetachedProcess(cmd)
  263. if err := cmd.Start(); err != nil {
  264. _ = os.Remove(scriptPath)
  265. return 0, fmt.Errorf("failed to start panel update job: %w", err)
  266. }
  267. if err := cmd.Process.Release(); err != nil {
  268. logger.Warning("failed to release panel update process:", err)
  269. }
  270. logger.Infof("started panel update job with pid %d", cmd.Process.Pid)
  271. recordUpdatePID(cmd.Process.Pid)
  272. launched = true
  273. return runID, nil
  274. }
  275. // acquireUpdateSlot claims the single in-flight-update slot for runID. It
  276. // refuses while another run is genuinely still in flight, but grants the
  277. // slot immediately once that run's own status file reports a terminal
  278. // result (success or failure) -- a fast failure shouldn't force the next
  279. // attempt to wait out updateStaleAfter for no reason. Past updateStaleAfter
  280. // with no terminal status yet, it grants the slot anyway UNLESS the process
  281. // we recorded (updatePID) is confirmed still alive, so a merely-slow run
  282. // isn't mistaken for a crashed one; past updateHardCeiling it grants the
  283. // slot unconditionally regardless of liveness, so a truly wedged run can
  284. // never lock out retries forever.
  285. func acquireUpdateSlot(runID int64) bool {
  286. updateMu.Lock()
  287. defer updateMu.Unlock()
  288. if updateRunning && !previousRunIsTerminal() {
  289. elapsed := time.Since(updateStarted)
  290. if elapsed < updateHardCeiling {
  291. stale := elapsed >= updateStaleAfter
  292. alive := updatePID > 0 && processAlive(updatePID)
  293. if !stale || alive {
  294. return false
  295. }
  296. }
  297. }
  298. updateRunning = true
  299. updateStarted = time.Now()
  300. updateRunID = runID
  301. updatePID = 0
  302. return true
  303. }
  304. // recordUpdatePID notes the PID of the detached update.sh process the
  305. // current slot is tracking, so a later acquireUpdateSlot call can check
  306. // whether it is actually still running instead of only how long ago it
  307. // started. Only reachable for the detached-fallback launch path -- the
  308. // systemd-run path never learns update.sh's own PID, since the process it
  309. // directly observes (systemd-run) has already exited by the time it returns.
  310. func recordUpdatePID(pid int) {
  311. updateMu.Lock()
  312. updatePID = pid
  313. updateMu.Unlock()
  314. }
  315. // previousRunIsTerminal reports whether the run currently recorded in
  316. // updateRunID has reached success or failure per its status file. Must be
  317. // called with updateMu held.
  318. func previousRunIsTerminal() bool {
  319. status := (&PanelService{}).GetUpdateStatus()
  320. return status.RunID == strconv.FormatInt(updateRunID, 10) && status.State != updateStatePending
  321. }
  322. func releaseUpdateSlot() {
  323. updateMu.Lock()
  324. updateRunning = false
  325. updateMu.Unlock()
  326. }
  327. func downloadPanelUpdater() (string, error) {
  328. client := (&service.SettingService{}).NewProxiedHTTPClient(15 * time.Second)
  329. req, reqErr := http.NewRequestWithContext(context.Background(), http.MethodGet, panelUpdaterURL, nil)
  330. if reqErr != nil {
  331. return "", fmt.Errorf("download panel updater: %w", reqErr)
  332. }
  333. resp, err := client.Do(req)
  334. if err != nil {
  335. return "", fmt.Errorf("download panel updater: %w", err)
  336. }
  337. defer resp.Body.Close()
  338. if resp.StatusCode != http.StatusOK {
  339. return "", fmt.Errorf("download panel updater: unexpected HTTP %d", resp.StatusCode)
  340. }
  341. file, err := os.CreateTemp("", "3x-ui-update-*.sh")
  342. if err != nil {
  343. return "", err
  344. }
  345. path := file.Name()
  346. ok := false
  347. defer func() {
  348. _ = file.Close()
  349. if !ok {
  350. _ = os.Remove(path)
  351. }
  352. }()
  353. n, err := io.Copy(file, io.LimitReader(resp.Body, maxPanelUpdaterBytes+1))
  354. if err != nil {
  355. return "", fmt.Errorf("write panel updater: %w", err)
  356. }
  357. if n == 0 {
  358. return "", fmt.Errorf("panel updater download is empty")
  359. }
  360. if n > maxPanelUpdaterBytes {
  361. return "", fmt.Errorf("panel updater exceeds %d bytes", maxPanelUpdaterBytes)
  362. }
  363. if err := file.Chmod(0o700); err != nil {
  364. return "", err
  365. }
  366. ok = true
  367. return path, nil
  368. }
  369. func fetchLatestPanelVersion() (string, error) {
  370. release, err := fetchPanelRelease("")
  371. if err != nil {
  372. return "", err
  373. }
  374. if release.TagName == "" {
  375. return "", fmt.Errorf("latest panel release tag is empty")
  376. }
  377. return release.TagName, nil
  378. }
  379. // fetchPanelRelease fetches a release from GitHub. An empty tag resolves the
  380. // latest stable release; a non-empty tag (e.g. dev-latest) resolves that tag.
  381. func fetchPanelRelease(tag string) (*service.Release, error) {
  382. url := "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest"
  383. if tag != "" {
  384. url = "https://api.github.com/repos/MHSanaei/3x-ui/releases/tags/" + tag
  385. }
  386. client := (&service.SettingService{}).NewProxiedHTTPClient(10 * time.Second)
  387. req, reqErr := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil)
  388. if reqErr != nil {
  389. return nil, reqErr
  390. }
  391. resp, err := client.Do(req)
  392. if err != nil {
  393. return nil, err
  394. }
  395. defer resp.Body.Close()
  396. if resp.StatusCode != http.StatusOK {
  397. return nil, fmt.Errorf("GitHub API returned status %d: %s", resp.StatusCode, resp.Status)
  398. }
  399. var release service.Release
  400. if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
  401. return nil, err
  402. }
  403. return &release, nil
  404. }
  405. // extractReleaseCommit reads the build commit recorded in the dev release: first
  406. // the `commit=<sha>` marker the CI writes into the body, falling back to the
  407. // tag's target commit.
  408. func extractReleaseCommit(release *service.Release) string {
  409. if m := releaseCommitRegex.FindStringSubmatch(release.Body); m != nil {
  410. return strings.ToLower(m[1])
  411. }
  412. if isCommitSHA(release.TargetCommitish) {
  413. return strings.ToLower(release.TargetCommitish)
  414. }
  415. return ""
  416. }
  417. func isCommitSHA(s string) bool {
  418. s = strings.TrimSpace(s)
  419. if len(s) < 7 || len(s) > 40 {
  420. return false
  421. }
  422. for _, r := range s {
  423. if (r < '0' || r > '9') && (r < 'a' || r > 'f') && (r < 'A' || r > 'F') {
  424. return false
  425. }
  426. }
  427. return true
  428. }
  429. func shortCommit(sha string) string {
  430. sha = strings.TrimSpace(sha)
  431. if len(sha) > 8 {
  432. return sha[:8]
  433. }
  434. return sha
  435. }
  436. // commitsEqual compares a short (injected) commit against a full release commit
  437. // by prefix, so an 8-char build stamp matches the 40-char release SHA.
  438. func commitsEqual(a, b string) bool {
  439. a = strings.ToLower(strings.TrimSpace(a))
  440. b = strings.ToLower(strings.TrimSpace(b))
  441. if a == "" || b == "" {
  442. return false
  443. }
  444. if len(a) > len(b) {
  445. a, b = b, a
  446. }
  447. return strings.HasPrefix(b, a)
  448. }
  449. func resolveUpdateFolders() (string, string) {
  450. mainFolder := os.Getenv("XUI_MAIN_FOLDER")
  451. if mainFolder == "" {
  452. if exePath, err := os.Executable(); err == nil {
  453. mainFolder = filepath.Dir(exePath)
  454. }
  455. }
  456. if mainFolder == "" {
  457. mainFolder = "/usr/local/x-ui"
  458. }
  459. serviceFolder := os.Getenv("XUI_SERVICE")
  460. if serviceFolder == "" {
  461. serviceFolder = "/etc/systemd/system"
  462. }
  463. return mainFolder, serviceFolder
  464. }
  465. func isNewerVersion(latest string, current string) bool {
  466. cmp, ok := compareVersionStrings(latest, current)
  467. if !ok {
  468. return normalizeVersionTag(latest) != normalizeVersionTag(current)
  469. }
  470. return cmp > 0
  471. }
  472. func compareVersionStrings(a string, b string) (int, bool) {
  473. aParts, okA := parseVersionParts(a)
  474. bParts, okB := parseVersionParts(b)
  475. if !okA || !okB {
  476. return 0, false
  477. }
  478. for i := range len(aParts) {
  479. if aParts[i] > bParts[i] {
  480. return 1, true
  481. }
  482. if aParts[i] < bParts[i] {
  483. return -1, true
  484. }
  485. }
  486. return 0, true
  487. }
  488. func parseVersionParts(version string) ([3]int, bool) {
  489. var result [3]int
  490. parts := strings.Split(normalizeVersionTag(version), ".")
  491. if len(parts) != 3 {
  492. return result, false
  493. }
  494. for i, part := range parts {
  495. n, err := strconv.Atoi(part)
  496. if err != nil {
  497. return result, false
  498. }
  499. result[i] = n
  500. }
  501. return result, true
  502. }
  503. func normalizeVersionTag(version string) string {
  504. return strings.TrimPrefix(strings.TrimSpace(version), "v")
  505. }
  506. func shellQuote(value string) string {
  507. return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'"
  508. }