1
0

web.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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. //
  39. // `all:` is required so files whose names start with `_` are NOT
  40. // silently excluded by go:embed's default rules. Vite/rolldown emits
  41. // `_plugin-vue_export-helper-<hash>.js` for the @vitejs/plugin-vue
  42. // runtime; without `all:` the chunk would be missing from the binary
  43. // at runtime → 404 → blank-page boot failure.
  44. //
  45. //go:embed all:dist
  46. var distFS embed.FS
  47. var startTime = time.Now()
  48. // wrapDistFS adapts the embedded `dist/` directory so it can be mounted
  49. // as the panel's `/assets/` static route. Vite emits its bundled JS/CSS
  50. // under `dist/assets/`; serving the FS rooted at `dist/assets` makes
  51. // `/assets/<hash>.js` URLs resolve directly.
  52. type wrapDistFS struct {
  53. embed.FS
  54. }
  55. func (f *wrapDistFS) Open(name string) (fs.File, error) {
  56. file, err := f.FS.Open("dist/assets/" + name)
  57. if err != nil {
  58. return nil, err
  59. }
  60. return &wrapAssetsFile{
  61. File: file,
  62. }, nil
  63. }
  64. type wrapAssetsFile struct {
  65. fs.File
  66. }
  67. func (f *wrapAssetsFile) Stat() (fs.FileInfo, error) {
  68. info, err := f.File.Stat()
  69. if err != nil {
  70. return nil, err
  71. }
  72. return &wrapAssetsFileInfo{
  73. FileInfo: info,
  74. }, nil
  75. }
  76. type wrapAssetsFileInfo struct {
  77. fs.FileInfo
  78. }
  79. func (f *wrapAssetsFileInfo) ModTime() time.Time {
  80. return startTime
  81. }
  82. // EmbeddedDist returns the embedded Vite-built frontend filesystem.
  83. // Controllers serve their HTML out of this FS via the dist-page handler
  84. // installed in NewEngine().
  85. func EmbeddedDist() embed.FS {
  86. return distFS
  87. }
  88. // Server represents the main web server for the 3x-ui panel with controllers, services, and scheduled jobs.
  89. type Server struct {
  90. httpServer *http.Server
  91. listener net.Listener
  92. index *controller.IndexController
  93. panel *controller.XUIController
  94. api *controller.APIController
  95. ws *controller.WebSocketController
  96. xrayService service.XrayService
  97. settingService service.SettingService
  98. tgbotService service.Tgbot
  99. customGeoService *service.CustomGeoService
  100. wsHub *websocket.Hub
  101. cron *cron.Cron
  102. ctx context.Context
  103. cancel context.CancelFunc
  104. }
  105. // NewServer creates a new web server instance with a cancellable context.
  106. func NewServer() *Server {
  107. ctx, cancel := context.WithCancel(context.Background())
  108. return &Server{
  109. ctx: ctx,
  110. cancel: cancel,
  111. }
  112. }
  113. func (s *Server) isDirectHTTPSConfigured() bool {
  114. certFile, certErr := s.settingService.GetCertFile()
  115. keyFile, keyErr := s.settingService.GetKeyFile()
  116. if certErr != nil || keyErr != nil || certFile == "" || keyFile == "" {
  117. return false
  118. }
  119. _, err := tls.LoadX509KeyPair(certFile, keyFile)
  120. return err == nil
  121. }
  122. // initRouter initializes Gin, registers middleware, templates, static
  123. // assets, controllers and returns the configured engine.
  124. func (s *Server) initRouter() (*gin.Engine, error) {
  125. if config.IsDebug() {
  126. gin.SetMode(gin.DebugMode)
  127. } else {
  128. gin.DefaultWriter = io.Discard
  129. gin.DefaultErrorWriter = io.Discard
  130. gin.SetMode(gin.ReleaseMode)
  131. }
  132. engine := gin.Default()
  133. directHTTPS := s.isDirectHTTPSConfigured()
  134. engine.Use(middleware.SecurityHeadersMiddleware(directHTTPS))
  135. webDomain, err := s.settingService.GetWebDomain()
  136. if err != nil {
  137. return nil, err
  138. }
  139. if webDomain != "" {
  140. engine.Use(middleware.DomainValidatorMiddleware(webDomain))
  141. }
  142. secret, err := s.settingService.GetSecret()
  143. if err != nil {
  144. return nil, err
  145. }
  146. basePath, err := s.settingService.GetBasePath()
  147. if err != nil {
  148. return nil, err
  149. }
  150. engine.Use(gzip.Gzip(gzip.DefaultCompression))
  151. assetsBasePath := basePath + "assets/"
  152. store := cookie.NewStore(secret)
  153. // Configure default session cookie options, including expiration (MaxAge)
  154. sessionOptions := sessions.Options{
  155. Path: basePath,
  156. HttpOnly: true,
  157. Secure: directHTTPS,
  158. SameSite: http.SameSiteLaxMode,
  159. }
  160. if sessionMaxAge, err := s.settingService.GetSessionMaxAge(); err == nil && sessionMaxAge > 0 {
  161. sessionOptions.MaxAge = sessionMaxAge * 60 // minutes -> seconds
  162. }
  163. store.Options(sessionOptions)
  164. engine.Use(sessions.Sessions("3x-ui", store))
  165. engine.Use(func(c *gin.Context) {
  166. c.Set("base_path", basePath)
  167. })
  168. engine.Use(func(c *gin.Context) {
  169. uri := c.Request.RequestURI
  170. if strings.HasPrefix(uri, assetsBasePath) {
  171. c.Header("Cache-Control", "max-age=31536000")
  172. }
  173. })
  174. // init i18n — still used by backend strings (errors, log messages,
  175. // SubPage menu entries) even though the Go template engine is gone.
  176. err = locale.InitLocalizer(i18nFS, &s.settingService)
  177. if err != nil {
  178. return nil, err
  179. }
  180. engine.Use(locale.LocalizerMiddleware())
  181. // `/assets/` serves the Vite-built bundle. In dev we pull from disk
  182. // so the Vite watcher's incremental rebuilds show up without
  183. // restarting the binary; in prod we serve the embedded dist FS
  184. // rooted at `dist/assets/`.
  185. if config.IsDebug() {
  186. engine.StaticFS(basePath+"assets", http.FS(os.DirFS("web/dist/assets")))
  187. } else {
  188. engine.StaticFS(basePath+"assets", http.FS(&wrapDistFS{FS: distFS}))
  189. }
  190. // Apply the redirect middleware (`/xui` to `/panel`)
  191. engine.Use(middleware.RedirectMiddleware(basePath))
  192. // Hand the embedded `dist/` filesystem to the controller package
  193. // before any HTML-serving controller is constructed. Phase 8
  194. // cutover: every HTML route reads from web/dist/ instead of
  195. // rendering a legacy template.
  196. controller.SetDistFS(distFS)
  197. g := engine.Group(basePath)
  198. s.index = controller.NewIndexController(g)
  199. s.panel = controller.NewXUIController(g)
  200. s.api = controller.NewAPIController(g, s.customGeoService)
  201. // Initialize WebSocket hub
  202. s.wsHub = websocket.NewHub()
  203. go s.wsHub.Run()
  204. // Initialize WebSocket controller — service owns per-connection pumps,
  205. // controller is HTTP-layer only (auth + upgrade).
  206. s.ws = controller.NewWebSocketController(service.NewWebSocketService(s.wsHub))
  207. // Register WebSocket route with basePath (g already has basePath prefix)
  208. g.GET("/ws", s.ws.HandleWebSocket)
  209. // Chrome DevTools endpoint for debugging web apps
  210. engine.GET("/.well-known/appspecific/com.chrome.devtools.json", func(c *gin.Context) {
  211. c.JSON(http.StatusOK, gin.H{})
  212. })
  213. // Add a catch-all route to handle undefined paths and return 404
  214. engine.NoRoute(func(c *gin.Context) {
  215. c.AbortWithStatus(http.StatusNotFound)
  216. })
  217. return engine, nil
  218. }
  219. // startTask schedules background jobs (Xray checks, traffic jobs, cron
  220. // jobs) which the panel relies on for periodic maintenance and monitoring.
  221. func (s *Server) startTask() {
  222. s.customGeoService.EnsureOnStartup()
  223. err := s.xrayService.RestartXray(true)
  224. if err != nil {
  225. logger.Warning("start xray failed:", err)
  226. }
  227. // Check whether xray is running every second
  228. s.cron.AddJob("@every 1s", job.NewCheckXrayRunningJob())
  229. // Check if xray needs to be restarted every 30 seconds
  230. s.cron.AddFunc("@every 30s", func() {
  231. if s.xrayService.IsNeedRestartAndSetFalse() {
  232. err := s.xrayService.RestartXray(false)
  233. if err != nil {
  234. logger.Error("restart xray failed:", err)
  235. }
  236. }
  237. })
  238. go func() {
  239. time.Sleep(time.Second * 5)
  240. // Statistics every 10 seconds, start the delay for 5 seconds for the first time, and staggered with the time to restart xray
  241. s.cron.AddJob("@every 10s", job.NewXrayTrafficJob())
  242. }()
  243. // check client ips from log file every 10 sec
  244. s.cron.AddJob("@every 10s", job.NewCheckClientIpJob())
  245. // Probe every enabled remote node every 10 sec
  246. s.cron.AddJob("@every 10s", job.NewNodeHeartbeatJob())
  247. // Pull traffic + online-clients from every online node every 10 sec
  248. // and merge absolute counters into the central DB.
  249. s.cron.AddJob("@every 10s", job.NewNodeTrafficSyncJob())
  250. // check client ips from log file every day
  251. s.cron.AddJob("@daily", job.NewClearLogsJob())
  252. // Inbound traffic reset jobs
  253. // Run every hour
  254. s.cron.AddJob("@hourly", job.NewPeriodicTrafficResetJob("hourly"))
  255. // Run once a day, midnight
  256. s.cron.AddJob("@daily", job.NewPeriodicTrafficResetJob("daily"))
  257. // Run once a week, midnight between Sat/Sun
  258. s.cron.AddJob("@weekly", job.NewPeriodicTrafficResetJob("weekly"))
  259. // Run once a month, midnight, first of month
  260. s.cron.AddJob("@monthly", job.NewPeriodicTrafficResetJob("monthly"))
  261. // LDAP sync scheduling
  262. if ldapEnabled, _ := s.settingService.GetLdapEnable(); ldapEnabled {
  263. runtime, err := s.settingService.GetLdapSyncCron()
  264. if err != nil || runtime == "" {
  265. runtime = "@every 1m"
  266. }
  267. j := job.NewLdapSyncJob()
  268. // job has zero-value services with method receivers that read settings on demand
  269. s.cron.AddJob(runtime, j)
  270. }
  271. // Make a traffic condition every day, 8:30
  272. var entry cron.EntryID
  273. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  274. if (err == nil) && (isTgbotenabled) {
  275. runtime, err := s.settingService.GetTgbotRuntime()
  276. if err != nil {
  277. logger.Warningf("Add NewStatsNotifyJob: failed to load runtime: %v; using default @daily", err)
  278. runtime = "@daily"
  279. } else if strings.TrimSpace(runtime) == "" {
  280. logger.Warning("Add NewStatsNotifyJob runtime is empty, using default @daily")
  281. runtime = "@daily"
  282. }
  283. logger.Infof("Tg notify enabled,run at %s", runtime)
  284. _, err = s.cron.AddJob(runtime, job.NewStatsNotifyJob())
  285. if err != nil {
  286. logger.Warningf("Add NewStatsNotifyJob: failed to schedule runtime %q: %v", runtime, err)
  287. return
  288. }
  289. // check for Telegram bot callback query hash storage reset
  290. s.cron.AddJob("@every 2m", job.NewCheckHashStorageJob())
  291. // Check CPU load and alarm to TgBot if threshold passes
  292. cpuThreshold, err := s.settingService.GetTgCpu()
  293. if (err == nil) && (cpuThreshold > 0) {
  294. s.cron.AddJob("@every 10s", job.NewCheckCpuJob())
  295. }
  296. } else {
  297. s.cron.Remove(entry)
  298. }
  299. }
  300. // Start initializes and starts the web server with configured settings, routes, and background jobs.
  301. func (s *Server) Start() (err error) {
  302. // This is an anonymous function, no function name
  303. defer func() {
  304. if err != nil {
  305. s.Stop()
  306. }
  307. }()
  308. loc, err := s.settingService.GetTimeLocation()
  309. if err != nil {
  310. return err
  311. }
  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. }
  368. go func() {
  369. s.httpServer.Serve(listener)
  370. }()
  371. s.startTask()
  372. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  373. if (err == nil) && (isTgbotenabled) {
  374. tgBot := s.tgbotService.NewTgbot()
  375. tgBot.Start(i18nFS)
  376. }
  377. return nil
  378. }
  379. // Stop gracefully shuts down the web server, stops Xray, cron jobs, and Telegram bot.
  380. func (s *Server) Stop() error {
  381. s.cancel()
  382. s.xrayService.StopXray()
  383. if s.cron != nil {
  384. s.cron.Stop()
  385. }
  386. if s.tgbotService.IsRunning() {
  387. s.tgbotService.Stop()
  388. }
  389. // Gracefully stop WebSocket hub
  390. if s.wsHub != nil {
  391. s.wsHub.Stop()
  392. }
  393. var err1 error
  394. var err2 error
  395. if s.httpServer != nil {
  396. err1 = s.httpServer.Shutdown(s.ctx)
  397. }
  398. if s.listener != nil {
  399. err2 = s.listener.Close()
  400. }
  401. return common.Combine(err1, err2)
  402. }
  403. // GetCtx returns the server's context for cancellation and deadline management.
  404. func (s *Server) GetCtx() context.Context {
  405. return s.ctx
  406. }
  407. // GetCron returns the server's cron scheduler instance.
  408. func (s *Server) GetCron() *cron.Cron {
  409. return s.cron
  410. }
  411. // GetWSHub returns the WebSocket hub instance.
  412. func (s *Server) GetWSHub() any {
  413. return s.wsHub
  414. }
  415. func (s *Server) RestartXray() error {
  416. return s.xrayService.RestartXray(true)
  417. }