panel.go 18 KB

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