1
0

web.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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. cadenceMemoryAlarm = "@every 1m"
  251. )
  252. // startTask schedules background jobs (Xray checks, traffic jobs, cron
  253. // jobs) which the panel relies on for periodic maintenance and monitoring.
  254. func (s *Server) startTask(restartXray bool) {
  255. if restartXray {
  256. err := s.xrayService.RestartXray(true)
  257. if err != nil {
  258. logger.Warning("start xray failed:", err)
  259. }
  260. }
  261. // Check whether xray is running every second
  262. s.cron.AddJob(cadenceXrayRunning, job.NewCheckXrayRunningJob())
  263. // Check if xray needs to be restarted every 30 seconds
  264. s.cron.AddFunc(cadenceXrayRestart, func() {
  265. if s.xrayService.IsNeedRestartAndSetFalse() {
  266. err := s.xrayService.RestartXray(false)
  267. if err != nil {
  268. logger.Error("restart xray failed:", err)
  269. }
  270. }
  271. })
  272. go func() {
  273. time.Sleep(time.Second * 5)
  274. s.cron.AddJob(cadenceXrayTraffic, job.NewXrayTrafficJob())
  275. }()
  276. // Reconcile mtproto (mtg) sidecars and scrape their traffic
  277. mtJob := job.NewMtprotoJob()
  278. s.cron.AddJob(cadenceMtproto, mtJob)
  279. go mtJob.Run()
  280. // check client ips from log file every 10 sec
  281. s.cron.AddJob(cadenceClientIPScan, job.NewCheckClientIpJob())
  282. s.cron.AddJob(cadenceNodeHeartbeat, job.NewNodeHeartbeatJob())
  283. s.cron.AddJob(cadenceNodeTraffic, job.NewNodeTrafficSyncJob())
  284. // Outbound subscription auto-refresh (respects per-sub updateInterval)
  285. s.cron.AddJob(cadenceOutboundSub, job.NewOutboundSubscriptionJob())
  286. // check client ips from log file every day
  287. s.cron.AddJob("@daily", job.NewClearLogsJob())
  288. s.cron.AddJob("@hourly", job.NewWarpIpJob())
  289. // Inbound traffic reset jobs
  290. // Run every hour
  291. s.cron.AddJob("@hourly", job.NewPeriodicTrafficResetJob("hourly"))
  292. // Run once a day, midnight
  293. s.cron.AddJob("@daily", job.NewPeriodicTrafficResetJob("daily"))
  294. // Run once a week, midnight between Sat/Sun
  295. s.cron.AddJob("@weekly", job.NewPeriodicTrafficResetJob("weekly"))
  296. // Run once a month, midnight, first of month
  297. s.cron.AddJob("@monthly", job.NewPeriodicTrafficResetJob("monthly"))
  298. // LDAP sync scheduling
  299. if ldapEnabled, _ := s.settingService.GetLdapEnable(); ldapEnabled {
  300. runtime, err := s.settingService.GetLdapSyncCron()
  301. if err != nil || runtime == "" {
  302. runtime = "@every 1m"
  303. }
  304. j := job.NewLdapSyncJob()
  305. // job has zero-value services with method receivers that read settings on demand
  306. s.cron.AddJob(runtime, j)
  307. }
  308. // Telegram-bot–dependent jobs: periodic stats report + callback-hash cleanup.
  309. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  310. if (err == nil) && (isTgbotenabled) {
  311. runtime, err := s.settingService.GetTgbotRuntime()
  312. if err != nil {
  313. logger.Warningf("Add NewStatsNotifyJob: failed to load runtime: %v; using default @daily", err)
  314. runtime = "@daily"
  315. } else if strings.TrimSpace(runtime) == "" {
  316. logger.Warning("Add NewStatsNotifyJob runtime is empty, using default @daily")
  317. runtime = "@daily"
  318. }
  319. logger.Infof("Tg notify enabled,run at %s", runtime)
  320. if _, err = s.cron.AddJob(runtime, job.NewStatsNotifyJob()); err != nil {
  321. logger.Warningf("Add NewStatsNotifyJob: failed to schedule runtime %q: %v", runtime, err)
  322. }
  323. // check for Telegram bot callback query hash storage reset
  324. s.cron.AddJob(cadenceCheckHash, job.NewCheckHashStorageJob())
  325. }
  326. // CPU monitor publishes cpu.high events; register it whenever any notifier
  327. // (Telegram or Email) wants them, independent of the Telegram bot being on.
  328. if s.cpuAlarmWanted() {
  329. s.cron.AddJob(cadenceCPUAlarm, job.NewCheckCpuJob())
  330. }
  331. // Memory monitor publishes memory.high events; register it whenever any notifier wants them.
  332. if s.memoryAlarmWanted() {
  333. s.cron.AddJob(cadenceMemoryAlarm, job.NewCheckMemJob())
  334. }
  335. }
  336. // cpuAlarmWanted reports whether any notifier is configured to receive cpu.high
  337. // alerts, so the minute-long blocking CPU sampler only runs when it's needed.
  338. func (s *Server) cpuAlarmWanted() bool {
  339. wants := func(events string, threshold int) bool {
  340. if threshold <= 0 {
  341. return false
  342. }
  343. for e := range strings.SplitSeq(events, ",") {
  344. if strings.TrimSpace(e) == string(eventbus.EventCPUHigh) {
  345. return true
  346. }
  347. }
  348. return false
  349. }
  350. if on, _ := s.settingService.GetTgbotEnabled(); on {
  351. events, _ := s.settingService.GetTgEnabledEvents()
  352. cpu, _ := s.settingService.GetTgCpu()
  353. if wants(events, cpu) {
  354. return true
  355. }
  356. }
  357. if on, _ := s.settingService.GetSmtpEnable(); on {
  358. events, _ := s.settingService.GetSmtpEnabledEvents()
  359. cpu, _ := s.settingService.GetSmtpCpu()
  360. if wants(events, cpu) {
  361. return true
  362. }
  363. }
  364. return false
  365. }
  366. // memoryAlarmWanted reports whether any notifier is configured to receive memory.high alerts.
  367. func (s *Server) memoryAlarmWanted() bool {
  368. wants := func(events string, threshold int) bool {
  369. if threshold <= 0 {
  370. return false
  371. }
  372. for _, e := range strings.Split(events, ",") {
  373. if strings.TrimSpace(e) == string(eventbus.EventMemoryHigh) {
  374. return true
  375. }
  376. }
  377. return false
  378. }
  379. if on, _ := s.settingService.GetTgbotEnabled(); on {
  380. events, _ := s.settingService.GetTgEnabledEvents()
  381. mem, _ := s.settingService.GetTgMemory()
  382. if wants(events, mem) {
  383. return true
  384. }
  385. }
  386. if on, _ := s.settingService.GetSmtpEnable(); on {
  387. events, _ := s.settingService.GetSmtpEnabledEvents()
  388. mem, _ := s.settingService.GetSmtpMemory()
  389. if wants(events, mem) {
  390. return true
  391. }
  392. }
  393. return false
  394. }
  395. // Start initializes and starts the web server with configured settings, routes, and background jobs.
  396. func (s *Server) Start() (err error) {
  397. return s.start(true, true)
  398. }
  399. func (s *Server) StartPanelOnly() (err error) {
  400. return s.start(false, true)
  401. }
  402. func (s *Server) start(restartXray bool, startTgBot bool) (err error) {
  403. // This is an anonymous function, no function name
  404. defer func() {
  405. if err != nil {
  406. s.Stop()
  407. }
  408. }()
  409. loc, err := s.settingService.GetTimeLocation()
  410. if err != nil {
  411. return err
  412. }
  413. service.StartTrafficWriter()
  414. // cron.Recover wraps every job so a panic is logged and the scheduler keeps
  415. // running, instead of the panic taking down the whole panel process.
  416. s.cron = cron.New(cron.WithLocation(loc), cron.WithSeconds(), cron.WithChain(cron.Recover(cron.PrintfLogger(cronPanicLogger{}))))
  417. s.cron.Start()
  418. // Wire the inbound-runtime manager once so InboundService can route
  419. // add/update/delete to either the local xray or a remote node panel.
  420. // The closures bridge into XrayService (which owns the running xray
  421. // process state) without forcing the runtime package to import service.
  422. runtime.SetManager(runtime.NewManager(runtime.LocalDeps{
  423. APIPort: func() int { return s.xrayService.GetXrayAPIPort() },
  424. SetNeedRestart: func() { s.xrayService.SetToNeedRestart() },
  425. }))
  426. runtime.GetManager().SetNodeEgressResolver(&s.settingService)
  427. // Supply the master client certificate for nodes in mtls mode. Issued lazily
  428. // from the node CA on first use; runtime stays free of a service import.
  429. runtime.SetMasterClientCertProvider(func() (tls.Certificate, error) {
  430. ck, err := s.settingService.EnsureMasterClientCert()
  431. if err != nil {
  432. return tls.Certificate{}, err
  433. }
  434. return tls.X509KeyPair(ck.CertPEM, ck.KeyPEM)
  435. })
  436. engine, err := s.initRouter()
  437. if err != nil {
  438. return err
  439. }
  440. certFile, err := s.settingService.GetCertFile()
  441. if err != nil {
  442. return err
  443. }
  444. keyFile, err := s.settingService.GetKeyFile()
  445. if err != nil {
  446. return err
  447. }
  448. listen, err := s.settingService.GetListen()
  449. if err != nil {
  450. return err
  451. }
  452. port, err := s.settingService.GetPort()
  453. if err != nil {
  454. return err
  455. }
  456. if envPort, configured, envErr := config.GetPortOverride(); configured {
  457. if envErr != nil {
  458. logger.Warning("Ignoring invalid XUI_PORT; using configured web port:", port, envErr)
  459. } else {
  460. port = envPort
  461. logger.Info("Using XUI_PORT override for web panel port:", port)
  462. }
  463. }
  464. listenAddr := net.JoinHostPort(listen, strconv.Itoa(port))
  465. listener, err := net.Listen("tcp", listenAddr)
  466. if err != nil {
  467. return err
  468. }
  469. if certFile != "" || keyFile != "" {
  470. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  471. if err == nil {
  472. c := &tls.Config{
  473. Certificates: []tls.Certificate{cert},
  474. }
  475. // Opt-in node mTLS: when a trust CA is configured, request and verify
  476. // client certs (VerifyClientCertIfGiven keeps browsers working). With
  477. // no CA the listener is unchanged.
  478. if pool, perr := s.settingService.NodeMtlsClientCAPool(); perr != nil {
  479. logger.Warning("node mTLS: failed to build client CA trust pool:", perr)
  480. } else if pool != nil {
  481. applyNodeMtls(c, pool)
  482. logger.Info("Node mTLS enabled: verifying client certificates for the node API")
  483. }
  484. listener = network.NewAutoHttpsListener(listener)
  485. listener = tls.NewListener(listener, c)
  486. logger.Info("Web server running HTTPS on", listener.Addr())
  487. } else {
  488. logger.Error("Error loading certificates:", err)
  489. logger.Info("Web server running HTTP on", listener.Addr())
  490. }
  491. } else {
  492. logger.Info("Web server running HTTP on", listener.Addr())
  493. }
  494. s.listener = listener
  495. s.httpServer = &http.Server{
  496. Handler: engine,
  497. ReadHeaderTimeout: 5 * time.Second,
  498. ReadTimeout: 30 * time.Second,
  499. WriteTimeout: 30 * time.Second,
  500. IdleTimeout: 120 * time.Second,
  501. }
  502. go func() {
  503. s.httpServer.Serve(listener)
  504. }()
  505. // Create event bus before startTask so jobs can use it
  506. s.bus = eventbus.New(eventbus.DefaultBufferSize)
  507. service.SetEventBus(s.bus)
  508. job.EventBus = s.bus
  509. tgbot.EventBus = s.bus
  510. // Wire xray crash callback BEFORE startTask so it's ready
  511. xray.OnCrash = func(err error) {
  512. if s.bus != nil {
  513. s.bus.Publish(eventbus.Event{
  514. Type: eventbus.EventXrayCrash,
  515. Data: err.Error(),
  516. })
  517. }
  518. }
  519. // Register email subscriber (always — it checks smtpEnable at runtime)
  520. emailService := email.NewEmailService(s.settingService)
  521. emailSub := email.NewSubscriber(s.settingService, emailService)
  522. s.bus.Subscribe("email-notifier", emailSub.HandleEvent)
  523. // Wire email service to controller for test endpoint
  524. controller.SetEmailService(emailService)
  525. // Wire Telegram test function to controller
  526. controller.SetTestTgFunc(func() error {
  527. if !s.tgbotService.IsRunning() {
  528. return fmt.Errorf("telegram bot is not running (check token and chat ID)")
  529. }
  530. if err := s.tgbotService.TestConnection(); err != nil {
  531. return fmt.Errorf("telegram API test failed: %w", err)
  532. }
  533. s.tgbotService.SendMsgToTgbotAdmins("✅ Test message from 3x-ui")
  534. return nil
  535. })
  536. s.startTask(restartXray)
  537. if startTgBot {
  538. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  539. if (err == nil) && (isTgbotenabled) {
  540. tgBot := s.tgbotService.NewTgbot()
  541. tgBot.Start(i18nFS)
  542. // Subscribe Telegram notifications for event bus
  543. s.bus.Subscribe("tg-notifier", s.tgbotService.HandleEvent)
  544. }
  545. }
  546. return nil
  547. }
  548. // Stop gracefully shuts down the web server, stops Xray, cron jobs, and Telegram bot.
  549. func (s *Server) Stop() error {
  550. return s.stop(true, true)
  551. }
  552. func (s *Server) StopPanelOnly() error {
  553. return s.stop(false, true)
  554. }
  555. func (s *Server) stop(stopXray bool, stopTgBot bool) error {
  556. s.cancel()
  557. if stopXray {
  558. s.xrayService.StopXray()
  559. mtproto.GetManager().StopAll()
  560. }
  561. if s.cron != nil {
  562. s.cron.Stop()
  563. }
  564. if s.bus != nil {
  565. s.bus.Stop()
  566. }
  567. if err := service.PersistSystemMetrics(); err != nil {
  568. logger.Warning("persist system metrics on shutdown failed:", err)
  569. }
  570. if stopXray {
  571. service.StopTrafficWriter()
  572. }
  573. if stopTgBot && s.tgbotService.IsRunning() {
  574. s.tgbotService.Stop()
  575. }
  576. // Gracefully stop WebSocket hub
  577. if s.wsHub != nil {
  578. s.wsHub.Stop()
  579. }
  580. var err1 error
  581. var err2 error
  582. if s.httpServer != nil {
  583. shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
  584. defer shutdownCancel()
  585. err1 = s.httpServer.Shutdown(shutdownCtx)
  586. }
  587. if s.listener != nil {
  588. err2 = s.listener.Close()
  589. }
  590. return common.Combine(err1, err2)
  591. }
  592. // GetCtx returns the server's context for cancellation and deadline management.
  593. func (s *Server) GetCtx() context.Context {
  594. return s.ctx
  595. }
  596. // GetCron returns the server's cron scheduler instance.
  597. func (s *Server) GetCron() *cron.Cron {
  598. return s.cron
  599. }
  600. // GetWSHub returns the WebSocket hub instance.
  601. func (s *Server) GetWSHub() any {
  602. return s.wsHub
  603. }
  604. func (s *Server) RestartXray() error {
  605. return s.xrayService.RestartXray(true)
  606. }