web.go 22 KB

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