1
0

web.go 22 KB

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