panel.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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. proxyEnv := updateProxyEnvVars()
  229. if systemdRun, err := exec.LookPath("systemd-run"); err == nil {
  230. unitName := fmt.Sprintf("x-ui-web-update-%d", time.Now().Unix())
  231. args := []string{
  232. "--unit", unitName,
  233. "--setenv", "XUI_MAIN_FOLDER=" + mainFolder,
  234. "--setenv", "XUI_SERVICE=" + serviceFolder,
  235. "--setenv", "XUI_UPDATE_TAG=" + updateTag,
  236. "--setenv", runIDEnv,
  237. "--setenv", statusFileEnv,
  238. }
  239. for _, kv := range proxyEnv {
  240. args = append(args, "--setenv", kv)
  241. }
  242. args = append(args, bash, "-lc", updateScript)
  243. cmd := exec.CommandContext(context.Background(), systemdRun, args...)
  244. out, err := cmd.CombinedOutput()
  245. if err != nil {
  246. output := strings.TrimSpace(string(out))
  247. if !strings.Contains(output, "System has not been booted with systemd") &&
  248. !strings.Contains(output, "Failed to connect to bus") {
  249. _ = os.Remove(scriptPath)
  250. return 0, fmt.Errorf("failed to start panel update job: %w: %s", err, output)
  251. }
  252. logger.Warning("systemd-run is unavailable, falling back to detached update process:", output)
  253. } else {
  254. logger.Infof("started panel update job via systemd-run unit %s", unitName)
  255. launched = true
  256. return runID, nil
  257. }
  258. }
  259. cmd := exec.CommandContext(context.Background(), bash, "-lc", updateScript)
  260. cmd.Env = append(os.Environ(),
  261. "XUI_MAIN_FOLDER="+mainFolder,
  262. "XUI_SERVICE="+serviceFolder,
  263. "XUI_UPDATE_TAG="+updateTag,
  264. runIDEnv,
  265. statusFileEnv,
  266. )
  267. setDetachedProcess(cmd)
  268. if err := cmd.Start(); err != nil {
  269. _ = os.Remove(scriptPath)
  270. return 0, fmt.Errorf("failed to start panel update job: %w", err)
  271. }
  272. if err := cmd.Process.Release(); err != nil {
  273. logger.Warning("failed to release panel update process:", err)
  274. }
  275. logger.Infof("started panel update job with pid %d", cmd.Process.Pid)
  276. recordUpdatePID(cmd.Process.Pid)
  277. launched = true
  278. return runID, nil
  279. }
  280. // updateProxyEnvVars forwards ambient proxy env vars to systemd-run's child,
  281. // which (unlike the bash fallback) inherits nothing but --setenv.
  282. func updateProxyEnvVars() []string {
  283. var out []string
  284. for _, key := range []string{"https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY", "http_proxy", "HTTP_PROXY", "no_proxy", "NO_PROXY"} {
  285. if v := os.Getenv(key); v != "" {
  286. out = append(out, key+"="+v)
  287. }
  288. }
  289. return out
  290. }
  291. // acquireUpdateSlot claims the single in-flight-update slot for runID. It
  292. // refuses while another run is genuinely still in flight, but grants the
  293. // slot immediately once that run's own status file reports a terminal
  294. // result (success or failure) -- a fast failure shouldn't force the next
  295. // attempt to wait out updateStaleAfter for no reason. Past updateStaleAfter
  296. // with no terminal status yet, it grants the slot anyway UNLESS the process
  297. // we recorded (updatePID) is confirmed still alive, so a merely-slow run
  298. // isn't mistaken for a crashed one; past updateHardCeiling it grants the
  299. // slot unconditionally regardless of liveness, so a truly wedged run can
  300. // never lock out retries forever.
  301. func acquireUpdateSlot(runID int64) bool {
  302. updateMu.Lock()
  303. defer updateMu.Unlock()
  304. if updateRunning && !previousRunIsTerminal() {
  305. elapsed := time.Since(updateStarted)
  306. if elapsed < updateHardCeiling {
  307. stale := elapsed >= updateStaleAfter
  308. alive := updatePID > 0 && processAlive(updatePID)
  309. if !stale || alive {
  310. return false
  311. }
  312. }
  313. }
  314. updateRunning = true
  315. updateStarted = time.Now()
  316. updateRunID = runID
  317. updatePID = 0
  318. return true
  319. }
  320. // recordUpdatePID notes the PID of the detached update.sh process the
  321. // current slot is tracking, so a later acquireUpdateSlot call can check
  322. // whether it is actually still running instead of only how long ago it
  323. // started. Only reachable for the detached-fallback launch path -- the
  324. // systemd-run path never learns update.sh's own PID, since the process it
  325. // directly observes (systemd-run) has already exited by the time it returns.
  326. func recordUpdatePID(pid int) {
  327. updateMu.Lock()
  328. updatePID = pid
  329. updateMu.Unlock()
  330. }
  331. // previousRunIsTerminal reports whether the run currently recorded in
  332. // updateRunID has reached success or failure per its status file. Must be
  333. // called with updateMu held.
  334. func previousRunIsTerminal() bool {
  335. status := (&PanelService{}).GetUpdateStatus()
  336. return status.RunID == strconv.FormatInt(updateRunID, 10) && status.State != updateStatePending
  337. }
  338. func releaseUpdateSlot() {
  339. updateMu.Lock()
  340. updateRunning = false
  341. updateMu.Unlock()
  342. }
  343. func downloadPanelUpdater() (string, error) {
  344. client := (&service.SettingService{}).NewProxiedHTTPClient(15 * time.Second)
  345. req, reqErr := http.NewRequestWithContext(context.Background(), http.MethodGet, panelUpdaterURL, nil)
  346. if reqErr != nil {
  347. return "", fmt.Errorf("download panel updater: %w", reqErr)
  348. }
  349. resp, err := client.Do(req)
  350. if err != nil {
  351. return "", fmt.Errorf("download panel updater: %w", err)
  352. }
  353. defer resp.Body.Close()
  354. if resp.StatusCode != http.StatusOK {
  355. return "", fmt.Errorf("download panel updater: unexpected HTTP %d", resp.StatusCode)
  356. }
  357. file, err := os.CreateTemp("", "3x-ui-update-*.sh")
  358. if err != nil {
  359. return "", err
  360. }
  361. path := file.Name()
  362. ok := false
  363. defer func() {
  364. _ = file.Close()
  365. if !ok {
  366. _ = os.Remove(path)
  367. }
  368. }()
  369. n, err := io.Copy(file, io.LimitReader(resp.Body, maxPanelUpdaterBytes+1))
  370. if err != nil {
  371. return "", fmt.Errorf("write panel updater: %w", err)
  372. }
  373. if n == 0 {
  374. return "", fmt.Errorf("panel updater download is empty")
  375. }
  376. if n > maxPanelUpdaterBytes {
  377. return "", fmt.Errorf("panel updater exceeds %d bytes", maxPanelUpdaterBytes)
  378. }
  379. if err := file.Chmod(0o700); err != nil {
  380. return "", err
  381. }
  382. ok = true
  383. return path, nil
  384. }
  385. func fetchLatestPanelVersion() (string, error) {
  386. release, err := fetchPanelRelease("")
  387. if err != nil {
  388. return "", err
  389. }
  390. if release.TagName == "" {
  391. return "", fmt.Errorf("latest panel release tag is empty")
  392. }
  393. return release.TagName, nil
  394. }
  395. // fetchPanelRelease fetches a release from GitHub. An empty tag resolves the
  396. // latest stable release; a non-empty tag (e.g. dev-latest) resolves that tag.
  397. func fetchPanelRelease(tag string) (*service.Release, error) {
  398. url := "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest"
  399. if tag != "" {
  400. url = "https://api.github.com/repos/MHSanaei/3x-ui/releases/tags/" + tag
  401. }
  402. client := (&service.SettingService{}).NewProxiedHTTPClient(10 * time.Second)
  403. req, reqErr := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil)
  404. if reqErr != nil {
  405. return nil, reqErr
  406. }
  407. resp, err := client.Do(req)
  408. if err != nil {
  409. return nil, err
  410. }
  411. defer resp.Body.Close()
  412. if resp.StatusCode != http.StatusOK {
  413. return nil, fmt.Errorf("GitHub API returned status %d: %s", resp.StatusCode, resp.Status)
  414. }
  415. var release service.Release
  416. if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
  417. return nil, err
  418. }
  419. return &release, nil
  420. }
  421. // extractReleaseCommit reads the build commit recorded in the dev release: first
  422. // the `commit=<sha>` marker the CI writes into the body, falling back to the
  423. // tag's target commit.
  424. func extractReleaseCommit(release *service.Release) string {
  425. if m := releaseCommitRegex.FindStringSubmatch(release.Body); m != nil {
  426. return strings.ToLower(m[1])
  427. }
  428. if isCommitSHA(release.TargetCommitish) {
  429. return strings.ToLower(release.TargetCommitish)
  430. }
  431. return ""
  432. }
  433. func isCommitSHA(s string) bool {
  434. s = strings.TrimSpace(s)
  435. if len(s) < 7 || len(s) > 40 {
  436. return false
  437. }
  438. for _, r := range s {
  439. if (r < '0' || r > '9') && (r < 'a' || r > 'f') && (r < 'A' || r > 'F') {
  440. return false
  441. }
  442. }
  443. return true
  444. }
  445. func shortCommit(sha string) string {
  446. sha = strings.TrimSpace(sha)
  447. if len(sha) > 8 {
  448. return sha[:8]
  449. }
  450. return sha
  451. }
  452. // commitsEqual compares a short (injected) commit against a full release commit
  453. // by prefix, so an 8-char build stamp matches the 40-char release SHA.
  454. func commitsEqual(a, b string) bool {
  455. a = strings.ToLower(strings.TrimSpace(a))
  456. b = strings.ToLower(strings.TrimSpace(b))
  457. if a == "" || b == "" {
  458. return false
  459. }
  460. if len(a) > len(b) {
  461. a, b = b, a
  462. }
  463. return strings.HasPrefix(b, a)
  464. }
  465. func resolveUpdateFolders() (string, string) {
  466. mainFolder := os.Getenv("XUI_MAIN_FOLDER")
  467. if mainFolder == "" {
  468. if exePath, err := os.Executable(); err == nil {
  469. mainFolder = filepath.Dir(exePath)
  470. }
  471. }
  472. if mainFolder == "" {
  473. mainFolder = "/usr/local/x-ui"
  474. }
  475. serviceFolder := os.Getenv("XUI_SERVICE")
  476. if serviceFolder == "" {
  477. serviceFolder = "/etc/systemd/system"
  478. }
  479. return mainFolder, serviceFolder
  480. }
  481. func isNewerVersion(latest string, current string) bool {
  482. cmp, ok := compareVersionStrings(latest, current)
  483. if !ok {
  484. return normalizeVersionTag(latest) != normalizeVersionTag(current)
  485. }
  486. return cmp > 0
  487. }
  488. func compareVersionStrings(a string, b string) (int, bool) {
  489. aParts, okA := parseVersionParts(a)
  490. bParts, okB := parseVersionParts(b)
  491. if !okA || !okB {
  492. return 0, false
  493. }
  494. for i := range len(aParts) {
  495. if aParts[i] > bParts[i] {
  496. return 1, true
  497. }
  498. if aParts[i] < bParts[i] {
  499. return -1, true
  500. }
  501. }
  502. return 0, true
  503. }
  504. func parseVersionParts(version string) ([3]int, bool) {
  505. var result [3]int
  506. parts := strings.Split(normalizeVersionTag(version), ".")
  507. if len(parts) != 3 {
  508. return result, false
  509. }
  510. for i, part := range parts {
  511. n, err := strconv.Atoi(part)
  512. if err != nil {
  513. return result, false
  514. }
  515. result[i] = n
  516. }
  517. return result, true
  518. }
  519. func normalizeVersionTag(version string) string {
  520. return strings.TrimPrefix(strings.TrimSpace(version), "v")
  521. }
  522. func shellQuote(value string) string {
  523. return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'"
  524. }