web.go 23 KB

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