1
0

web.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. g.GET("/manifest.webmanifest", controller.ServePWAManifest)
  211. g.GET("/pwa-register.js", controller.ServePWARegister)
  212. g.GET("/service-worker.js", controller.ServePWAServiceWorker)
  213. g.GET("/icons/:name", controller.ServePWAIcon)
  214. s.index = controller.NewIndexController(g)
  215. s.panel = controller.NewXUIController(g)
  216. s.api = controller.NewAPIController(g)
  217. // Initialize WebSocket hub
  218. s.wsHub = websocket.NewHub()
  219. go s.wsHub.Run()
  220. // Initialize WebSocket controller — service owns per-connection pumps,
  221. // controller is HTTP-layer only (auth + upgrade).
  222. s.ws = controller.NewWebSocketController(panel.NewWebSocketService(s.wsHub))
  223. // Register WebSocket route with basePath (g already has basePath prefix)
  224. g.GET("/ws", s.ws.HandleWebSocket)
  225. // Chrome DevTools endpoint for debugging web apps
  226. engine.GET("/.well-known/appspecific/com.chrome.devtools.json", func(c *gin.Context) {
  227. c.JSON(http.StatusOK, gin.H{})
  228. })
  229. // Let unknown panel document routes fall back to the SPA shell, while every
  230. // non-SPA miss still returns a hard 404.
  231. engine.NoRoute(func(c *gin.Context) {
  232. if s.panel.HandleNoRoutePanelSPA(c) {
  233. return
  234. }
  235. c.AbortWithStatus(http.StatusNotFound)
  236. })
  237. return engine, nil
  238. }
  239. // Background-job cadences. Centralized here as the single tuning surface; the
  240. // values are unchanged from the historical hardcoded cron specs. Follow-up:
  241. // make these configurable via settings, add per-tick jitter to de-synchronize
  242. // fleet load, skip expensive jobs when no WebSocket clients are connected or
  243. // node/xray state is unchanged, and export per-job duration/skipped/error
  244. // counters.
  245. const (
  246. cadenceXrayRunning = "@every 1s"
  247. cadenceXrayRestart = "@every 30s"
  248. cadenceXrayTraffic = "@every 5s"
  249. cadenceMtproto = "@every 10s"
  250. cadenceClientIPScan = "@every 10s"
  251. cadenceNodeHeartbeat = "@every 5s"
  252. cadenceNodeTraffic = "@every 5s"
  253. cadenceOutboundSub = "@every 5m"
  254. cadenceReapOrphans = "@every 5m"
  255. cadenceXrayLogPrune = "@every 10m"
  256. cadenceCheckHash = "@every 2m"
  257. // cpu.Percent samples over a full minute (blocking), so a finer cadence just
  258. // stacks overlapping samplers; subscribers rate-limit alerts to 1/min anyway.
  259. cadenceCPUAlarm = "@every 1m"
  260. cadenceMemoryAlarm = "@every 1m"
  261. )
  262. // startTask schedules background jobs (Xray checks, traffic jobs, cron
  263. // jobs) which the panel relies on for periodic maintenance and monitoring.
  264. func (s *Server) startTask(restartXray bool, loc *time.Location) {
  265. if restartXray {
  266. err := s.xrayService.RestartXray(true)
  267. if err != nil {
  268. logger.Warning("start xray failed:", err)
  269. }
  270. }
  271. // Check whether xray is running every second
  272. _, _ = s.cron.AddJob(cadenceXrayRunning, job.NewCheckXrayRunningJob())
  273. // Check if xray needs to be restarted every 30 seconds
  274. _, _ = s.cron.AddFunc(cadenceXrayRestart, func() {
  275. s.xrayService.ApplyPendingRestart()
  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. _, _ = s.cron.AddJob(cadenceReapOrphans, job.NewReapSyncOrphansJob())
  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", loc))
  299. // Run once a day, midnight
  300. _, _ = s.cron.AddJob("@daily", job.NewPeriodicTrafficResetJob("daily", loc))
  301. // Run once a week, midnight between Sat/Sun
  302. _, _ = s.cron.AddJob("@weekly", job.NewPeriodicTrafficResetJob("weekly", loc))
  303. // Check monthly reset days at midnight
  304. _, _ = s.cron.AddJob("@daily", job.NewPeriodicTrafficResetJob("monthly", loc))
  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 network.ServeHTTP(s.httpServer, listener, "Web server")
  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, loc)
  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. }