web.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  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. }
  343. }
  344. // cpuAlarmWanted reports whether any notifier is configured to receive cpu.high
  345. // alerts, so the minute-long blocking CPU sampler only runs when it's needed.
  346. func (s *Server) cpuAlarmWanted() bool {
  347. wants := func(events string, threshold int) bool {
  348. if threshold <= 0 {
  349. return false
  350. }
  351. for e := range strings.SplitSeq(events, ",") {
  352. if strings.TrimSpace(e) == string(eventbus.EventCPUHigh) {
  353. return true
  354. }
  355. }
  356. return false
  357. }
  358. if on, _ := s.settingService.GetTgbotEnabled(); on {
  359. events, _ := s.settingService.GetTgEnabledEvents()
  360. cpu, _ := s.settingService.GetTgCpu()
  361. if wants(events, cpu) {
  362. return true
  363. }
  364. }
  365. if on, _ := s.settingService.GetSmtpEnable(); on {
  366. events, _ := s.settingService.GetSmtpEnabledEvents()
  367. cpu, _ := s.settingService.GetSmtpCpu()
  368. if wants(events, cpu) {
  369. return true
  370. }
  371. }
  372. return false
  373. }
  374. // memoryAlarmWanted reports whether any notifier is configured to receive memory.high alerts.
  375. func (s *Server) memoryAlarmWanted() bool {
  376. wants := func(events string, threshold int) bool {
  377. if threshold <= 0 {
  378. return false
  379. }
  380. for e := range strings.SplitSeq(events, ",") {
  381. if strings.TrimSpace(e) == string(eventbus.EventMemoryHigh) {
  382. return true
  383. }
  384. }
  385. return false
  386. }
  387. if on, _ := s.settingService.GetTgbotEnabled(); on {
  388. events, _ := s.settingService.GetTgEnabledEvents()
  389. mem, _ := s.settingService.GetTgMemory()
  390. if wants(events, mem) {
  391. return true
  392. }
  393. }
  394. if on, _ := s.settingService.GetSmtpEnable(); on {
  395. events, _ := s.settingService.GetSmtpEnabledEvents()
  396. mem, _ := s.settingService.GetSmtpMemory()
  397. if wants(events, mem) {
  398. return true
  399. }
  400. }
  401. return false
  402. }
  403. // Start initializes and starts the web server with configured settings, routes, and background jobs.
  404. func (s *Server) Start() (err error) {
  405. return s.start(true, true)
  406. }
  407. func (s *Server) StartPanelOnly() (err error) {
  408. return s.start(false, true)
  409. }
  410. func (s *Server) start(restartXray bool, startTgBot bool) (err error) {
  411. // This is an anonymous function, no function name
  412. defer func() {
  413. if err != nil {
  414. s.Stop()
  415. }
  416. }()
  417. loc, err := s.settingService.GetTimeLocation()
  418. if err != nil {
  419. return err
  420. }
  421. service.StartTrafficWriter()
  422. // SkipIfStillRunning stops a slow job (e.g. the 5s traffic poll on a large
  423. // install) from overlapping itself: two concurrent runs of the same job race
  424. // the shared xrayAPI — leaking a grpc connection — and the StatsLastValues
  425. // map, whose concurrent write is a fatal runtime throw cron.Recover can't
  426. // catch. cron.Recover then logs any panic and keeps the scheduler alive.
  427. s.cron = cron.New(
  428. cron.WithLocation(loc),
  429. cron.WithSeconds(),
  430. cron.WithChain(
  431. cron.SkipIfStillRunning(cron.DiscardLogger),
  432. cron.Recover(cron.PrintfLogger(cronPanicLogger{})),
  433. ),
  434. )
  435. s.cron.Start()
  436. // Wire the inbound-runtime manager once so InboundService can route
  437. // add/update/delete to either the local xray or a remote node panel.
  438. // The closures bridge into XrayService (which owns the running xray
  439. // process state) without forcing the runtime package to import service.
  440. runtime.SetManager(runtime.NewManager(runtime.LocalDeps{
  441. APIPort: func() int { return s.xrayService.GetXrayAPIPort() },
  442. SetNeedRestart: func() { s.xrayService.SetToNeedRestart() },
  443. }))
  444. runtime.GetManager().SetNodeEgressResolver(&s.settingService)
  445. // Supply the master client certificate for nodes in mtls mode. Issued lazily
  446. // from the node CA on first use; runtime stays free of a service import.
  447. runtime.SetMasterClientCertProvider(func() (tls.Certificate, error) {
  448. ck, err := s.settingService.EnsureMasterClientCert()
  449. if err != nil {
  450. return tls.Certificate{}, err
  451. }
  452. return tls.X509KeyPair(ck.CertPEM, ck.KeyPEM)
  453. })
  454. engine, err := s.initRouter()
  455. if err != nil {
  456. return err
  457. }
  458. certFile, err := s.settingService.GetCertFile()
  459. if err != nil {
  460. return err
  461. }
  462. keyFile, err := s.settingService.GetKeyFile()
  463. if err != nil {
  464. return err
  465. }
  466. listen, err := s.settingService.GetListen()
  467. if err != nil {
  468. return err
  469. }
  470. port, err := s.settingService.GetPort()
  471. if err != nil {
  472. return err
  473. }
  474. if envPort, configured, envErr := config.GetPortOverride(); configured {
  475. if envErr != nil {
  476. logger.Warning("Ignoring invalid XUI_PORT; using configured web port:", port, envErr)
  477. } else {
  478. port = envPort
  479. logger.Info("Using XUI_PORT override for web panel port:", port)
  480. }
  481. }
  482. listenAddr := net.JoinHostPort(listen, strconv.Itoa(port))
  483. listener, err := net.Listen("tcp", listenAddr)
  484. if err != nil {
  485. return err
  486. }
  487. if certFile != "" || keyFile != "" {
  488. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  489. if err == nil {
  490. c := &tls.Config{
  491. Certificates: []tls.Certificate{cert},
  492. }
  493. // Opt-in node mTLS: when a trust CA is configured, request and verify
  494. // client certs (VerifyClientCertIfGiven keeps browsers working). With
  495. // no CA the listener is unchanged.
  496. if pool, perr := s.settingService.NodeMtlsClientCAPool(); perr != nil {
  497. logger.Warning("node mTLS: failed to build client CA trust pool:", perr)
  498. } else if pool != nil {
  499. applyNodeMtls(c, pool)
  500. logger.Info("Node mTLS enabled: verifying client certificates for the node API")
  501. }
  502. listener = network.NewAutoHttpsListener(listener)
  503. listener = tls.NewListener(listener, c)
  504. logger.Info("Web server running HTTPS on", listener.Addr())
  505. } else {
  506. logger.Error("Error loading certificates:", err)
  507. logger.Info("Web server running HTTP on", listener.Addr())
  508. }
  509. } else {
  510. logger.Info("Web server running HTTP on", listener.Addr())
  511. }
  512. s.listener = listener
  513. s.httpServer = &http.Server{
  514. Handler: engine,
  515. ReadHeaderTimeout: 5 * time.Second,
  516. ReadTimeout: 30 * time.Second,
  517. WriteTimeout: 30 * time.Second,
  518. IdleTimeout: 120 * time.Second,
  519. }
  520. go func() {
  521. s.httpServer.Serve(listener)
  522. }()
  523. // Create event bus before startTask so jobs can use it
  524. s.bus = eventbus.New(eventbus.DefaultBufferSize)
  525. service.SetEventBus(s.bus)
  526. job.EventBus = s.bus
  527. tgbot.EventBus = s.bus
  528. // Wire xray crash callback BEFORE startTask so it's ready
  529. xray.OnCrash = func(err error) {
  530. if s.bus != nil {
  531. s.bus.Publish(eventbus.Event{
  532. Type: eventbus.EventXrayCrash,
  533. Data: err.Error(),
  534. })
  535. }
  536. }
  537. // Register email subscriber (always — it checks smtpEnable at runtime)
  538. emailService := email.NewEmailService(s.settingService)
  539. emailSub := email.NewSubscriber(s.settingService, emailService)
  540. s.bus.Subscribe("email-notifier", emailSub.HandleEvent)
  541. // Wire email service to controller for test endpoint
  542. controller.SetEmailService(emailService)
  543. // Wire Telegram test function to controller
  544. controller.SetTestTgFunc(func() error {
  545. if !s.tgbotService.IsRunning() {
  546. return fmt.Errorf("telegram bot is not running (check token and chat ID)")
  547. }
  548. if err := s.tgbotService.TestConnection(); err != nil {
  549. return fmt.Errorf("telegram API test failed: %w", err)
  550. }
  551. s.tgbotService.SendMsgToTgbotAdmins("✅ Test message from 3x-ui")
  552. return nil
  553. })
  554. controller.SetReloadTgbotFunc(func() {
  555. enabled, err := s.settingService.GetTgbotEnabled()
  556. if err != nil || !enabled {
  557. if s.tgbotService.IsRunning() {
  558. s.tgbotService.Stop()
  559. }
  560. if s.bus != nil {
  561. s.bus.Unsubscribe("tg-notifier")
  562. }
  563. return
  564. }
  565. // Start() stops any previous receiver first, so it is safe whether or not the bot is already running.
  566. tgBot := s.tgbotService.NewTgbot()
  567. if startErr := tgBot.Start(i18nFS); startErr != nil {
  568. logger.Warning("reload Telegram bot failed:", startErr)
  569. return
  570. }
  571. if s.bus != nil {
  572. s.bus.Subscribe("tg-notifier", s.tgbotService.HandleEvent)
  573. }
  574. })
  575. s.startTask(restartXray)
  576. if startTgBot {
  577. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  578. if (err == nil) && (isTgbotenabled) {
  579. tgBot := s.tgbotService.NewTgbot()
  580. tgBot.Start(i18nFS)
  581. // Subscribe Telegram notifications for event bus
  582. s.bus.Subscribe("tg-notifier", s.tgbotService.HandleEvent)
  583. }
  584. }
  585. return nil
  586. }
  587. // Stop gracefully shuts down the web server, stops Xray, cron jobs, and Telegram bot.
  588. func (s *Server) Stop() error {
  589. return s.stop(true, true)
  590. }
  591. func (s *Server) StopPanelOnly() error {
  592. return s.stop(false, true)
  593. }
  594. func (s *Server) stop(stopXray bool, stopTgBot bool) error {
  595. s.cancel()
  596. if stopXray {
  597. s.xrayService.StopXray()
  598. mtproto.GetManager().StopAll()
  599. }
  600. if s.cron != nil {
  601. s.cron.Stop()
  602. }
  603. if s.bus != nil {
  604. s.bus.Stop()
  605. }
  606. if err := service.PersistSystemMetrics(); err != nil {
  607. logger.Warning("persist system metrics on shutdown failed:", err)
  608. }
  609. if stopXray {
  610. service.StopTrafficWriter()
  611. }
  612. if stopTgBot && s.tgbotService.IsRunning() {
  613. s.tgbotService.Stop()
  614. }
  615. // Gracefully stop WebSocket hub
  616. if s.wsHub != nil {
  617. s.wsHub.Stop()
  618. }
  619. var err1 error
  620. var err2 error
  621. if s.httpServer != nil {
  622. shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
  623. defer shutdownCancel()
  624. err1 = s.httpServer.Shutdown(shutdownCtx)
  625. }
  626. if s.listener != nil {
  627. err2 = s.listener.Close()
  628. }
  629. return common.Combine(err1, err2)
  630. }
  631. // GetCtx returns the server's context for cancellation and deadline management.
  632. func (s *Server) GetCtx() context.Context {
  633. return s.ctx
  634. }
  635. // GetCron returns the server's cron scheduler instance.
  636. func (s *Server) GetCron() *cron.Cron {
  637. return s.cron
  638. }
  639. // GetWSHub returns the WebSocket hub instance.
  640. func (s *Server) GetWSHub() any {
  641. return s.wsHub
  642. }
  643. func (s *Server) RestartXray() error {
  644. return s.xrayService.RestartXray(true)
  645. }