web.go 27 KB

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