1
0

web.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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. "io"
  9. "io/fs"
  10. "net"
  11. "net/http"
  12. "os"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/mhsanaei/3x-ui/v3/internal/config"
  17. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  18. "github.com/mhsanaei/3x-ui/v3/internal/mtproto"
  19. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  20. "github.com/mhsanaei/3x-ui/v3/internal/web/controller"
  21. "github.com/mhsanaei/3x-ui/v3/internal/web/job"
  22. "github.com/mhsanaei/3x-ui/v3/internal/web/locale"
  23. "github.com/mhsanaei/3x-ui/v3/internal/web/middleware"
  24. "github.com/mhsanaei/3x-ui/v3/internal/web/network"
  25. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  26. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  27. "github.com/mhsanaei/3x-ui/v3/internal/web/service/panel"
  28. "github.com/mhsanaei/3x-ui/v3/internal/web/service/tgbot"
  29. "github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
  30. "github.com/gin-contrib/gzip"
  31. "github.com/gin-contrib/sessions"
  32. "github.com/gin-contrib/sessions/cookie"
  33. "github.com/gin-gonic/gin"
  34. "github.com/robfig/cron/v3"
  35. )
  36. //go:embed translation/*
  37. var i18nFS embed.FS
  38. // distFS embeds the Vite-built frontend (internal/web/dist/). Every user-facing
  39. // HTML route is served straight out of this FS — the legacy Go
  40. // templates and `web/assets/` tree are gone post-Phase 8.
  41. //go:embed all:dist
  42. var distFS embed.FS
  43. var startTime = time.Now()
  44. // wrapDistFS adapts the embedded `dist/` directory so it can be mounted
  45. // as the panel's `/assets/` static route. Vite emits its bundled JS/CSS
  46. // under `dist/assets/`; serving the FS rooted at `dist/assets` makes
  47. // `/assets/<hash>.js` URLs resolve directly.
  48. type wrapDistFS struct {
  49. embed.FS
  50. }
  51. func (f *wrapDistFS) Open(name string) (fs.File, error) {
  52. file, err := f.FS.Open("dist/assets/" + name)
  53. if err != nil {
  54. return nil, err
  55. }
  56. return &wrapAssetsFile{
  57. File: file,
  58. }, nil
  59. }
  60. type wrapAssetsFile struct {
  61. fs.File
  62. }
  63. func (f *wrapAssetsFile) Stat() (fs.FileInfo, error) {
  64. info, err := f.File.Stat()
  65. if err != nil {
  66. return nil, err
  67. }
  68. return &wrapAssetsFileInfo{
  69. FileInfo: info,
  70. }, nil
  71. }
  72. type wrapAssetsFileInfo struct {
  73. fs.FileInfo
  74. }
  75. func (f *wrapAssetsFileInfo) ModTime() time.Time {
  76. return startTime
  77. }
  78. // EmbeddedDist returns the embedded Vite-built frontend filesystem.
  79. // Controllers serve their HTML out of this FS via the dist-page handler
  80. // installed in NewEngine().
  81. func EmbeddedDist() embed.FS {
  82. return distFS
  83. }
  84. // Server represents the main web server for the 3x-ui panel with controllers, services, and scheduled jobs.
  85. type Server struct {
  86. httpServer *http.Server
  87. listener net.Listener
  88. index *controller.IndexController
  89. panel *controller.XUIController
  90. api *controller.APIController
  91. ws *controller.WebSocketController
  92. xrayService service.XrayService
  93. settingService service.SettingService
  94. tgbotService tgbot.Tgbot
  95. wsHub *websocket.Hub
  96. cron *cron.Cron
  97. ctx context.Context
  98. cancel context.CancelFunc
  99. }
  100. // NewServer creates a new web server instance with a cancellable context.
  101. func NewServer() *Server {
  102. ctx, cancel := context.WithCancel(context.Background())
  103. return &Server{
  104. ctx: ctx,
  105. cancel: cancel,
  106. }
  107. }
  108. func (s *Server) isDirectHTTPSConfigured() bool {
  109. certFile, certErr := s.settingService.GetCertFile()
  110. keyFile, keyErr := s.settingService.GetKeyFile()
  111. if certErr != nil || keyErr != nil || certFile == "" || keyFile == "" {
  112. return false
  113. }
  114. _, err := tls.LoadX509KeyPair(certFile, keyFile)
  115. return err == nil
  116. }
  117. // initRouter initializes Gin, registers middleware, templates, static
  118. // assets, controllers and returns the configured engine.
  119. func (s *Server) initRouter() (*gin.Engine, error) {
  120. if config.IsDebug() {
  121. gin.SetMode(gin.DebugMode)
  122. } else {
  123. gin.DefaultWriter = io.Discard
  124. gin.DefaultErrorWriter = io.Discard
  125. gin.SetMode(gin.ReleaseMode)
  126. }
  127. engine := gin.Default()
  128. directHTTPS := s.isDirectHTTPSConfigured()
  129. sendHSTS := directHTTPS && !config.IsSkipHSTS()
  130. engine.Use(middleware.SecurityHeadersMiddleware(sendHSTS))
  131. // Cap request bodies on state-changing requests so a stolen session/API
  132. // token or a buggy client can't force large allocations or long DB
  133. // transactions via bulk create/attach/import endpoints. GET/HEAD/OPTIONS
  134. // carry no body and are left untouched. importDB restores a full SQLite
  135. // backup that legitimately exceeds the cap, so it's exempt. Follow-up: make
  136. // the limit a setting.
  137. const maxRequestBodyBytes = 10 << 20 // 10 MiB
  138. engine.Use(middleware.MaxBodyBytes(maxRequestBodyBytes, "/panel/api/server/importDB"))
  139. webDomain, err := s.settingService.GetWebDomain()
  140. if err != nil {
  141. return nil, err
  142. }
  143. if webDomain != "" {
  144. engine.Use(middleware.DomainValidatorMiddleware(webDomain))
  145. }
  146. secret, err := s.settingService.GetSecret()
  147. if err != nil {
  148. return nil, err
  149. }
  150. basePath, err := s.settingService.GetBasePath()
  151. if err != nil {
  152. return nil, err
  153. }
  154. engine.Use(gzip.Gzip(gzip.DefaultCompression))
  155. assetsBasePath := basePath + "assets/"
  156. store := cookie.NewStore(secret)
  157. // Configure default session cookie options, including expiration (MaxAge)
  158. sessionOptions := sessions.Options{
  159. Path: basePath,
  160. HttpOnly: true,
  161. Secure: directHTTPS,
  162. SameSite: http.SameSiteLaxMode,
  163. }
  164. if sessionMaxAge, err := s.settingService.GetSessionMaxAge(); err == nil && sessionMaxAge > 0 {
  165. sessionOptions.MaxAge = sessionMaxAge * 60 // minutes -> seconds
  166. }
  167. store.Options(sessionOptions)
  168. engine.Use(sessions.Sessions("3x-ui", store))
  169. engine.Use(func(c *gin.Context) {
  170. c.Set("base_path", basePath)
  171. })
  172. engine.Use(func(c *gin.Context) {
  173. uri := c.Request.RequestURI
  174. if strings.HasPrefix(uri, assetsBasePath) {
  175. c.Header("Cache-Control", "max-age=31536000")
  176. }
  177. })
  178. // init i18n — still used by backend strings (errors, log messages,
  179. // SubPage menu entries) even though the Go template engine is gone.
  180. err = locale.InitLocalizer(i18nFS, &s.settingService)
  181. if err != nil {
  182. return nil, err
  183. }
  184. engine.Use(locale.LocalizerMiddleware())
  185. // `/assets/` serves the Vite-built bundle. In dev we pull from disk
  186. // so the Vite watcher's incremental rebuilds show up without
  187. // restarting the binary; in prod we serve the embedded dist FS
  188. // rooted at `dist/assets/`.
  189. if config.IsDebug() {
  190. engine.StaticFS(basePath+"assets", http.FS(os.DirFS("internal/web/dist/assets")))
  191. } else {
  192. engine.StaticFS(basePath+"assets", http.FS(&wrapDistFS{FS: distFS}))
  193. }
  194. // Hand the embedded `dist/` filesystem to the controller package
  195. // before any HTML-serving controller is constructed. Phase 8
  196. // cutover: every HTML route reads from internal/web/dist/ instead of
  197. // rendering a legacy template.
  198. controller.SetDistFS(distFS)
  199. g := engine.Group(basePath)
  200. s.index = controller.NewIndexController(g)
  201. s.panel = controller.NewXUIController(g)
  202. g.GET("/panel/api/openapi.json", controller.ServeOpenAPISpec)
  203. s.api = controller.NewAPIController(g)
  204. // Initialize WebSocket hub
  205. s.wsHub = websocket.NewHub()
  206. go s.wsHub.Run()
  207. // Initialize WebSocket controller — service owns per-connection pumps,
  208. // controller is HTTP-layer only (auth + upgrade).
  209. s.ws = controller.NewWebSocketController(panel.NewWebSocketService(s.wsHub))
  210. // Register WebSocket route with basePath (g already has basePath prefix)
  211. g.GET("/ws", s.ws.HandleWebSocket)
  212. // Chrome DevTools endpoint for debugging web apps
  213. engine.GET("/.well-known/appspecific/com.chrome.devtools.json", func(c *gin.Context) {
  214. c.JSON(http.StatusOK, gin.H{})
  215. })
  216. // Add a catch-all route to handle undefined paths and return 404
  217. engine.NoRoute(func(c *gin.Context) {
  218. c.AbortWithStatus(http.StatusNotFound)
  219. })
  220. return engine, nil
  221. }
  222. // Background-job cadences. Centralized here as the single tuning surface; the
  223. // values are unchanged from the historical hardcoded cron specs. Follow-up:
  224. // make these configurable via settings, add per-tick jitter to de-synchronize
  225. // fleet load, skip expensive jobs when no WebSocket clients are connected or
  226. // node/xray state is unchanged, and export per-job duration/skipped/error
  227. // counters.
  228. const (
  229. cadenceXrayRunning = "@every 1s"
  230. cadenceXrayRestart = "@every 30s"
  231. cadenceXrayTraffic = "@every 5s"
  232. cadenceMtproto = "@every 10s"
  233. cadenceClientIPScan = "@every 10s"
  234. cadenceNodeHeartbeat = "@every 5s"
  235. cadenceNodeTraffic = "@every 5s"
  236. cadenceOutboundSub = "@every 5m"
  237. cadenceCheckHash = "@every 2m"
  238. cadenceCPUAlarm = "@every 10s"
  239. )
  240. // startTask schedules background jobs (Xray checks, traffic jobs, cron
  241. // jobs) which the panel relies on for periodic maintenance and monitoring.
  242. func (s *Server) startTask(restartXray bool) {
  243. if restartXray {
  244. err := s.xrayService.RestartXray(true)
  245. if err != nil {
  246. logger.Warning("start xray failed:", err)
  247. }
  248. }
  249. // Check whether xray is running every second
  250. s.cron.AddJob(cadenceXrayRunning, job.NewCheckXrayRunningJob())
  251. // Check if xray needs to be restarted every 30 seconds
  252. s.cron.AddFunc(cadenceXrayRestart, func() {
  253. if s.xrayService.IsNeedRestartAndSetFalse() {
  254. err := s.xrayService.RestartXray(false)
  255. if err != nil {
  256. logger.Error("restart xray failed:", err)
  257. }
  258. }
  259. })
  260. go func() {
  261. time.Sleep(time.Second * 5)
  262. s.cron.AddJob(cadenceXrayTraffic, job.NewXrayTrafficJob())
  263. }()
  264. // Reconcile mtproto (mtg) sidecars and scrape their traffic
  265. mtJob := job.NewMtprotoJob()
  266. s.cron.AddJob(cadenceMtproto, mtJob)
  267. go mtJob.Run()
  268. // check client ips from log file every 10 sec
  269. s.cron.AddJob(cadenceClientIPScan, job.NewCheckClientIpJob())
  270. s.cron.AddJob(cadenceNodeHeartbeat, job.NewNodeHeartbeatJob())
  271. s.cron.AddJob(cadenceNodeTraffic, job.NewNodeTrafficSyncJob())
  272. // Outbound subscription auto-refresh (respects per-sub updateInterval)
  273. s.cron.AddJob(cadenceOutboundSub, job.NewOutboundSubscriptionJob())
  274. // check client ips from log file every day
  275. s.cron.AddJob("@daily", job.NewClearLogsJob())
  276. s.cron.AddJob("@hourly", job.NewWarpIpJob())
  277. // Inbound traffic reset jobs
  278. // Run every hour
  279. s.cron.AddJob("@hourly", job.NewPeriodicTrafficResetJob("hourly"))
  280. // Run once a day, midnight
  281. s.cron.AddJob("@daily", job.NewPeriodicTrafficResetJob("daily"))
  282. // Run once a week, midnight between Sat/Sun
  283. s.cron.AddJob("@weekly", job.NewPeriodicTrafficResetJob("weekly"))
  284. // Run once a month, midnight, first of month
  285. s.cron.AddJob("@monthly", job.NewPeriodicTrafficResetJob("monthly"))
  286. // LDAP sync scheduling
  287. if ldapEnabled, _ := s.settingService.GetLdapEnable(); ldapEnabled {
  288. runtime, err := s.settingService.GetLdapSyncCron()
  289. if err != nil || runtime == "" {
  290. runtime = "@every 1m"
  291. }
  292. j := job.NewLdapSyncJob()
  293. // job has zero-value services with method receivers that read settings on demand
  294. s.cron.AddJob(runtime, j)
  295. }
  296. // Make a traffic condition every day, 8:30
  297. var entry cron.EntryID
  298. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  299. if (err == nil) && (isTgbotenabled) {
  300. runtime, err := s.settingService.GetTgbotRuntime()
  301. if err != nil {
  302. logger.Warningf("Add NewStatsNotifyJob: failed to load runtime: %v; using default @daily", err)
  303. runtime = "@daily"
  304. } else if strings.TrimSpace(runtime) == "" {
  305. logger.Warning("Add NewStatsNotifyJob runtime is empty, using default @daily")
  306. runtime = "@daily"
  307. }
  308. logger.Infof("Tg notify enabled,run at %s", runtime)
  309. _, err = s.cron.AddJob(runtime, job.NewStatsNotifyJob())
  310. if err != nil {
  311. logger.Warningf("Add NewStatsNotifyJob: failed to schedule runtime %q: %v", runtime, err)
  312. return
  313. }
  314. // check for Telegram bot callback query hash storage reset
  315. s.cron.AddJob(cadenceCheckHash, job.NewCheckHashStorageJob())
  316. // Check CPU load and alarm to TgBot if threshold passes
  317. cpuThreshold, err := s.settingService.GetTgCpu()
  318. if (err == nil) && (cpuThreshold > 0) {
  319. s.cron.AddJob(cadenceCPUAlarm, job.NewCheckCpuJob())
  320. }
  321. } else {
  322. s.cron.Remove(entry)
  323. }
  324. }
  325. // Start initializes and starts the web server with configured settings, routes, and background jobs.
  326. func (s *Server) Start() (err error) {
  327. return s.start(true, true)
  328. }
  329. func (s *Server) StartPanelOnly() (err error) {
  330. return s.start(false, true)
  331. }
  332. func (s *Server) start(restartXray bool, startTgBot bool) (err error) {
  333. // This is an anonymous function, no function name
  334. defer func() {
  335. if err != nil {
  336. s.Stop()
  337. }
  338. }()
  339. loc, err := s.settingService.GetTimeLocation()
  340. if err != nil {
  341. return err
  342. }
  343. service.StartTrafficWriter()
  344. s.cron = cron.New(cron.WithLocation(loc), cron.WithSeconds())
  345. s.cron.Start()
  346. // Wire the inbound-runtime manager once so InboundService can route
  347. // add/update/delete to either the local xray or a remote node panel.
  348. // The closures bridge into XrayService (which owns the running xray
  349. // process state) without forcing the runtime package to import service.
  350. runtime.SetManager(runtime.NewManager(runtime.LocalDeps{
  351. APIPort: func() int { return s.xrayService.GetXrayAPIPort() },
  352. SetNeedRestart: func() { s.xrayService.SetToNeedRestart() },
  353. }))
  354. runtime.GetManager().SetNodeEgressResolver(&s.settingService)
  355. engine, err := s.initRouter()
  356. if err != nil {
  357. return err
  358. }
  359. certFile, err := s.settingService.GetCertFile()
  360. if err != nil {
  361. return err
  362. }
  363. keyFile, err := s.settingService.GetKeyFile()
  364. if err != nil {
  365. return err
  366. }
  367. listen, err := s.settingService.GetListen()
  368. if err != nil {
  369. return err
  370. }
  371. port, err := s.settingService.GetPort()
  372. if err != nil {
  373. return err
  374. }
  375. if envPort, configured, envErr := config.GetPortOverride(); configured {
  376. if envErr != nil {
  377. logger.Warning("Ignoring invalid XUI_PORT; using configured web port:", port, envErr)
  378. } else {
  379. port = envPort
  380. logger.Info("Using XUI_PORT override for web panel port:", port)
  381. }
  382. }
  383. listenAddr := net.JoinHostPort(listen, strconv.Itoa(port))
  384. listener, err := net.Listen("tcp", listenAddr)
  385. if err != nil {
  386. return err
  387. }
  388. if certFile != "" || keyFile != "" {
  389. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  390. if err == nil {
  391. c := &tls.Config{
  392. Certificates: []tls.Certificate{cert},
  393. }
  394. listener = network.NewAutoHttpsListener(listener)
  395. listener = tls.NewListener(listener, c)
  396. logger.Info("Web server running HTTPS on", listener.Addr())
  397. } else {
  398. logger.Error("Error loading certificates:", err)
  399. logger.Info("Web server running HTTP on", listener.Addr())
  400. }
  401. } else {
  402. logger.Info("Web server running HTTP on", listener.Addr())
  403. }
  404. s.listener = listener
  405. s.httpServer = &http.Server{
  406. Handler: engine,
  407. ReadHeaderTimeout: 5 * time.Second,
  408. ReadTimeout: 30 * time.Second,
  409. WriteTimeout: 30 * time.Second,
  410. IdleTimeout: 120 * time.Second,
  411. }
  412. go func() {
  413. s.httpServer.Serve(listener)
  414. }()
  415. s.startTask(restartXray)
  416. if startTgBot {
  417. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  418. if (err == nil) && (isTgbotenabled) {
  419. tgBot := s.tgbotService.NewTgbot()
  420. tgBot.Start(i18nFS)
  421. }
  422. }
  423. return nil
  424. }
  425. // Stop gracefully shuts down the web server, stops Xray, cron jobs, and Telegram bot.
  426. func (s *Server) Stop() error {
  427. return s.stop(true, true)
  428. }
  429. func (s *Server) StopPanelOnly() error {
  430. return s.stop(false, true)
  431. }
  432. func (s *Server) stop(stopXray bool, stopTgBot bool) error {
  433. s.cancel()
  434. if stopXray {
  435. s.xrayService.StopXray()
  436. mtproto.GetManager().StopAll()
  437. }
  438. if s.cron != nil {
  439. s.cron.Stop()
  440. }
  441. if err := service.PersistSystemMetrics(); err != nil {
  442. logger.Warning("persist system metrics on shutdown failed:", err)
  443. }
  444. if stopXray {
  445. service.StopTrafficWriter()
  446. }
  447. if stopTgBot && s.tgbotService.IsRunning() {
  448. s.tgbotService.Stop()
  449. }
  450. // Gracefully stop WebSocket hub
  451. if s.wsHub != nil {
  452. s.wsHub.Stop()
  453. }
  454. var err1 error
  455. var err2 error
  456. if s.httpServer != nil {
  457. shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
  458. defer shutdownCancel()
  459. err1 = s.httpServer.Shutdown(shutdownCtx)
  460. }
  461. if s.listener != nil {
  462. err2 = s.listener.Close()
  463. }
  464. return common.Combine(err1, err2)
  465. }
  466. // GetCtx returns the server's context for cancellation and deadline management.
  467. func (s *Server) GetCtx() context.Context {
  468. return s.ctx
  469. }
  470. // GetCron returns the server's cron scheduler instance.
  471. func (s *Server) GetCron() *cron.Cron {
  472. return s.cron
  473. }
  474. // GetWSHub returns the WebSocket hub instance.
  475. func (s *Server) GetWSHub() any {
  476. return s.wsHub
  477. }
  478. func (s *Server) RestartXray() error {
  479. return s.xrayService.RestartXray(true)
  480. }