1
0

web.go 27 KB

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