1
0

web.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. // Package web provides the main web server implementation for the 3x-ui panel,
  2. // including HTTP/HTTPS serving, routing, templates, and background job scheduling.
  3. package web
  4. import (
  5. "context"
  6. "crypto/tls"
  7. "embed"
  8. "fmt"
  9. "io"
  10. "io/fs"
  11. "net"
  12. "net/http"
  13. "os"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/mhsanaei/3x-ui/v3/internal/config"
  18. "github.com/mhsanaei/3x-ui/v3/internal/eventbus"
  19. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  20. "github.com/mhsanaei/3x-ui/v3/internal/mtproto"
  21. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  22. "github.com/mhsanaei/3x-ui/v3/internal/web/controller"
  23. "github.com/mhsanaei/3x-ui/v3/internal/web/job"
  24. "github.com/mhsanaei/3x-ui/v3/internal/web/locale"
  25. "github.com/mhsanaei/3x-ui/v3/internal/web/middleware"
  26. "github.com/mhsanaei/3x-ui/v3/internal/web/network"
  27. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  28. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  29. "github.com/mhsanaei/3x-ui/v3/internal/web/service/email"
  30. "github.com/mhsanaei/3x-ui/v3/internal/web/service/panel"
  31. "github.com/mhsanaei/3x-ui/v3/internal/web/service/tgbot"
  32. "github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
  33. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  34. "github.com/gin-contrib/gzip"
  35. "github.com/gin-contrib/sessions"
  36. "github.com/gin-contrib/sessions/cookie"
  37. "github.com/gin-gonic/gin"
  38. "github.com/robfig/cron/v3"
  39. )
  40. //go:embed translation/*
  41. var i18nFS embed.FS
  42. // distFS embeds the Vite-built frontend (internal/web/dist/). Every user-facing
  43. // HTML route is served straight out of this FS — the legacy Go
  44. // templates and `web/assets/` tree are gone post-Phase 8.
  45. //go:embed all:dist
  46. var distFS embed.FS
  47. var startTime = time.Now()
  48. // wrapDistFS adapts the embedded `dist/` directory so it can be mounted
  49. // as the panel's `/assets/` static route. Vite emits its bundled JS/CSS
  50. // under `dist/assets/`; serving the FS rooted at `dist/assets` makes
  51. // `/assets/<hash>.js` URLs resolve directly.
  52. type wrapDistFS struct {
  53. embed.FS
  54. }
  55. func (f *wrapDistFS) Open(name string) (fs.File, error) {
  56. file, err := f.FS.Open("dist/assets/" + name)
  57. if err != nil {
  58. return nil, err
  59. }
  60. return &wrapAssetsFile{
  61. File: file,
  62. }, nil
  63. }
  64. type wrapAssetsFile struct {
  65. fs.File
  66. }
  67. func (f *wrapAssetsFile) Stat() (fs.FileInfo, error) {
  68. info, err := f.File.Stat()
  69. if err != nil {
  70. return nil, err
  71. }
  72. return &wrapAssetsFileInfo{
  73. FileInfo: info,
  74. }, nil
  75. }
  76. type wrapAssetsFileInfo struct {
  77. fs.FileInfo
  78. }
  79. func (f *wrapAssetsFileInfo) ModTime() time.Time {
  80. return startTime
  81. }
  82. // EmbeddedDist returns the embedded Vite-built frontend filesystem.
  83. // Controllers serve their HTML out of this FS via the dist-page handler
  84. // installed in NewEngine().
  85. func EmbeddedDist() embed.FS {
  86. return distFS
  87. }
  88. // Server represents the main web server for the 3x-ui panel with controllers, services, and scheduled jobs.
  89. type Server struct {
  90. httpServer *http.Server
  91. listener net.Listener
  92. index *controller.IndexController
  93. panel *controller.XUIController
  94. api *controller.APIController
  95. ws *controller.WebSocketController
  96. xrayService service.XrayService
  97. settingService service.SettingService
  98. tgbotService tgbot.Tgbot
  99. wsHub *websocket.Hub
  100. bus *eventbus.Bus
  101. cron *cron.Cron
  102. ctx context.Context
  103. cancel context.CancelFunc
  104. }
  105. // NewServer creates a new web server instance with a cancellable context.
  106. func NewServer() *Server {
  107. ctx, cancel := context.WithCancel(context.Background())
  108. return &Server{
  109. ctx: ctx,
  110. cancel: cancel,
  111. }
  112. }
  113. func (s *Server) isDirectHTTPSConfigured() bool {
  114. certFile, certErr := s.settingService.GetCertFile()
  115. keyFile, keyErr := s.settingService.GetKeyFile()
  116. if certErr != nil || keyErr != nil || certFile == "" || keyFile == "" {
  117. return false
  118. }
  119. _, err := tls.LoadX509KeyPair(certFile, keyFile)
  120. return err == nil
  121. }
  122. // initRouter initializes Gin, registers middleware, templates, static
  123. // assets, controllers and returns the configured engine.
  124. func (s *Server) initRouter() (*gin.Engine, error) {
  125. if config.IsDebug() {
  126. gin.SetMode(gin.DebugMode)
  127. } else {
  128. gin.DefaultWriter = io.Discard
  129. gin.DefaultErrorWriter = io.Discard
  130. gin.SetMode(gin.ReleaseMode)
  131. }
  132. engine := gin.Default()
  133. directHTTPS := s.isDirectHTTPSConfigured()
  134. sendHSTS := directHTTPS && !config.IsSkipHSTS()
  135. engine.Use(middleware.SecurityHeadersMiddleware(sendHSTS))
  136. // Cap request bodies on state-changing requests so a stolen session/API
  137. // token or a buggy client can't force large allocations or long DB
  138. // transactions via bulk create/attach/import endpoints. GET/HEAD/OPTIONS
  139. // carry no body and are left untouched. importDB restores a full SQLite
  140. // backup that legitimately exceeds the cap, so it's exempt. Follow-up: make
  141. // the limit a setting.
  142. const maxRequestBodyBytes = 10 << 20 // 10 MiB
  143. engine.Use(middleware.MaxBodyBytes(maxRequestBodyBytes, "/panel/api/server/importDB"))
  144. webDomain, err := s.settingService.GetWebDomain()
  145. if err != nil {
  146. return nil, err
  147. }
  148. if webDomain != "" {
  149. engine.Use(middleware.DomainValidatorMiddleware(webDomain))
  150. }
  151. secret, err := s.settingService.GetSecret()
  152. if err != nil {
  153. return nil, err
  154. }
  155. basePath, err := s.settingService.GetBasePath()
  156. if err != nil {
  157. return nil, err
  158. }
  159. engine.Use(gzip.Gzip(gzip.DefaultCompression))
  160. assetsBasePath := basePath + "assets/"
  161. store := cookie.NewStore(secret)
  162. // Configure default session cookie options, including expiration (MaxAge)
  163. sessionOptions := sessions.Options{
  164. Path: basePath,
  165. HttpOnly: true,
  166. Secure: directHTTPS,
  167. SameSite: http.SameSiteLaxMode,
  168. }
  169. if sessionMaxAge, err := s.settingService.GetSessionMaxAge(); err == nil && sessionMaxAge > 0 {
  170. sessionOptions.MaxAge = sessionMaxAge * 60 // minutes -> seconds
  171. }
  172. store.Options(sessionOptions)
  173. engine.Use(sessions.Sessions("3x-ui", store))
  174. engine.Use(func(c *gin.Context) {
  175. c.Set("base_path", basePath)
  176. })
  177. engine.Use(func(c *gin.Context) {
  178. uri := c.Request.RequestURI
  179. if strings.HasPrefix(uri, assetsBasePath) {
  180. c.Header("Cache-Control", "max-age=31536000")
  181. }
  182. })
  183. // init i18n — still used by backend strings (errors, log messages,
  184. // SubPage menu entries) even though the Go template engine is gone.
  185. err = locale.InitLocalizer(i18nFS, &s.settingService)
  186. if err != nil {
  187. return nil, err
  188. }
  189. engine.Use(locale.LocalizerMiddleware())
  190. // `/assets/` serves the Vite-built bundle. In dev we pull from disk
  191. // so the Vite watcher's incremental rebuilds show up without
  192. // restarting the binary; in prod we serve the embedded dist FS
  193. // rooted at `dist/assets/`.
  194. if config.IsDebug() {
  195. engine.StaticFS(basePath+"assets", http.FS(os.DirFS("internal/web/dist/assets")))
  196. } else {
  197. engine.StaticFS(basePath+"assets", http.FS(&wrapDistFS{FS: distFS}))
  198. }
  199. // Hand the embedded `dist/` filesystem to the controller package
  200. // before any HTML-serving controller is constructed. Phase 8
  201. // cutover: every HTML route reads from internal/web/dist/ instead of
  202. // rendering a legacy template.
  203. controller.SetDistFS(distFS)
  204. g := engine.Group(basePath)
  205. s.index = controller.NewIndexController(g)
  206. s.panel = controller.NewXUIController(g)
  207. g.GET("/panel/api/openapi.json", controller.ServeOpenAPISpec)
  208. s.api = controller.NewAPIController(g)
  209. // Initialize WebSocket hub
  210. s.wsHub = websocket.NewHub()
  211. go s.wsHub.Run()
  212. // Initialize WebSocket controller — service owns per-connection pumps,
  213. // controller is HTTP-layer only (auth + upgrade).
  214. s.ws = controller.NewWebSocketController(panel.NewWebSocketService(s.wsHub))
  215. // Register WebSocket route with basePath (g already has basePath prefix)
  216. g.GET("/ws", s.ws.HandleWebSocket)
  217. // Chrome DevTools endpoint for debugging web apps
  218. engine.GET("/.well-known/appspecific/com.chrome.devtools.json", func(c *gin.Context) {
  219. c.JSON(http.StatusOK, gin.H{})
  220. })
  221. // Add a catch-all route to handle undefined paths and return 404
  222. engine.NoRoute(func(c *gin.Context) {
  223. c.AbortWithStatus(http.StatusNotFound)
  224. })
  225. return engine, nil
  226. }
  227. // Background-job cadences. Centralized here as the single tuning surface; the
  228. // values are unchanged from the historical hardcoded cron specs. Follow-up:
  229. // make these configurable via settings, add per-tick jitter to de-synchronize
  230. // fleet load, skip expensive jobs when no WebSocket clients are connected or
  231. // node/xray state is unchanged, and export per-job duration/skipped/error
  232. // counters.
  233. const (
  234. cadenceXrayRunning = "@every 1s"
  235. cadenceXrayRestart = "@every 30s"
  236. cadenceXrayTraffic = "@every 5s"
  237. cadenceMtproto = "@every 10s"
  238. cadenceClientIPScan = "@every 10s"
  239. cadenceNodeHeartbeat = "@every 5s"
  240. cadenceNodeTraffic = "@every 5s"
  241. cadenceOutboundSub = "@every 5m"
  242. cadenceCheckHash = "@every 2m"
  243. // cpu.Percent samples over a full minute (blocking), so a finer cadence just
  244. // stacks overlapping samplers; subscribers rate-limit alerts to 1/min anyway.
  245. cadenceCPUAlarm = "@every 1m"
  246. )
  247. // startTask schedules background jobs (Xray checks, traffic jobs, cron
  248. // jobs) which the panel relies on for periodic maintenance and monitoring.
  249. func (s *Server) startTask(restartXray bool) {
  250. if restartXray {
  251. err := s.xrayService.RestartXray(true)
  252. if err != nil {
  253. logger.Warning("start xray failed:", err)
  254. }
  255. }
  256. // Check whether xray is running every second
  257. s.cron.AddJob(cadenceXrayRunning, job.NewCheckXrayRunningJob())
  258. // Check if xray needs to be restarted every 30 seconds
  259. s.cron.AddFunc(cadenceXrayRestart, func() {
  260. if s.xrayService.IsNeedRestartAndSetFalse() {
  261. err := s.xrayService.RestartXray(false)
  262. if err != nil {
  263. logger.Error("restart xray failed:", err)
  264. }
  265. }
  266. })
  267. go func() {
  268. time.Sleep(time.Second * 5)
  269. s.cron.AddJob(cadenceXrayTraffic, job.NewXrayTrafficJob())
  270. }()
  271. // Reconcile mtproto (mtg) sidecars and scrape their traffic
  272. mtJob := job.NewMtprotoJob()
  273. s.cron.AddJob(cadenceMtproto, mtJob)
  274. go mtJob.Run()
  275. // check client ips from log file every 10 sec
  276. s.cron.AddJob(cadenceClientIPScan, job.NewCheckClientIpJob())
  277. s.cron.AddJob(cadenceNodeHeartbeat, job.NewNodeHeartbeatJob())
  278. s.cron.AddJob(cadenceNodeTraffic, job.NewNodeTrafficSyncJob())
  279. // Outbound subscription auto-refresh (respects per-sub updateInterval)
  280. s.cron.AddJob(cadenceOutboundSub, job.NewOutboundSubscriptionJob())
  281. // check client ips from log file every day
  282. s.cron.AddJob("@daily", job.NewClearLogsJob())
  283. s.cron.AddJob("@hourly", job.NewWarpIpJob())
  284. // Inbound traffic reset jobs
  285. // Run every hour
  286. s.cron.AddJob("@hourly", job.NewPeriodicTrafficResetJob("hourly"))
  287. // Run once a day, midnight
  288. s.cron.AddJob("@daily", job.NewPeriodicTrafficResetJob("daily"))
  289. // Run once a week, midnight between Sat/Sun
  290. s.cron.AddJob("@weekly", job.NewPeriodicTrafficResetJob("weekly"))
  291. // Run once a month, midnight, first of month
  292. s.cron.AddJob("@monthly", job.NewPeriodicTrafficResetJob("monthly"))
  293. // LDAP sync scheduling
  294. if ldapEnabled, _ := s.settingService.GetLdapEnable(); ldapEnabled {
  295. runtime, err := s.settingService.GetLdapSyncCron()
  296. if err != nil || runtime == "" {
  297. runtime = "@every 1m"
  298. }
  299. j := job.NewLdapSyncJob()
  300. // job has zero-value services with method receivers that read settings on demand
  301. s.cron.AddJob(runtime, j)
  302. }
  303. // Telegram-bot–dependent jobs: periodic stats report + callback-hash cleanup.
  304. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  305. if (err == nil) && (isTgbotenabled) {
  306. runtime, err := s.settingService.GetTgbotRuntime()
  307. if err != nil {
  308. logger.Warningf("Add NewStatsNotifyJob: failed to load runtime: %v; using default @daily", err)
  309. runtime = "@daily"
  310. } else if strings.TrimSpace(runtime) == "" {
  311. logger.Warning("Add NewStatsNotifyJob runtime is empty, using default @daily")
  312. runtime = "@daily"
  313. }
  314. logger.Infof("Tg notify enabled,run at %s", runtime)
  315. if _, err = s.cron.AddJob(runtime, job.NewStatsNotifyJob()); err != nil {
  316. logger.Warningf("Add NewStatsNotifyJob: failed to schedule runtime %q: %v", runtime, err)
  317. }
  318. // check for Telegram bot callback query hash storage reset
  319. s.cron.AddJob(cadenceCheckHash, job.NewCheckHashStorageJob())
  320. }
  321. // CPU monitor publishes cpu.high events; register it whenever any notifier
  322. // (Telegram or Email) wants them, independent of the Telegram bot being on.
  323. if s.cpuAlarmWanted() {
  324. s.cron.AddJob(cadenceCPUAlarm, job.NewCheckCpuJob())
  325. }
  326. }
  327. // cpuAlarmWanted reports whether any notifier is configured to receive cpu.high
  328. // alerts, so the minute-long blocking CPU sampler only runs when it's needed.
  329. func (s *Server) cpuAlarmWanted() bool {
  330. wants := func(events string, threshold int) bool {
  331. if threshold <= 0 {
  332. return false
  333. }
  334. for _, e := range strings.Split(events, ",") {
  335. if strings.TrimSpace(e) == string(eventbus.EventCPUHigh) {
  336. return true
  337. }
  338. }
  339. return false
  340. }
  341. if on, _ := s.settingService.GetTgbotEnabled(); on {
  342. events, _ := s.settingService.GetTgEnabledEvents()
  343. cpu, _ := s.settingService.GetTgCpu()
  344. if wants(events, cpu) {
  345. return true
  346. }
  347. }
  348. if on, _ := s.settingService.GetSmtpEnable(); on {
  349. events, _ := s.settingService.GetSmtpEnabledEvents()
  350. cpu, _ := s.settingService.GetSmtpCpu()
  351. if wants(events, cpu) {
  352. return true
  353. }
  354. }
  355. return false
  356. }
  357. // Start initializes and starts the web server with configured settings, routes, and background jobs.
  358. func (s *Server) Start() (err error) {
  359. return s.start(true, true)
  360. }
  361. func (s *Server) StartPanelOnly() (err error) {
  362. return s.start(false, true)
  363. }
  364. func (s *Server) start(restartXray bool, startTgBot bool) (err error) {
  365. // This is an anonymous function, no function name
  366. defer func() {
  367. if err != nil {
  368. s.Stop()
  369. }
  370. }()
  371. loc, err := s.settingService.GetTimeLocation()
  372. if err != nil {
  373. return err
  374. }
  375. service.StartTrafficWriter()
  376. s.cron = cron.New(cron.WithLocation(loc), cron.WithSeconds())
  377. s.cron.Start()
  378. // Wire the inbound-runtime manager once so InboundService can route
  379. // add/update/delete to either the local xray or a remote node panel.
  380. // The closures bridge into XrayService (which owns the running xray
  381. // process state) without forcing the runtime package to import service.
  382. runtime.SetManager(runtime.NewManager(runtime.LocalDeps{
  383. APIPort: func() int { return s.xrayService.GetXrayAPIPort() },
  384. SetNeedRestart: func() { s.xrayService.SetToNeedRestart() },
  385. }))
  386. runtime.GetManager().SetNodeEgressResolver(&s.settingService)
  387. // Supply the master client certificate for nodes in mtls mode. Issued lazily
  388. // from the node CA on first use; runtime stays free of a service import.
  389. runtime.SetMasterClientCertProvider(func() (tls.Certificate, error) {
  390. ck, err := s.settingService.EnsureMasterClientCert()
  391. if err != nil {
  392. return tls.Certificate{}, err
  393. }
  394. return tls.X509KeyPair(ck.CertPEM, ck.KeyPEM)
  395. })
  396. engine, err := s.initRouter()
  397. if err != nil {
  398. return err
  399. }
  400. certFile, err := s.settingService.GetCertFile()
  401. if err != nil {
  402. return err
  403. }
  404. keyFile, err := s.settingService.GetKeyFile()
  405. if err != nil {
  406. return err
  407. }
  408. listen, err := s.settingService.GetListen()
  409. if err != nil {
  410. return err
  411. }
  412. port, err := s.settingService.GetPort()
  413. if err != nil {
  414. return err
  415. }
  416. if envPort, configured, envErr := config.GetPortOverride(); configured {
  417. if envErr != nil {
  418. logger.Warning("Ignoring invalid XUI_PORT; using configured web port:", port, envErr)
  419. } else {
  420. port = envPort
  421. logger.Info("Using XUI_PORT override for web panel port:", port)
  422. }
  423. }
  424. listenAddr := net.JoinHostPort(listen, strconv.Itoa(port))
  425. listener, err := net.Listen("tcp", listenAddr)
  426. if err != nil {
  427. return err
  428. }
  429. if certFile != "" || keyFile != "" {
  430. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  431. if err == nil {
  432. c := &tls.Config{
  433. Certificates: []tls.Certificate{cert},
  434. }
  435. // Opt-in node mTLS: when a trust CA is configured, request and verify
  436. // client certs (VerifyClientCertIfGiven keeps browsers working). With
  437. // no CA the listener is unchanged.
  438. if pool, perr := s.settingService.NodeMtlsClientCAPool(); perr != nil {
  439. logger.Warning("node mTLS: failed to build client CA trust pool:", perr)
  440. } else if pool != nil {
  441. applyNodeMtls(c, pool)
  442. logger.Info("Node mTLS enabled: verifying client certificates for the node API")
  443. }
  444. listener = network.NewAutoHttpsListener(listener)
  445. listener = tls.NewListener(listener, c)
  446. logger.Info("Web server running HTTPS on", listener.Addr())
  447. } else {
  448. logger.Error("Error loading certificates:", err)
  449. logger.Info("Web server running HTTP on", listener.Addr())
  450. }
  451. } else {
  452. logger.Info("Web server running HTTP on", listener.Addr())
  453. }
  454. s.listener = listener
  455. s.httpServer = &http.Server{
  456. Handler: engine,
  457. ReadHeaderTimeout: 5 * time.Second,
  458. ReadTimeout: 30 * time.Second,
  459. WriteTimeout: 30 * time.Second,
  460. IdleTimeout: 120 * time.Second,
  461. }
  462. go func() {
  463. s.httpServer.Serve(listener)
  464. }()
  465. // Create event bus before startTask so jobs can use it
  466. s.bus = eventbus.New(eventbus.DefaultBufferSize)
  467. service.SetEventBus(s.bus)
  468. job.EventBus = s.bus
  469. tgbot.EventBus = s.bus
  470. // Wire xray crash callback BEFORE startTask so it's ready
  471. xray.OnCrash = func(err error) {
  472. if s.bus != nil {
  473. s.bus.Publish(eventbus.Event{
  474. Type: eventbus.EventXrayCrash,
  475. Data: err.Error(),
  476. })
  477. }
  478. }
  479. // Register email subscriber (always — it checks smtpEnable at runtime)
  480. emailService := email.NewEmailService(s.settingService)
  481. emailSub := email.NewSubscriber(s.settingService, emailService)
  482. s.bus.Subscribe("email-notifier", emailSub.HandleEvent)
  483. // Wire email service to controller for test endpoint
  484. controller.SetEmailService(emailService)
  485. // Wire Telegram test function to controller
  486. controller.SetTestTgFunc(func() error {
  487. if !s.tgbotService.IsRunning() {
  488. return fmt.Errorf("telegram bot is not running (check token and chat ID)")
  489. }
  490. if err := s.tgbotService.TestConnection(); err != nil {
  491. return fmt.Errorf("telegram API test failed: %w", err)
  492. }
  493. s.tgbotService.SendMsgToTgbotAdmins("✅ Test message from 3x-ui")
  494. return nil
  495. })
  496. s.startTask(restartXray)
  497. if startTgBot {
  498. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  499. if (err == nil) && (isTgbotenabled) {
  500. tgBot := s.tgbotService.NewTgbot()
  501. tgBot.Start(i18nFS)
  502. // Subscribe Telegram notifications for event bus
  503. s.bus.Subscribe("tg-notifier", s.tgbotService.HandleEvent)
  504. }
  505. }
  506. return nil
  507. }
  508. // Stop gracefully shuts down the web server, stops Xray, cron jobs, and Telegram bot.
  509. func (s *Server) Stop() error {
  510. return s.stop(true, true)
  511. }
  512. func (s *Server) StopPanelOnly() error {
  513. return s.stop(false, true)
  514. }
  515. func (s *Server) stop(stopXray bool, stopTgBot bool) error {
  516. s.cancel()
  517. if stopXray {
  518. s.xrayService.StopXray()
  519. mtproto.GetManager().StopAll()
  520. }
  521. if s.cron != nil {
  522. s.cron.Stop()
  523. }
  524. if s.bus != nil {
  525. s.bus.Stop()
  526. }
  527. if err := service.PersistSystemMetrics(); err != nil {
  528. logger.Warning("persist system metrics on shutdown failed:", err)
  529. }
  530. if stopXray {
  531. service.StopTrafficWriter()
  532. }
  533. if stopTgBot && s.tgbotService.IsRunning() {
  534. s.tgbotService.Stop()
  535. }
  536. // Gracefully stop WebSocket hub
  537. if s.wsHub != nil {
  538. s.wsHub.Stop()
  539. }
  540. var err1 error
  541. var err2 error
  542. if s.httpServer != nil {
  543. shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
  544. defer shutdownCancel()
  545. err1 = s.httpServer.Shutdown(shutdownCtx)
  546. }
  547. if s.listener != nil {
  548. err2 = s.listener.Close()
  549. }
  550. return common.Combine(err1, err2)
  551. }
  552. // GetCtx returns the server's context for cancellation and deadline management.
  553. func (s *Server) GetCtx() context.Context {
  554. return s.ctx
  555. }
  556. // GetCron returns the server's cron scheduler instance.
  557. func (s *Server) GetCron() *cron.Cron {
  558. return s.cron
  559. }
  560. // GetWSHub returns the WebSocket hub instance.
  561. func (s *Server) GetWSHub() any {
  562. return s.wsHub
  563. }
  564. func (s *Server) RestartXray() error {
  565. return s.xrayService.RestartXray(true)
  566. }