web.go 20 KB

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