1
0

web.go 15 KB

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