1
0

web.go 14 KB

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