web.go 14 KB

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