web.go 22 KB

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